plum
git clone https://git.pyrossh.dev/plum
A statically typed, imperative programming language inspired by rust, python
08d0036
— Peter John
2026-11-09T18:40:41+05:30
Traits: inheritance, downcasts to a trait, statics, and @typeName
- compiler/checker/src/infer.rs +5 -0
- compiler/checker/src/patterns.rs +41 -11
- compiler/checker/src/traits.rs +161 -13
- compiler/checker/tests/checker/traits_tests.rs +160 -3
- compiler/core/src/ast.rs +7 -3
- compiler/core/src/compile_builtins.rs +68 -0
- compiler/core/src/lib.rs +1 -0
- compiler/core/src/parser.rs +22 -1
- compiler/core/src/simplify.rs +17 -1
- compiler/core/src/trait_defaults.rs +138 -3
- compiler/core/tests/core/formatter_test.rs +20 -0
- compiler/core/tests/core/traits_parse_test.rs +40 -2
- compiler/tooling/tree-sitter-plum/grammar.js +22 -1
- compiler/tooling/tree-sitter-plum/queries/plum/format.scm +2 -0
- 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 +104 -0
- compiler/wasm-codegen/src/emit.rs +14 -5
- compiler/wasm-codegen/src/fnbody.rs +2 -2
- compiler/wasm-codegen/src/intrinsics.rs +21 -0
- compiler/wasm-codegen/src/matching.rs +10 -12
- compiler/wasm-codegen/src/traits.rs +51 -8
- compiler/wasm-codegen/tests/wasm_codegen/fusion_alloc_test.rs +94 -0
- docs/language.md +53 -2
- std/Str.plum +7 -0
- tests/traits/inlined_arg_pin.plum +31 -0
- tests/traits/statics_and_type_name.plum +48 -0
- tests/traits/supertraits.plum +88 -0
compiler/checker/src/infer.rs
CHANGED
|
@@ -444,6 +444,11 @@ pub(crate) fn inferExprInner(
|
|
|
444
444
|
Ok(substVars(&tt, &binds))
|
|
445
445
|
}
|
|
446
446
|
ast::Expr { kind: ast::ExprKind::FnCall(call), .. } => {
|
|
447
|
+
// `@name(..)` left as a call by the parser: an unknown built-in, or a known one
|
|
448
|
+
// with the wrong arguments (`plum_core::compile_builtins`).
|
|
449
|
+
if let Some(e) = plum_core::compile_builtins::error(&call.name) {
|
|
450
|
+
return Err(e);
|
|
451
|
+
}
|
|
447
452
|
// `Int(x)`/`Float(x)`/`Byte(x)` are builtin numeric conversions, not
|
|
448
453
|
// ordinary calls — handled here so `y = Float(x)` unifies against
|
|
449
454
|
// `TFloat` rather than falling through to the permissive
|
compiler/checker/src/patterns.rs
CHANGED
|
@@ -90,17 +90,20 @@ pub(crate) fn checkPattern(
|
|
|
90
90
|
Ok(())
|
|
91
91
|
}
|
|
92
92
|
}
|
|
93
|
-
ast::CasePattern::As { ty, name } => {
|
|
93
|
+
ast::CasePattern::As { ty, name, args } => {
|
|
94
94
|
let subject = resolveRecorded(subject_ty);
|
|
95
|
-
let target = downcastTarget(ty, &subject, ctx)?;
|
|
95
|
+
let target = downcastTarget(ty, args, &subject, ctx)?;
|
|
96
|
+
let ty = &if args.is_empty() { ty.clone() } else { target.to_string() };
|
|
96
97
|
if isTraitObject(&subject) {
|
|
97
98
|
if isTraitObject(&target) {
|
|
99
|
+
// A downcast to a trait: a value of any type that is both.
|
|
100
|
+
if !currentTraits().mayBeBoth(&subject, &target) {
|
|
98
|
-
|
|
101
|
+
let what = if target.to_string() == *ty { String::new() } else { format!(" ({ty} is {target} here)") };
|
|
99
|
-
|
|
102
|
+
return Err(format!(
|
|
100
|
-
|
|
103
|
+
"`{ty} as {name}`{what}: no type is both a {subject} and a {target}, so a {subject} is never a {target}"
|
|
101
|
-
|
|
104
|
+
));
|
|
102
|
-
|
|
105
|
+
}
|
|
103
|
-
if !matches!(target, PlumType::TParam(_)) && !implementsTrait(&target, &subject) {
|
|
106
|
+
} else if !matches!(target, PlumType::TParam(_)) && !implementsTrait(&target, &subject) {
|
|
104
107
|
return Err(format!("`{ty} as {name}`: {ty} does not implement {subject}, so a {subject} is never a {ty}"));
|
|
105
108
|
}
|
|
106
109
|
} else if !matches!(subject, PlumType::TVar(_) | PlumType::TParam(_)) && subject != target {
|
|
@@ -144,9 +147,36 @@ pub(crate) fn checkPattern(
|
|
|
144
147
|
}
|
|
145
148
|
}
|
|
146
149
|
|
|
147
|
-
/// The type a downcast pattern `ty as name` binds: a declared non-generic type,
|
|
150
|
+
/// The type a downcast pattern `ty as name` binds: a declared non-generic type, a trait
|
|
148
|
-
/// parameter in scope (its type in an instantiated body)
|
|
151
|
+
/// object, a generic parameter in scope (its type in an instantiated body), or a generic
|
|
152
|
+
/// type with the arguments written (`Box[Msg] as b`, `Screen[S, M] as s`) or, for an
|
|
153
|
+
/// implementer, those the trait object gives it.
|
|
149
|
-
fn downcastTarget(ty: &str, subject: &PlumType, ctx: &CheckCtx) -> Result<PlumType, String> {
|
|
154
|
+
fn downcastTarget(ty: &str, args: &[ast::Type], subject: &PlumType, ctx: &CheckCtx) -> Result<PlumType, String> {
|
|
155
|
+
if !args.is_empty() {
|
|
156
|
+
let written = ast::Type { name: ty.to_string(), generics: args.to_vec() };
|
|
157
|
+
let shown = plumTypeFromAstG(&written);
|
|
158
|
+
let want = if let Some(t) = currentTraits().traits.get(ty) {
|
|
159
|
+
t.generics.len()
|
|
160
|
+
} else if let Some(info) = ctx.enum_variants.values().find(|i| i.enum_name == ty) {
|
|
161
|
+
info.generics.len()
|
|
162
|
+
} else if withCheck(|s| s.scope.borrow().isGeneric(ty)) {
|
|
163
|
+
return Err(format!("`{shown} as ..`: {ty} is a type parameter and takes no type arguments"));
|
|
164
|
+
} else {
|
|
165
|
+
markResolution();
|
|
166
|
+
return Err(format!("`{shown} as ..`: unknown type {ty}"));
|
|
167
|
+
};
|
|
168
|
+
if want != args.len() {
|
|
169
|
+
return Err(format!("`{shown} as ..`: {ty} takes {want} type argument(s), got {}", args.len()));
|
|
170
|
+
}
|
|
171
|
+
return Ok(plumTypeFromAstG(&written));
|
|
172
|
+
}
|
|
173
|
+
if let Some(t) = currentTraits().traits.get(ty).filter(|t| !t.generics.is_empty()) {
|
|
174
|
+
return Err(format!(
|
|
175
|
+
"`{ty} as ..`: the trait {ty} takes type arguments ({}); write them: `{ty}[{}] as ..`",
|
|
176
|
+
t.generics.join(", "),
|
|
177
|
+
t.generics.join(", ")
|
|
178
|
+
));
|
|
179
|
+
}
|
|
150
180
|
if withCheck(|s| s.scope.borrow().isGeneric(ty)) {
|
|
151
181
|
if let Some(t) = typeParamBinding(ty) {
|
|
152
182
|
return Ok(t);
|
compiler/checker/src/traits.rs
CHANGED
|
@@ -26,6 +26,10 @@ pub struct TraitMethodInfo {
|
|
|
26
26
|
/// A call on a trait object runs each implementer's `$dyn` copy of the method
|
|
27
27
|
/// (`plum_core::trait_defaults::needsDynCopy`: `Self` inside another type).
|
|
28
28
|
pub dyn_copy: bool,
|
|
29
|
+
/// The supertrait it comes from (`Actor` for `key` in `trait Screen[S, M] is
|
|
30
|
+
/// Actor[M]`), `None` for the trait's own methods. An inherited method's `sig` has the
|
|
31
|
+
/// supertrait's parameters as the subtrait's arguments for them.
|
|
32
|
+
pub from: Option<String>,
|
|
29
33
|
pub line: usize,
|
|
30
34
|
pub column: usize,
|
|
31
35
|
}
|
|
@@ -37,6 +41,10 @@ pub struct TraitInfo {
|
|
|
37
41
|
pub line: usize,
|
|
38
42
|
pub column: usize,
|
|
39
43
|
pub generics: Vec<String>,
|
|
44
|
+
/// `trait Screen[S, M] is Actor[M]`: its direct supertraits, the trait's generics as
|
|
45
|
+
/// `TParam`s.
|
|
46
|
+
pub supers: Vec<PlumType>,
|
|
47
|
+
/// Its own methods, then those it inherits from its supertraits (transitively).
|
|
40
48
|
pub methods: Vec<TraitMethodInfo>,
|
|
41
49
|
}
|
|
42
50
|
|
|
@@ -76,6 +84,62 @@ impl Traits {
|
|
|
76
84
|
self.traits.contains_key(name)
|
|
77
85
|
}
|
|
78
86
|
|
|
87
|
+
/// Every supertrait of the trait object `tr`, transitively, with `tr`'s arguments
|
|
88
|
+
/// (`Screen[State, Msg]` with `trait Screen[S, M] is Actor[M]`: `[Actor[Msg]]`).
|
|
89
|
+
pub fn supertraitsOf(&self, tr: &PlumType) -> Vec<PlumType> {
|
|
90
|
+
let mut out: Vec<PlumType> = Vec::new();
|
|
91
|
+
let mut todo = vec![tr.clone()];
|
|
92
|
+
while let Some(t) = todo.pop() {
|
|
93
|
+
let Some((name, args)) = self.traitObject(&t) else { continue };
|
|
94
|
+
let Some(info) = self.traits.get(name) else { continue };
|
|
95
|
+
if info.generics.len() != args.len() {
|
|
96
|
+
continue;
|
|
97
|
+
}
|
|
98
|
+
let s = appSubst(&info.generics, args);
|
|
99
|
+
for sup in &info.supers {
|
|
100
|
+
let sup = types::substitute(sup, &s);
|
|
101
|
+
if !out.contains(&sup) && out.len() < 64 {
|
|
102
|
+
out.push(sup.clone());
|
|
103
|
+
todo.push(sup);
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
out
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/// Whether a value of the trait object `a` may be a `b` (the downcast `b as x` on an
|
|
111
|
+
/// `a`): `b` extends `a`, or some type implements both.
|
|
112
|
+
pub fn mayBeBoth(&self, a: &PlumType, b: &PlumType) -> bool {
|
|
113
|
+
if self.supertraitsOf(b).iter().any(|s| sameType(s, a)) {
|
|
114
|
+
return true;
|
|
115
|
+
}
|
|
116
|
+
let none = BTreeMap::new();
|
|
117
|
+
self.impls.keys().any(|ty| {
|
|
118
|
+
let t = plumTypeFromName(ty);
|
|
119
|
+
self.implements(&t, a, &none) && self.implements(&t, b, &none)
|
|
120
|
+
})
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/// Whether the trait `sub` has `sup` among its supertraits, by name.
|
|
124
|
+
pub fn extendsTrait(&self, sub: &str, sup: &str) -> bool {
|
|
125
|
+
let mut seen: Vec<&str> = Vec::new();
|
|
126
|
+
let mut todo = vec![sub];
|
|
127
|
+
while let Some(n) = todo.pop() {
|
|
128
|
+
let Some(info) = self.traits.get(n) else { continue };
|
|
129
|
+
for s in &info.supers {
|
|
130
|
+
let Some(sn) = nominalName(s) else { continue };
|
|
131
|
+
if sn == sup {
|
|
132
|
+
return true;
|
|
133
|
+
}
|
|
134
|
+
if !seen.contains(&sn) {
|
|
135
|
+
seen.push(sn);
|
|
136
|
+
todo.push(sn);
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
false
|
|
141
|
+
}
|
|
142
|
+
|
|
79
143
|
/// The trait `ty` is an object of: `Actor` -> ("Actor", []), `Reducer[Msg]` -> ("Reducer", [Msg]).
|
|
80
144
|
pub fn traitObject<'a>(&self, ty: &'a PlumType) -> Option<(&'a str, &'a [PlumType])> {
|
|
81
145
|
match ty {
|
|
@@ -122,8 +186,15 @@ impl Traits {
|
|
|
122
186
|
};
|
|
123
187
|
match ty {
|
|
124
188
|
PlumType::TParam(p) => bounds.get(p).is_some_and(|bs| {
|
|
189
|
+
bs.iter().any(|b| {
|
|
125
|
-
|
|
190
|
+
matches!(self.traitObject(b), Some((n, a)) if fits(n, a))
|
|
191
|
+
|| self.supertraitsOf(b).iter().any(|s| matches!(self.traitObject(s), Some((n, a)) if fits(n, a)))
|
|
192
|
+
})
|
|
126
193
|
}),
|
|
194
|
+
// An upcast: a `Screen[S, M]` is an `Actor[M]` when `Screen` extends it.
|
|
195
|
+
_ if self.traitObject(ty).is_some() => {
|
|
196
|
+
self.supertraitsOf(ty).iter().any(|s| matches!(self.traitObject(s), Some((n, a)) if fits(n, a)))
|
|
197
|
+
}
|
|
127
198
|
_ => self.entriesOf(ty).iter().any(|e| fits(&e.trait_name, &e.args)),
|
|
128
199
|
}
|
|
129
200
|
}
|
|
@@ -255,17 +326,22 @@ pub fn buildTraits(source: &ast::Source) -> Traits {
|
|
|
255
326
|
.iter()
|
|
256
327
|
.map(|p| p.default.clone().filter(|_| matches!(p.ty, ast::ParamType::Type(_))))
|
|
257
328
|
.collect(),
|
|
329
|
+
from: None,
|
|
258
330
|
line: m.sig.line,
|
|
259
331
|
column: m.sig.column,
|
|
260
332
|
}
|
|
261
333
|
})
|
|
262
334
|
.collect();
|
|
335
|
+
let saved = setScope(Scope::named(&generics), None);
|
|
336
|
+
let supers = t.supers.iter().map(plumTypeFromAstG).collect();
|
|
337
|
+
restoreScope(saved);
|
|
263
338
|
out.traits.entry(t.name.clone()).or_insert(TraitInfo {
|
|
264
339
|
name: t.name.clone(),
|
|
265
340
|
file: t.file.clone(),
|
|
266
341
|
line: t.line,
|
|
267
342
|
column: t.column,
|
|
268
343
|
generics,
|
|
344
|
+
supers,
|
|
269
345
|
methods,
|
|
270
346
|
});
|
|
271
347
|
}
|
|
@@ -303,9 +379,42 @@ pub fn buildTraits(source: &ast::Source) -> Traits {
|
|
|
303
379
|
_ => {}
|
|
304
380
|
}
|
|
305
381
|
}
|
|
382
|
+
inheritMethods(&mut out);
|
|
306
383
|
out
|
|
307
384
|
}
|
|
308
385
|
|
|
386
|
+
/// Adds to each trait the methods of its supertraits (transitively) that it doesn't
|
|
387
|
+
/// declare itself, their signatures with the supertrait's parameters as the trait's
|
|
388
|
+
/// arguments for them: on a `Screen[S, M]`, `step` returns `Self` and takes a `Ctx[M]`.
|
|
389
|
+
fn inheritMethods(out: &mut Traits) {
|
|
390
|
+
let names: Vec<String> = out.traits.keys().cloned().collect();
|
|
391
|
+
for name in names {
|
|
392
|
+
let t = &out.traits[&name];
|
|
393
|
+
let selfObj = selfTypeOf(&t.name, &t.generics);
|
|
394
|
+
let mut extra: Vec<TraitMethodInfo> = Vec::new();
|
|
395
|
+
for sup in out.supertraitsOf(&selfObj) {
|
|
396
|
+
let Some((sn, sargs)) = out.traitObject(&sup) else { continue };
|
|
397
|
+
let Some(si) = out.traits.get(sn) else { continue };
|
|
398
|
+
if si.generics.len() != sargs.len() || sn == name {
|
|
399
|
+
continue;
|
|
400
|
+
}
|
|
401
|
+
let s = appSubst(&si.generics, sargs);
|
|
402
|
+
for m in si.methods.iter().filter(|m| m.from.is_none()) {
|
|
403
|
+
if t.method(&m.name).is_some() || extra.iter().any(|x| x.name == m.name) {
|
|
404
|
+
continue;
|
|
405
|
+
}
|
|
406
|
+
let mut m2 = m.clone();
|
|
407
|
+
m2.sig = types::substitute(&m.sig, &s);
|
|
408
|
+
m2.from = Some(sn.to_string());
|
|
409
|
+
extra.push(m2);
|
|
410
|
+
}
|
|
411
|
+
}
|
|
412
|
+
if let Some(t) = out.traits.get_mut(&name) {
|
|
413
|
+
t.methods.extend(extra);
|
|
414
|
+
}
|
|
415
|
+
}
|
|
416
|
+
}
|
|
417
|
+
|
|
309
418
|
/// The type of `self` in a method of `name` (a type or a trait): `Orb`, `Queue[T]`.
|
|
310
419
|
fn selfTypeOf(name: &str, generics: &[String]) -> PlumType {
|
|
311
420
|
if generics.is_empty() {
|
|
@@ -485,13 +594,6 @@ pub(crate) fn checkTraitDecls(source: &ast::Source, traits: &Traits, methods: &M
|
|
|
485
594
|
));
|
|
486
595
|
}
|
|
487
596
|
seen.push(&m.sig.name);
|
|
488
|
-
if !m.sig.has_self {
|
|
489
|
-
errors.push(CheckError::resolution(
|
|
490
|
-
m.sig.line,
|
|
491
|
-
m.sig.column,
|
|
492
|
-
format!("trait '{}': method '{}' must take self first", t.name, m.sig.name),
|
|
493
|
-
));
|
|
494
|
-
}
|
|
495
597
|
if m.sig.is_extern || m.sig.is_export {
|
|
496
598
|
errors.push(CheckError::resolution(
|
|
497
599
|
m.sig.line,
|
|
@@ -500,6 +602,41 @@ pub(crate) fn checkTraitDecls(source: &ast::Source, traits: &Traits, methods: &M
|
|
|
500
602
|
));
|
|
501
603
|
}
|
|
502
604
|
}
|
|
605
|
+
// `trait Screen[S, M] is Actor[M]`: each supertrait is a trait, with its arguments,
|
|
606
|
+
// not the trait itself (through others), and declares no method the trait does.
|
|
607
|
+
for sup in &t.supers {
|
|
608
|
+
let at = |m: String| CheckError::resolution(t.line, t.column, m);
|
|
609
|
+
match traits.traits.get(&sup.name) {
|
|
610
|
+
None => errors.push(at(format!("trait '{}': `is {}`: {} is not a trait", t.name, sup.name, sup.name))),
|
|
611
|
+
Some(st) if st.generics.len() != sup.generics.len() => errors.push(at(format!(
|
|
612
|
+
"trait '{}': `is {}`: trait {} takes {} type argument(s), got {}",
|
|
613
|
+
t.name,
|
|
614
|
+
sup.name,
|
|
615
|
+
st.name,
|
|
616
|
+
st.generics.len(),
|
|
617
|
+
sup.generics.len()
|
|
618
|
+
))),
|
|
619
|
+
Some(st) => {
|
|
620
|
+
if st.name == t.name || traits.extendsTrait(&st.name, &t.name) {
|
|
621
|
+
errors.push(at(format!("trait '{}' extends itself (through {})", t.name, st.name)));
|
|
622
|
+
continue;
|
|
623
|
+
}
|
|
624
|
+
for m in &t.methods {
|
|
625
|
+
if let Some(sm) = traits.traits.get(&st.name).and_then(|x| x.method(&m.sig.name)) {
|
|
626
|
+
let owner = sm.from.clone().unwrap_or_else(|| st.name.clone());
|
|
627
|
+
errors.push(CheckError::resolution(
|
|
628
|
+
m.sig.line,
|
|
629
|
+
m.sig.column,
|
|
630
|
+
format!(
|
|
631
|
+
"trait '{}': method '{}' is already a method of its supertrait {}; override it in the types instead",
|
|
632
|
+
t.name, m.sig.name, owner
|
|
633
|
+
),
|
|
634
|
+
));
|
|
635
|
+
}
|
|
636
|
+
}
|
|
637
|
+
}
|
|
638
|
+
}
|
|
639
|
+
}
|
|
503
640
|
if let Some(p) = prev {
|
|
504
641
|
setCurrentFile(&p);
|
|
505
642
|
}
|
|
@@ -575,13 +712,21 @@ pub(crate) fn checkTraitDecls(source: &ast::Source, traits: &Traits, methods: &M
|
|
|
575
712
|
}
|
|
576
713
|
continue;
|
|
577
714
|
}
|
|
715
|
+
// `is Screen[..]` implies `is Actor[..]` (added after the written entries by
|
|
716
|
+
// `trait_defaults::expandSupertraits`): an error about an implied entry says so.
|
|
578
|
-
|
|
717
|
+
let via = entries
|
|
718
|
+
.iter()
|
|
719
|
+
.find(|o| o.trait_name != entry.trait_name && traits.supertraitsOf(&o.ty).contains(&entry.ty))
|
|
720
|
+
.map(|o| format!(" ({} extends {})", o.ty, entry.ty))
|
|
721
|
+
.unwrap_or_default();
|
|
722
|
+
// A supertrait's methods are checked under its own entry.
|
|
723
|
+
for m in t.methods.iter().filter(|m| m.from.is_none()) {
|
|
579
724
|
let Some(expected) = traits.methodSig(&entry.ty, &m.name, &selfTy) else { continue };
|
|
580
725
|
let key = (e.name.clone(), m.name.clone());
|
|
581
726
|
let Some(found) = methods.get(&key).filter(|_| declared.contains(&key)) else {
|
|
582
727
|
if !m.hasDefault {
|
|
583
728
|
errors.push(at(format!(
|
|
584
|
-
"{} is missing method '{}' of {}: fun {}(self{}) -> {}",
|
|
729
|
+
"{} is missing method '{}' of {}{via}: fun {}(self{}) -> {}",
|
|
585
730
|
e.name,
|
|
586
731
|
m.name,
|
|
587
732
|
entry.ty,
|
|
@@ -601,9 +746,12 @@ pub(crate) fn checkTraitDecls(source: &ast::Source, traits: &Traits, methods: &M
|
|
|
601
746
|
let static_ = source.items.iter().any(|i| {
|
|
602
747
|
matches!(i, ast::Item::Fn(f) if f.type_param.as_deref() == Some(e.name.as_str()) && f.name == m.name && !f.has_self)
|
|
603
748
|
});
|
|
749
|
+
// A trait's static (`fun name() -> Str`, no self) is a static of the type, and
|
|
750
|
+
// a trait's method a method.
|
|
751
|
+
let wrongKind = static_ == m.hasSelf;
|
|
604
|
-
if *found != expected ||
|
|
752
|
+
if *found != expected || wrongKind {
|
|
605
753
|
errors.push(at(format!(
|
|
606
|
-
"{}.{}: its signature differs from {}'s: expected (self{}) -> {}, found {}{}",
|
|
754
|
+
"{}.{}: its signature differs from {}'s{via}: expected (self{}) -> {}, found {}{}",
|
|
607
755
|
e.name,
|
|
608
756
|
m.name,
|
|
609
757
|
entry.ty,
|
|
@@ -615,7 +763,7 @@ pub(crate) fn checkTraitDecls(source: &ast::Source, traits: &Traits, methods: &M
|
|
|
615
763
|
PlumType::TFun(_, r) => r.to_string(),
|
|
616
764
|
_ => String::new(),
|
|
617
765
|
},
|
|
618
|
-
if static_ { "a static (no self) " } else { "" },
|
|
766
|
+
if wrongKind && static_ { "a static (no self) " } else if wrongKind { "a method (with self) " } else { "" },
|
|
619
767
|
match found {
|
|
620
768
|
PlumType::TFun(ps, r) => format!(
|
|
621
769
|
"({}) -> {}",
|
compiler/checker/tests/checker/traits_tests.rs
CHANGED
|
@@ -413,11 +413,40 @@ fn traitObjectsAreMatchedByType() {
|
|
|
413
413
|
}
|
|
414
414
|
|
|
415
415
|
#[test]
|
|
416
|
-
fn
|
|
416
|
+
fn traitMethodsAreDeclaredOnce() {
|
|
417
|
-
fails("trait T =\n fun make() -> Int\n", "method 'make' must take self first");
|
|
418
417
|
fails("trait T =\n fun a(self) -> Int\n fun a(self) -> Int\n", "declares method 'a' twice");
|
|
419
418
|
}
|
|
420
419
|
|
|
420
|
+
/// A trait may declare a static (no self): required, or with a default copied into each
|
|
421
|
+
/// implementer. `Self.make()` in a default calls the implementer's static.
|
|
422
|
+
#[test]
|
|
423
|
+
fn traitStatics() {
|
|
424
|
+
let tr = "trait Made =\n fun make() -> Int = 1\n fun twice(self) -> Int = Self.make() * 2\n\n";
|
|
425
|
+
ok(&format!("{tr}struct A(id: Int) is Made\n\nstruct B(id: Int) is Made =\n fun make() -> Int = 5\n\nfun main() =\n a: Made := A(id: 1)\n show(\"{{A.make()}} {{B.make()}} {{a.twice()}} {{B(id: 1).twice()}}\")\n"));
|
|
426
|
+
fails(
|
|
427
|
+
&format!("{tr}struct A(id: Int) is Made =\n fun make(self) -> Int = 5\n\nfun main() = Unit\n"),
|
|
428
|
+
"A.make: its signature differs from Made's: expected (self) -> Int, found a method (with self)",
|
|
429
|
+
);
|
|
430
|
+
fails(
|
|
431
|
+
"trait Named =\n fun name() -> Str\n\nstruct A(id: Int) is Named\n\nfun main() = Unit\n",
|
|
432
|
+
"A is missing method 'name' of Named",
|
|
433
|
+
);
|
|
434
|
+
fails(
|
|
435
|
+
&format!("{tr}struct A(id: Int) is Made =\n fun twice() -> Int = 5\n\nfun main() = Unit\n"),
|
|
436
|
+
"A.twice: its signature differs from Made's: expected (self) -> Int, found a static (no self)",
|
|
437
|
+
);
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
/// `@typeName(T)` is a `Str`; an unknown built-in or the wrong arguments are errors.
|
|
441
|
+
#[test]
|
|
442
|
+
fn compileTimeBuiltins() {
|
|
443
|
+
ok("fun main() =\n s: Str := @typeName(Int)\n show(s)\n");
|
|
444
|
+
fails("fun main() =\n show(@nope(Int))\n", "unknown built-in @nope; the built-ins are @typeName");
|
|
445
|
+
fails("fun main() =\n x := 1\n show(@typeName(x))\n", "@typeName takes one type, e.g. @typeName(Self)");
|
|
446
|
+
fails("fun main() =\n show(@typeName(Int, Str))\n", "@typeName takes one type");
|
|
447
|
+
fails("fun main() =\n n: Int := @typeName(Int)\n show(\"{n}\")\n", "type mismatch");
|
|
448
|
+
}
|
|
449
|
+
|
|
421
450
|
#[test]
|
|
422
451
|
fn coercionIsOfWholeValuesOnly() {
|
|
423
452
|
// a `List[Orb]` is not a `List[Actor]`, nor a `fn(Orb) -> Orb` a `fn(Actor) -> Actor`
|
|
@@ -640,6 +669,134 @@ fn downcastToAGenericImplementer() {
|
|
|
640
669
|
);
|
|
641
670
|
fails(
|
|
642
671
|
&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"),
|
|
672
|
+
"(T is Named here): no type is both a Actor and a Named",
|
|
673
|
+
);
|
|
674
|
+
}
|
|
675
|
+
|
|
676
|
+
/// `Box[Msg] as b` names the arguments of a generic implementer.
|
|
677
|
+
#[test]
|
|
678
|
+
fn downcastWithTypeArguments() {
|
|
679
|
+
ok(&format!("{GEN}fun idOf(t: Thing[Msg]) -> Int = match t\n Box[Msg] as b => b.id\n _ => 0\n\nfun main() = show(\"{{idOf(Box(id: 1))}}\")\n"));
|
|
680
|
+
fails(
|
|
681
|
+
&format!("{GEN}fun idOf(t: Thing[Msg]) -> Int = match t\n Box[Msg, Int] as b => b.id\n _ => 0\n\nfun main() = Unit\n"),
|
|
682
|
+
"Box takes 1 type argument(s), got 2",
|
|
683
|
+
);
|
|
684
|
+
fails(
|
|
685
|
+
&format!("{GEN}fun idOf(t: Thing[Msg]) -> Int = match t\n Nope[Msg] as b => 1\n _ => 0\n\nfun main() = Unit\n"),
|
|
686
|
+
"unknown type Nope",
|
|
687
|
+
);
|
|
688
|
+
}
|
|
689
|
+
|
|
690
|
+
const SCREEN: &str = "enum Msg = Go | Stop
|
|
691
|
+
|
|
692
|
+
trait Actor[M] =
|
|
693
|
+
fun key(self) -> Int
|
|
694
|
+
fun step(self, dt: Float) -> Self = self
|
|
695
|
+
fun name(self) -> Str = \"actor\"
|
|
696
|
+
|
|
697
|
+
trait Screen[S, M] is Actor[M] =
|
|
698
|
+
fun react(self, state: S, msg: M) -> Self = self
|
|
699
|
+
fun title(self) -> Str = \"{self.name()} {self.key()}\"
|
|
700
|
+
|
|
701
|
+
struct Orb(id: Int) is Actor[Msg] =
|
|
702
|
+
fun key(self) -> Int = self.id
|
|
703
|
+
|
|
704
|
+
struct Play(id: Int, n: Int) is Screen[Int, Msg] =
|
|
705
|
+
fun key(self) -> Int = self.id
|
|
706
|
+
fun react(self, state: Int, msg: Msg) -> Play = Play(..self, n: state)
|
|
707
|
+
|
|
708
|
+
";
|
|
709
|
+
|
|
710
|
+
/// `trait Screen[S, M] is Actor[M]`: a `Screen` is an `Actor` (an upcast needs no cast), a
|
|
711
|
+
/// `Screen` trait object has `Actor`'s methods, and a default may call them on self.
|
|
712
|
+
#[test]
|
|
713
|
+
fn supertraits() {
|
|
714
|
+
ok(&format!(
|
|
715
|
+
"{SCREEN}fun keyOf(a: Actor[Msg]) -> Int = a.key()
|
|
716
|
+
|
|
717
|
+
fun main() =
|
|
718
|
+
s: Screen[Int, Msg] := Play(id: 1, n: 0)
|
|
719
|
+
a: Actor[Msg] := s
|
|
720
|
+
xs: List[Actor[Msg]] := [s, Orb(id: 2), Play(id: 3, n: 0)]
|
|
721
|
+
t: Screen[Int, Msg] := s.step(1.0).react(2, Go)
|
|
722
|
+
show(\"{{keyOf(s)}} {{a.key()}} {{xs.length()}} {{t.title()}} {{s.name()}}\")
|
|
723
|
+
"
|
|
724
|
+
));
|
|
725
|
+
// The other way is a downcast.
|
|
726
|
+
fails(
|
|
727
|
+
&format!("{SCREEN}fun main() =\n a: Actor[Msg] := Orb(id: 1)\n s: Screen[Int, Msg] := a\n show(\"{{s.key()}}\")\n"),
|
|
728
|
+
"type mismatch",
|
|
729
|
+
);
|
|
730
|
+
// Not an `Actor[Int]`: the arguments carry over.
|
|
731
|
+
fails(
|
|
732
|
+
&format!("{SCREEN}fun main() =\n s: Screen[Int, Msg] := Play(id: 1, n: 0)\n a: Actor[Int] := s\n show(\"{{a.key()}}\")\n"),
|
|
733
|
+
"type mismatch",
|
|
734
|
+
);
|
|
735
|
+
}
|
|
736
|
+
|
|
737
|
+
/// `is Screen[..]` implies `is Actor[..]`: the type must have Actor's required methods, and
|
|
738
|
+
/// the error says where the Actor entry comes from.
|
|
739
|
+
#[test]
|
|
740
|
+
fn subtraitImplementerNeedsTheSupertraitsMethods() {
|
|
741
|
+
fails(
|
|
742
|
+
&format!("{SCREEN}struct Menu(id: Int) is Screen[Int, Msg] =\n fun name(self) -> Str = \"m\"\n\nfun main() = Unit\n"),
|
|
743
|
+
"Menu is missing method 'key' of Actor[Msg] (Screen[Int, Msg] extends Actor[Msg])",
|
|
744
|
+
);
|
|
745
|
+
fails(
|
|
746
|
+
&format!("{SCREEN}struct Menu(id: Int) is Screen[Int, Msg] =\n fun key(self) -> Str = \"m\"\n\nfun main() = Unit\n"),
|
|
747
|
+
"Menu.key: its signature differs from Actor[Msg]'s (Screen[Int, Msg] extends Actor[Msg])",
|
|
748
|
+
);
|
|
749
|
+
// Written out as well, it is the same entry.
|
|
750
|
+
ok(&format!("{SCREEN}struct Menu(id: Int) is Screen[Int, Msg], Actor[Msg] =\n fun key(self) -> Int = self.id\n\nfun main() =\n a: Actor[Msg] := Menu(id: 1)\n show(\"{{a.key()}}\")\n"));
|
|
751
|
+
fails(
|
|
752
|
+
&format!("{SCREEN}struct Menu(id: Int) is Screen[Int, Msg], Actor[Int] =\n fun key(self) -> Int = self.id\n\nfun main() = Unit\n"),
|
|
643
|
-
"
|
|
753
|
+
"implements Actor twice",
|
|
754
|
+
);
|
|
755
|
+
}
|
|
756
|
+
|
|
757
|
+
#[test]
|
|
758
|
+
fn supertraitDeclarationErrors() {
|
|
759
|
+
fails("trait A is Nope =\n fun a(self) -> Int\n\nfun main() = Unit\n", "trait 'A': `is Nope`: Nope is not a trait");
|
|
760
|
+
fails(
|
|
761
|
+
"trait B[M] =\n fun b(self) -> Int\n\ntrait A is B =\n fun a(self) -> Int\n\nfun main() = Unit\n",
|
|
762
|
+
"trait 'A': `is B`: trait B takes 1 type argument(s), got 0",
|
|
763
|
+
);
|
|
764
|
+
fails(
|
|
765
|
+
"trait A is B =\n fun a(self) -> Int\n\ntrait B is A =\n fun b(self) -> Int\n\nfun main() = Unit\n",
|
|
766
|
+
"extends itself",
|
|
767
|
+
);
|
|
768
|
+
fails(
|
|
769
|
+
"trait B =\n fun b(self) -> Int\n\ntrait A is B =\n fun b(self) -> Int\n\nfun main() = Unit\n",
|
|
770
|
+
"trait 'A': method 'b' is already a method of its supertrait B",
|
|
771
|
+
);
|
|
772
|
+
}
|
|
773
|
+
|
|
774
|
+
/// `Screen[S, M] as s` on an `Actor[M]`: a downcast to a trait binds a trait object.
|
|
775
|
+
#[test]
|
|
776
|
+
fn downcastToATrait() {
|
|
777
|
+
ok(&format!(
|
|
778
|
+
"{SCREEN}fun asScreen(a: Actor[Msg]) -> Option[Screen[Int, Msg]] = match a
|
|
779
|
+
Screen[Int, Msg] as s => Some(s)
|
|
780
|
+
_ => None
|
|
781
|
+
|
|
782
|
+
fun main() =
|
|
783
|
+
a: Actor[Msg] := Play(id: 1, n: 0)
|
|
784
|
+
n := match asScreen(a)
|
|
785
|
+
Some(s) => s.react(1, Go).key()
|
|
786
|
+
None => 0
|
|
787
|
+
show(\"{{n}}\")
|
|
788
|
+
"
|
|
789
|
+
));
|
|
790
|
+
fails(
|
|
791
|
+
&format!("{SCREEN}fun f(a: Actor[Msg]) -> Int = match a\n Screen as s => 1\n _ => 0\n\nfun main() = Unit\n"),
|
|
792
|
+
"the trait Screen takes type arguments (S, M); write them",
|
|
793
|
+
);
|
|
794
|
+
fails(
|
|
795
|
+
&format!("{SCREEN}trait Named =\n fun name2(self) -> Str\n\nfun f(a: Actor[Msg]) -> Int = match a\n Named as s => 1\n _ => 0\n\nfun main() = Unit\n"),
|
|
796
|
+
"no type is both a Actor[Msg] and a Named",
|
|
797
|
+
);
|
|
798
|
+
fails(
|
|
799
|
+
&format!("{SCREEN}fun f(a: Actor[Msg]) -> Int = match a\n Screen[Int, Msg] as s => s.nope()\n _ => 0\n\nfun main() = Unit\n"),
|
|
800
|
+
"nope",
|
|
644
801
|
);
|
|
645
802
|
}
|
compiler/core/src/ast.rs
CHANGED
|
@@ -451,6 +451,9 @@ pub struct Trait {
|
|
|
451
451
|
pub line: usize,
|
|
452
452
|
pub column: usize,
|
|
453
453
|
pub generics: Vec<GenericParam>,
|
|
454
|
+
/// `trait Screen[S, M] is Actor[M]`: its supertraits, as written. A type that is a
|
|
455
|
+
/// `Screen[S, M]` is an `Actor[M]` too (`trait_defaults::expandSupertraits`).
|
|
456
|
+
pub supers: Vec<Type>,
|
|
454
457
|
pub methods: Vec<TraitMethod>,
|
|
455
458
|
}
|
|
456
459
|
|
|
@@ -875,8 +878,9 @@ pub enum CasePattern {
|
|
|
875
878
|
Bool(bool),
|
|
876
879
|
Name(String),
|
|
877
880
|
/// `Orb as o`: on a trait object, matches a value of type `ty` and binds it,
|
|
878
|
-
/// typed `ty`, as `name`.
|
|
881
|
+
/// typed `ty`, as `name`. `args` are the type arguments if written
|
|
882
|
+
/// (`Box[Msg] as b`, `Screen[S, M] as s`); empty when they are left out.
|
|
879
|
-
As { ty: String, name: String },
|
|
883
|
+
As { ty: String, name: String, args: Vec<Type> },
|
|
880
884
|
Wildcard,
|
|
881
885
|
}
|
|
882
886
|
|
|
@@ -890,7 +894,7 @@ impl PartialEq for CasePattern {
|
|
|
890
894
|
(P::Float(a), P::Float(b)) => a == b,
|
|
891
895
|
(P::Bool(a), P::Bool(b)) => a == b,
|
|
892
896
|
(P::Name(a), P::Name(b)) => a == b,
|
|
893
|
-
(P::As { ty: a, name: x }, P::As { ty: b, name: y }) => a == b && x == y,
|
|
897
|
+
(P::As { ty: a, name: x, args: p }, P::As { ty: b, name: y, args: q }) => a == b && x == y && p == q,
|
|
894
898
|
(P::Wildcard, P::Wildcard) => true,
|
|
895
899
|
_ => false,
|
|
896
900
|
}
|
compiler/core/src/compile_builtins.rs
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
//! Compile-time built-ins: `@name(args)`, Zig-style. Each is in `BUILTINS`, with what it
|
|
2
|
+
//! takes; the parser lowers a well-formed one (`lower`) and leaves anything else as a call
|
|
3
|
+
//! named `@name`, which the checker reports (`error`).
|
|
4
|
+
|
|
5
|
+
use crate::ast::*;
|
|
6
|
+
|
|
7
|
+
/// What a built-in's arguments must be.
|
|
8
|
+
#[derive(Debug, Clone, Copy, PartialEq)]
|
|
9
|
+
pub enum Takes {
|
|
10
|
+
/// Exactly one type.
|
|
11
|
+
OneType,
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/// The built-ins, with what each takes and an example.
|
|
15
|
+
pub const BUILTINS: &[(&str, Takes, &str)] = &[
|
|
16
|
+
// `@typeName(T)`: the name of the type `T` without its type arguments, a `Str` known
|
|
17
|
+
// at compile time (`@typeName(Button[Msg])` is "Button"); in a trait's default,
|
|
18
|
+
// `@typeName(Self)` is each implementer's own name. It is std's
|
|
19
|
+
// `str.typeName[T]()`, resolved per instantiation.
|
|
20
|
+
("typeName", Takes::OneType, "@typeName(Self)"),
|
|
21
|
+
];
|
|
22
|
+
|
|
23
|
+
/// One argument as written: a type or a value.
|
|
24
|
+
#[derive(Debug, Clone)]
|
|
25
|
+
pub enum BuiltinArg {
|
|
26
|
+
Type(Type),
|
|
27
|
+
Value(Expr),
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/// `@name(args)` as the program uses it: the lowered expression when the built-in exists
|
|
31
|
+
/// and its arguments fit, else a call named `@name` for the checker to report.
|
|
32
|
+
pub fn lower(name: &str, args: Vec<BuiltinArg>, line: usize, column: usize) -> Expr {
|
|
33
|
+
let call = |name: String, args: Vec<Arg>, type_args: Vec<Type>| FnCall {
|
|
34
|
+
name,
|
|
35
|
+
args,
|
|
36
|
+
line,
|
|
37
|
+
column,
|
|
38
|
+
tail: TailKind::NotTail,
|
|
39
|
+
recv: None,
|
|
40
|
+
type_args,
|
|
41
|
+
};
|
|
42
|
+
if let ("typeName", [BuiltinArg::Type(t)]) = (name, args.as_slice()) {
|
|
43
|
+
return Expr::Attribute(Box::new(AttributeExpr {
|
|
44
|
+
object: Expr::Var("str".to_string()),
|
|
45
|
+
attr: AttrKind::Method(call("typeName".to_string(), Vec::new(), vec![t.clone()])),
|
|
46
|
+
}));
|
|
47
|
+
}
|
|
48
|
+
let mut values = Vec::new();
|
|
49
|
+
let mut types = Vec::new();
|
|
50
|
+
for a in args {
|
|
51
|
+
match a {
|
|
52
|
+
BuiltinArg::Type(t) => types.push(t),
|
|
53
|
+
BuiltinArg::Value(e) => values.push(Arg::Positional(e)),
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
Expr::FnCall(call(format!("@{name}"), values, types))
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/// The error for a call named `@name` that reached the checker: an unknown built-in, or
|
|
60
|
+
/// one given the wrong arguments.
|
|
61
|
+
pub fn error(name: &str) -> Option<String> {
|
|
62
|
+
let bare = name.strip_prefix('@')?;
|
|
63
|
+
let known: Vec<String> = BUILTINS.iter().map(|(n, _, _)| format!("@{n}")).collect();
|
|
64
|
+
Some(match BUILTINS.iter().find(|(n, _, _)| *n == bare) {
|
|
65
|
+
Some((_, Takes::OneType, eg)) => format!("@{bare} takes one type, e.g. {eg}"),
|
|
66
|
+
None => format!("unknown built-in @{bare}; the built-ins are {}", known.join(", ")),
|
|
67
|
+
})
|
|
68
|
+
}
|
compiler/core/src/lib.rs
CHANGED
|
@@ -8,6 +8,7 @@ pub mod blocks;
|
|
|
8
8
|
pub mod builtin_usage;
|
|
9
9
|
pub mod closure_escape;
|
|
10
10
|
pub mod closure_spec;
|
|
11
|
+
pub mod compile_builtins;
|
|
11
12
|
pub mod ctors;
|
|
12
13
|
pub mod diag;
|
|
13
14
|
pub mod drive;
|
compiler/core/src/parser.rs
CHANGED
|
@@ -338,7 +338,8 @@ impl<'a> AstParser<'a> {
|
|
|
338
338
|
.unwrap_or_default();
|
|
339
339
|
let generics = self.parseGenericsField(node);
|
|
340
340
|
let pos = node.start_position();
|
|
341
|
+
let supers = self.parseImplements(node);
|
|
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 mut t = Trait { name: name.clone(), file: String::new(), line: pos.row + 1, column: pos.column + 1, generics, supers, methods: Vec::new() };
|
|
342
343
|
let selfTy = t.selfType();
|
|
343
344
|
let mut defaults = Vec::new();
|
|
344
345
|
for n in self.childrenOfKind(node, "fn") {
|
|
@@ -1086,6 +1087,10 @@ impl<'a> AstParser<'a> {
|
|
|
1086
1087
|
"as_pattern" => CasePattern::As {
|
|
1087
1088
|
ty: inner.child_by_field_name("type").map(|n| self.text(n)).unwrap_or_default(),
|
|
1088
1089
|
name: inner.child_by_field_name("name").map(|n| self.text(n)).unwrap_or_default(),
|
|
1090
|
+
args: {
|
|
1091
|
+
let mut c = inner.walk();
|
|
1092
|
+
inner.children_by_field_name("args", &mut c).filter(|n| n.kind() == "type").map(|n| self.parseType(n)).collect()
|
|
1093
|
+
},
|
|
1089
1094
|
},
|
|
1090
1095
|
"string" => CasePattern::String(self.parseStringRaw(inner)),
|
|
1091
1096
|
"integer" => CasePattern::Int(self.parseInteger(inner)),
|
|
@@ -1305,6 +1310,7 @@ impl<'a> AstParser<'a> {
|
|
|
1305
1310
|
}))
|
|
1306
1311
|
}
|
|
1307
1312
|
"fn_call" => Expr::FnCall(self.parseFnCall(node)),
|
|
1313
|
+
"builtin_call" => self.parseBuiltinCall(node),
|
|
1308
1314
|
"class_call" => Expr::ClassCall(self.parseClassCall(node)),
|
|
1309
1315
|
"list_literal" => self.parseListLiteral(node),
|
|
1310
1316
|
"parenthesized_expression" => {
|
|
@@ -1591,6 +1597,21 @@ impl<'a> AstParser<'a> {
|
|
|
1591
1597
|
g.named_children(&mut cursor).map(|t| self.parseTypeOrFn(t)).collect()
|
|
1592
1598
|
}
|
|
1593
1599
|
|
|
1600
|
+
/// `@name(args)`: a compile-time built-in (`compile_builtins`).
|
|
1601
|
+
fn parseBuiltinCall(&self, node: Node) -> Expr {
|
|
1602
|
+
let name = node.child_by_field_name("name").map(|n| self.text(n)).unwrap_or_default();
|
|
1603
|
+
let mut cursor = node.walk();
|
|
1604
|
+
let args = node
|
|
1605
|
+
.children_by_field_name("argument", &mut cursor)
|
|
1606
|
+
.map(|a| match a.kind() {
|
|
1607
|
+
"type" => crate::compile_builtins::BuiltinArg::Type(self.parseType(a)),
|
|
1608
|
+
_ => crate::compile_builtins::BuiltinArg::Value(self.parseExpression(self.unwrapExprNode(a))),
|
|
1609
|
+
})
|
|
1610
|
+
.collect();
|
|
1611
|
+
let pos = node.start_position();
|
|
1612
|
+
crate::compile_builtins::lower(&name, args, pos.row + 1, pos.column + 1)
|
|
1613
|
+
}
|
|
1614
|
+
|
|
1594
1615
|
fn parseFnCall(&self, node: Node) -> FnCall {
|
|
1595
1616
|
// fn_call: var_identifier fn_argument_list (the callee lexes as var_identifier
|
|
1596
1617
|
// to avoid an identifier-token tie with all-lowercase, no-underscore names)
|
compiler/core/src/simplify.rs
CHANGED
|
@@ -584,12 +584,23 @@ impl<'a> Cx<'a> {
|
|
|
584
584
|
if trivial(&a) && !assigned.contains(p) && !declared.contains(p) && !called.contains(&fr) {
|
|
585
585
|
subst.insert(fr, a);
|
|
586
586
|
} else if allowLets {
|
|
587
|
+
// The local has the parameter's declared type, so an argument whose type the
|
|
588
|
+
// parameter fixed (`use(Holder.of(lit))`, `Holder[M]` pinned by `use`'s
|
|
589
|
+
// `Holder[Int]`) keeps it. Not when the type names the callee's generics.
|
|
590
|
+
let mut gens: Vec<&String> = f.generics.iter().collect();
|
|
591
|
+
if let Some(o) = f.type_param.as_ref().and_then(|t| self.owners.get(t)) {
|
|
592
|
+
gens.extend(o.iter());
|
|
593
|
+
}
|
|
594
|
+
let ty = match &f.params[i].ty {
|
|
595
|
+
ParamType::Type(t) if !mentionsAny(t, &gens) => Some(t.clone()),
|
|
596
|
+
_ => None,
|
|
597
|
+
};
|
|
587
598
|
binds.push(Stmt::Assign(Assign {
|
|
588
599
|
isSynthetic: false,
|
|
589
600
|
targets: vec![AssignTarget::Var(fr)],
|
|
590
601
|
values: vec![a],
|
|
591
602
|
declare: true,
|
|
592
|
-
ty
|
|
603
|
+
ty,
|
|
593
604
|
}));
|
|
594
605
|
} else {
|
|
595
606
|
let StmtKind::Expr(be, ..) = &body.stmts.first()?.kind else { return None };
|
|
@@ -889,6 +900,11 @@ impl<'a> Cx<'a> {
|
|
|
889
900
|
}
|
|
890
901
|
|
|
891
902
|
|
|
903
|
+
/// Whether `t` names any of `names` (a generic parameter), or `Self`.
|
|
904
|
+
fn mentionsAny(t: &Type, names: &[&String]) -> bool {
|
|
905
|
+
t.name == SELF_TYPE || names.iter().any(|n| **n == t.name) || t.generics.iter().any(|g| mentionsAny(g, names))
|
|
906
|
+
}
|
|
907
|
+
|
|
892
908
|
/// Scope-aware renamer: a declaration renames only the uses in its own scope (the rest of its
|
|
893
909
|
/// block and nested blocks/closures); uses before it, or in sibling scopes, keep the outer name.
|
|
894
910
|
struct Scoper {
|
compiler/core/src/trait_defaults.rs
CHANGED
|
@@ -11,9 +11,70 @@
|
|
|
11
11
|
use crate::ast::*;
|
|
12
12
|
use std::collections::{HashMap, HashSet};
|
|
13
13
|
|
|
14
|
-
/// The program with
|
|
14
|
+
/// The program with each type's supertraits added to its `is` list and a copy of each
|
|
15
|
+
/// inherited default added to each implementer, or `None` when nothing is missing (the
|
|
15
|
-
///
|
|
16
|
+
/// program already has every entry and copy, or has no traits).
|
|
16
17
|
pub fn expandDefaults(src: &Source) -> Option<Source> {
|
|
18
|
+
match expandSupertraits(src) {
|
|
19
|
+
Some(s) => Some(expandDefaultsOnly(&s).unwrap_or(s)),
|
|
20
|
+
None => expandDefaultsOnly(src),
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/// The supertraits `trait t is ..` gives the entry `entry` (`Screen[State, Msg]` with
|
|
25
|
+
/// `trait Screen[S, M] is Actor[M]`: `Actor[Msg]`).
|
|
26
|
+
pub fn supersOf(t: &Trait, entry: &Type) -> Vec<Type> {
|
|
27
|
+
if t.generics.len() != entry.generics.len() {
|
|
28
|
+
return Vec::new();
|
|
29
|
+
}
|
|
30
|
+
let subst: HashMap<String, Type> = t.generics.iter().map(|g| g.name.clone()).zip(entry.generics.iter().cloned()).collect();
|
|
31
|
+
t.supers.iter().map(|s| substType(s, &subst)).collect()
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/// Trait inheritance: a type that is a `Screen[S, M]`, with `trait Screen[S, M] is
|
|
35
|
+
/// Actor[M]`, is an `Actor[M]` too. Each type's `is` list gets the supertraits of its
|
|
36
|
+
/// entries (and theirs), after the entries as written, unless written already. Every pass
|
|
37
|
+
/// after this sees `is Screen[S, M], Actor[M]`: the type must have `Actor`'s methods, is
|
|
38
|
+
/// in `Actor[M]`'s dispatch set, and gets `Actor`'s defaults. `None` if nothing is added.
|
|
39
|
+
pub fn expandSupertraits(src: &Source) -> Option<Source> {
|
|
40
|
+
let traits: HashMap<&str, &Trait> = src
|
|
41
|
+
.items
|
|
42
|
+
.iter()
|
|
43
|
+
.filter_map(|i| match i {
|
|
44
|
+
Item::Trait(t) => Some((t.name.as_str(), t)),
|
|
45
|
+
_ => None,
|
|
46
|
+
})
|
|
47
|
+
.collect();
|
|
48
|
+
if !traits.values().any(|t| !t.supers.is_empty()) {
|
|
49
|
+
return None;
|
|
50
|
+
}
|
|
51
|
+
let mut out: Option<Source> = None;
|
|
52
|
+
for (idx, item) in src.items.iter().enumerate() {
|
|
53
|
+
let Item::Enum(e) = item else { continue };
|
|
54
|
+
let mut all = e.implements.clone();
|
|
55
|
+
let mut i = 0;
|
|
56
|
+
// A cycle of supertraits (an error the checker reports) stops at a bound.
|
|
57
|
+
while i < all.len() && all.len() < 64 {
|
|
58
|
+
if let Some(t) = traits.get(all[i].name.as_str()) {
|
|
59
|
+
for s in supersOf(t, &all[i].clone()) {
|
|
60
|
+
if !all.contains(&s) {
|
|
61
|
+
all.push(s);
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
i += 1;
|
|
66
|
+
}
|
|
67
|
+
if all.len() > e.implements.len() {
|
|
68
|
+
let o = out.get_or_insert_with(|| src.clone());
|
|
69
|
+
if let Item::Enum(oe) = &mut o.items[idx] {
|
|
70
|
+
oe.implements = all;
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
out
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
fn expandDefaultsOnly(src: &Source) -> Option<Source> {
|
|
17
78
|
let traits: HashMap<&str, &Trait> = src
|
|
18
79
|
.items
|
|
19
80
|
.iter()
|
|
@@ -66,6 +127,7 @@ pub fn expandDefaults(src: &Source) -> Option<Source> {
|
|
|
66
127
|
}
|
|
67
128
|
let Some(d) = defaults.get(&(t.name.as_str(), m.sig.name.as_str())) else { continue };
|
|
68
129
|
let mut f = (*d).clone();
|
|
130
|
+
selfTypeNamesTo(&mut f.body, &e.name);
|
|
69
131
|
f.type_param = Some(e.name.clone());
|
|
70
132
|
for (p, sp) in f.params.iter_mut().zip(&m.sig.params) {
|
|
71
133
|
p.ty = substParam(&sp.ty, &subst);
|
|
@@ -79,10 +141,20 @@ pub fn expandDefaults(src: &Source) -> Option<Source> {
|
|
|
79
141
|
}
|
|
80
142
|
}
|
|
81
143
|
addDynCopies(src, &traits, &mut owned, &mut added);
|
|
144
|
+
// The trait's own default bodies (kept for checking) name the trait where they say
|
|
145
|
+
// `Self` as a type (`Self.name()`): each copy above has the implementer there.
|
|
146
|
+
let selfy = src.items.iter().any(|i| matches!(i, Item::Fn(f) if f.type_param.as_deref().is_some_and(|t| traits.contains_key(t)) && bodySaysSelf(&f.body)));
|
|
82
|
-
if added.is_empty() {
|
|
147
|
+
if added.is_empty() && !selfy {
|
|
83
148
|
return None;
|
|
84
149
|
}
|
|
85
150
|
let mut out = src.clone();
|
|
151
|
+
for item in &mut out.items {
|
|
152
|
+
if let Item::Fn(f) = item {
|
|
153
|
+
if let Some(t) = f.type_param.clone().filter(|t| traits.contains_key(t.as_str())) {
|
|
154
|
+
selfTypeNamesTo(&mut f.body, &t);
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
}
|
|
86
158
|
out.items.extend(added);
|
|
87
159
|
Some(out)
|
|
88
160
|
}
|
|
@@ -210,6 +282,49 @@ fn substType(t: &Type, s: &HashMap<String, Type>) -> Type {
|
|
|
210
282
|
Type { name: t.name.clone(), generics: t.generics.iter().map(|g| substType(g, s)).collect() }
|
|
211
283
|
}
|
|
212
284
|
|
|
285
|
+
/// Whether `body` uses `Self` as a type in an expression (`Self.name()`).
|
|
286
|
+
fn bodySaysSelf(body: &FnBody) -> bool {
|
|
287
|
+
let mut found = false;
|
|
288
|
+
let mut b = body.clone();
|
|
289
|
+
crate::forms::walkBody(&mut b, &mut |_| {}, &mut |e| {
|
|
290
|
+
if let ExprKind::TypeName(n) = &e.kind {
|
|
291
|
+
found |= n == SELF_TYPE || n.starts_with(&format!("{SELF_TYPE}{MEMBER_SEP}"));
|
|
292
|
+
}
|
|
293
|
+
});
|
|
294
|
+
found
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
/// `Self` used as a type in an expression of `body` (`Self.name()`, `Self.Name`) renamed
|
|
298
|
+
/// `to`: the implementer in its copy of a default, the trait in the trait's own.
|
|
299
|
+
pub fn selfTypeNamesTo(body: &mut FnBody, to: &str) {
|
|
300
|
+
crate::forms::walkBody(body, &mut |_| {}, &mut |e| {
|
|
301
|
+
if let ExprKind::TypeName(n) = &mut e.kind {
|
|
302
|
+
if n == SELF_TYPE {
|
|
303
|
+
*n = to.to_string();
|
|
304
|
+
} else if let Some(rest) = n.strip_prefix(&format!("{SELF_TYPE}{MEMBER_SEP}")) {
|
|
305
|
+
*n = format!("{to}{MEMBER_SEP}{rest}");
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
});
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
/// The type arguments of the downcasts in `p` (`Screen[S, M] as s`).
|
|
312
|
+
fn substPattern(p: &mut CasePattern, s: &HashMap<String, Type>) {
|
|
313
|
+
match p {
|
|
314
|
+
CasePattern::As { args, .. } => {
|
|
315
|
+
for a in args.iter_mut() {
|
|
316
|
+
*a = substType(a, s);
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
CasePattern::Class { fields, .. } => {
|
|
320
|
+
for f in fields.iter_mut() {
|
|
321
|
+
substPattern(f, s);
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
_ => {}
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
|
|
213
328
|
fn substParam(t: &ParamType, s: &HashMap<String, Type>) -> ParamType {
|
|
214
329
|
match t {
|
|
215
330
|
ParamType::Type(t) => ParamType::Type(substType(t, s)),
|
|
@@ -230,6 +345,13 @@ fn substBody(body: &mut FnBody, s: &HashMap<String, Type>) {
|
|
|
230
345
|
*t = substType(t, s);
|
|
231
346
|
}
|
|
232
347
|
}
|
|
348
|
+
if let StmtKind::Match(m) = &mut st.kind {
|
|
349
|
+
for c in &mut m.cases {
|
|
350
|
+
for p in &mut c.patterns {
|
|
351
|
+
substPattern(p, s);
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
}
|
|
233
355
|
},
|
|
234
356
|
&mut |e| match &mut e.kind {
|
|
235
357
|
ExprKind::Closure(c) => {
|
|
@@ -242,6 +364,19 @@ fn substBody(body: &mut FnBody, s: &HashMap<String, Type>) {
|
|
|
242
364
|
*t = substType(t, s);
|
|
243
365
|
}
|
|
244
366
|
}
|
|
367
|
+
// `str.typeName[Self]()` (`@typeName(Self)`), `findAs[Self](..)`.
|
|
368
|
+
ExprKind::FnCall(c) => {
|
|
369
|
+
for t in &mut c.type_args {
|
|
370
|
+
*t = substType(t, s);
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
ExprKind::Attribute(a) => {
|
|
374
|
+
if let AttrKind::Method(c) = &mut a.attr {
|
|
375
|
+
for t in &mut c.type_args {
|
|
376
|
+
*t = substType(t, s);
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
}
|
|
245
380
|
_ => {}
|
|
246
381
|
},
|
|
247
382
|
);
|
compiler/core/tests/core/formatter_test.rs
CHANGED
|
@@ -393,3 +393,23 @@ fn moduleLevelConstantsFormat() {
|
|
|
393
393
|
assert_eq!(out, input);
|
|
394
394
|
assert_eq!(formatSource(&out).expect("formats twice"), out);
|
|
395
395
|
}
|
|
396
|
+
|
|
397
|
+
/// A supertrait and a downcast with type arguments keep their spaces.
|
|
398
|
+
#[test]
|
|
399
|
+
fn supertraitsAndDowncastArgumentsFormat() {
|
|
400
|
+
let input = "\
|
|
401
|
+
trait Screen[S, M] is Actor[M] =
|
|
402
|
+
fun react(self) -> Self = self
|
|
403
|
+
|
|
404
|
+
fun f(a: Actor[Msg]) -> Int = match a
|
|
405
|
+
Screen[Int, Msg] as s => 1
|
|
406
|
+
_ => 0
|
|
407
|
+
|
|
408
|
+
fun n() -> Str = @typeName(Button[Msg])
|
|
409
|
+
";
|
|
410
|
+
let once = formatSource(input).expect("first pass");
|
|
411
|
+
assert!(once.contains("trait Screen[S, M] is Actor[M] ="), "got: {once}");
|
|
412
|
+
assert!(once.contains("Screen[Int, Msg] as s =>"), "got: {once}");
|
|
413
|
+
assert!(once.contains("= @typeName(Button[Msg])"), "got: {once}");
|
|
414
|
+
assert_eq!(once, formatSource(&once).expect("second pass"), "idempotent");
|
|
415
|
+
}
|
compiler/core/tests/core/traits_parse_test.rs
CHANGED
|
@@ -128,19 +128,40 @@ fn downcastPattern() {
|
|
|
128
128
|
match a
|
|
129
129
|
Orb as o => o.id
|
|
130
130
|
Some(Label as l) => 1
|
|
131
|
+
Box[Msg] as b => 2
|
|
132
|
+
Screen[S, M] as s => 3
|
|
131
133
|
_ => 0
|
|
132
134
|
",
|
|
133
135
|
);
|
|
134
136
|
let f = fnOf(&s, None, "f");
|
|
135
137
|
let FnBody::Block(b) = &f.body else { panic!("block") };
|
|
136
138
|
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() });
|
|
139
|
+
assert_eq!(m.cases[0].patterns[0], CasePattern::As { ty: "Orb".to_string(), name: "o".to_string(), args: vec![] });
|
|
138
140
|
assert_eq!(
|
|
139
141
|
m.cases[1].patterns[0],
|
|
140
|
-
CasePattern::class("Some".to_string(), vec![CasePattern::As { ty: "Label".to_string(), name: "l".to_string() }])
|
|
142
|
+
CasePattern::class("Some".to_string(), vec![CasePattern::As { ty: "Label".to_string(), name: "l".to_string(), args: vec![] }])
|
|
143
|
+
);
|
|
144
|
+
assert_eq!(m.cases[2].patterns[0], CasePattern::As { ty: "Box".to_string(), name: "b".to_string(), args: vec![named("Msg")] });
|
|
145
|
+
assert_eq!(
|
|
146
|
+
m.cases[3].patterns[0],
|
|
147
|
+
CasePattern::As { ty: "Screen".to_string(), name: "s".to_string(), args: vec![named("S"), named("M")] }
|
|
141
148
|
);
|
|
142
149
|
}
|
|
143
150
|
|
|
151
|
+
#[test]
|
|
152
|
+
fn supertraits() {
|
|
153
|
+
let s = plum_test_support::parseRawSource(
|
|
154
|
+
"trait Screen[S, M] is Actor[M], Named =
|
|
155
|
+
fun react(self, state: S, msg: M) -> Self = self
|
|
156
|
+
",
|
|
157
|
+
);
|
|
158
|
+
let t = traitOf(&s, "Screen");
|
|
159
|
+
assert_eq!(t.supers, vec![ty("Actor", vec![named("M")]), named("Named")]);
|
|
160
|
+
assert_eq!(t.methods.len(), 1);
|
|
161
|
+
let plain = plum_test_support::parseRawSource("trait Actor =\n fun key(self) -> Int\n");
|
|
162
|
+
assert!(traitOf(&plain, "Actor").supers.is_empty());
|
|
163
|
+
}
|
|
164
|
+
|
|
144
165
|
#[test]
|
|
145
166
|
fn downcastBinderThatShadowsALocalIsRenamed() {
|
|
146
167
|
let s = plum_test_support::parse(
|
|
@@ -163,3 +184,20 @@ fn downcastBinderThatShadowsALocalIsRenamed() {
|
|
|
163
184
|
// the outer `o` is untouched
|
|
164
185
|
assert!(format!("{:?}", b.stmts[2]).contains("Var(\"o\")"));
|
|
165
186
|
}
|
|
187
|
+
|
|
188
|
+
/// `@typeName(T)` is std's `str.typeName[T]()`; anything else stays a call named `@name`.
|
|
189
|
+
#[test]
|
|
190
|
+
fn compileTimeBuiltinCalls() {
|
|
191
|
+
let s = plum_test_support::parseRawSource("fun f() -> Str = @typeName(Button[Msg])\n\nfun g(x: Int) = @nope(x, Orb)\n");
|
|
192
|
+
let FnBody::Expr(e) = &fnOf(&s, None, "f").body else { panic!("expr body") };
|
|
193
|
+
let ExprKind::Attribute(a) = &e.kind else { panic!("{e:?}") };
|
|
194
|
+
assert!(matches!(&a.object.kind, ExprKind::Var(m) if m == "str"));
|
|
195
|
+
let AttrKind::Method(c) = &a.attr else { panic!("method") };
|
|
196
|
+
assert_eq!(c.name, "typeName");
|
|
197
|
+
assert_eq!(c.type_args, vec![ty("Button", vec![named("Msg")])]);
|
|
198
|
+
let FnBody::Expr(e) = &fnOf(&s, None, "g").body else { panic!("expr body") };
|
|
199
|
+
let ExprKind::FnCall(c) = &e.kind else { panic!("{e:?}") };
|
|
200
|
+
assert_eq!(c.name, "@nope");
|
|
201
|
+
assert_eq!(c.args.len(), 1);
|
|
202
|
+
assert_eq!(c.type_args, vec![named("Orb")]);
|
|
203
|
+
}
|
compiler/tooling/tree-sitter-plum/grammar.js
CHANGED
|
@@ -107,6 +107,8 @@ module.exports = grammar({
|
|
|
107
107
|
"trait",
|
|
108
108
|
field("name", $.type_identifier),
|
|
109
109
|
field("generics", optional($.generics)),
|
|
110
|
+
// `trait Screen[S, M] is Actor[M]`: its supertraits.
|
|
111
|
+
optional(field("implements", $.implements)),
|
|
110
112
|
"=",
|
|
111
113
|
$._indent,
|
|
112
114
|
field("methods", repeat($.fn)),
|
|
@@ -478,8 +480,14 @@ module.exports = grammar({
|
|
|
478
480
|
),
|
|
479
481
|
|
|
480
482
|
// `Orb as o`: on a trait object, matches a value of type `Orb` and binds it as one.
|
|
483
|
+
// `Box[Msg] as b` and `Screen[S, M] as s` name the type arguments.
|
|
481
484
|
as_pattern: ($) =>
|
|
485
|
+
seq(
|
|
486
|
+
field("type", $.type_identifier),
|
|
482
|
-
|
|
487
|
+
optional(seq("[", field("args", commaSep1($.type)), "]")),
|
|
488
|
+
"as",
|
|
489
|
+
field("name", $.var_identifier),
|
|
490
|
+
),
|
|
483
491
|
|
|
484
492
|
class_pattern: ($) =>
|
|
485
493
|
seq(
|
|
@@ -522,6 +530,19 @@ module.exports = grammar({
|
|
|
522
530
|
$.class_call,
|
|
523
531
|
$.list_literal,
|
|
524
532
|
$.parenthesized_expression,
|
|
533
|
+
$.builtin_call,
|
|
534
|
+
),
|
|
535
|
+
|
|
536
|
+
// `@typeName(Self)`: a compile-time built-in. Each argument is a type or an
|
|
537
|
+
// expression; each built-in says which it takes (a name that reads as both, like
|
|
538
|
+
// `Self` or `Orb`, is a type).
|
|
539
|
+
builtin_call: ($) =>
|
|
540
|
+
seq(
|
|
541
|
+
"@",
|
|
542
|
+
field("name", $.var_identifier),
|
|
543
|
+
"(",
|
|
544
|
+
optional(seq(commaSep1(field("argument", choice(prec.dynamic(1, $.type), $.expression))), optional(","))),
|
|
545
|
+
")",
|
|
525
546
|
),
|
|
526
547
|
|
|
527
548
|
parenthesized_expression: ($) =>
|
compiler/tooling/tree-sitter-plum/queries/plum/format.scm
CHANGED
|
@@ -144,6 +144,8 @@
|
|
|
144
144
|
|
|
145
145
|
(as_pattern "as" @prepend_space @append_space)
|
|
146
146
|
|
|
147
|
+
(as_pattern "," @append_space)
|
|
148
|
+
|
|
147
149
|
(primitive
|
|
148
150
|
(fn) @prepend_hardline)
|
|
149
151
|
|
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
|
@@ -238,3 +238,107 @@ fun main() =
|
|
|
238
238
|
(expression
|
|
239
239
|
(primary_expression
|
|
240
240
|
(var_identifier)))))))))))
|
|
241
|
+
|
|
242
|
+
==================
|
|
243
|
+
trait with a supertrait and a downcast with type arguments
|
|
244
|
+
==================
|
|
245
|
+
|
|
246
|
+
trait Screen[S, M] is Actor[M] =
|
|
247
|
+
fun react(self) -> Self = self
|
|
248
|
+
|
|
249
|
+
fun f(a: Actor[Msg]) -> Int = match a
|
|
250
|
+
Screen[Int, Msg] as s => 1
|
|
251
|
+
_ => 0
|
|
252
|
+
|
|
253
|
+
---
|
|
254
|
+
|
|
255
|
+
(source
|
|
256
|
+
(trait
|
|
257
|
+
(type_identifier)
|
|
258
|
+
(generics
|
|
259
|
+
(type_identifier)
|
|
260
|
+
(type_identifier))
|
|
261
|
+
(implements
|
|
262
|
+
(type
|
|
263
|
+
(type_identifier)
|
|
264
|
+
(type
|
|
265
|
+
(type_identifier))))
|
|
266
|
+
(fn
|
|
267
|
+
(fn_identifier)
|
|
268
|
+
(self)
|
|
269
|
+
(type
|
|
270
|
+
(type_identifier))
|
|
271
|
+
(expression
|
|
272
|
+
(primary_expression
|
|
273
|
+
(self)))))
|
|
274
|
+
(fn
|
|
275
|
+
(fn_identifier)
|
|
276
|
+
(param
|
|
277
|
+
(var_identifier)
|
|
278
|
+
(type
|
|
279
|
+
(type_identifier)
|
|
280
|
+
(type
|
|
281
|
+
(type_identifier))))
|
|
282
|
+
(type
|
|
283
|
+
(type_identifier))
|
|
284
|
+
(expression
|
|
285
|
+
(match
|
|
286
|
+
(expression
|
|
287
|
+
(primary_expression
|
|
288
|
+
(var_identifier)))
|
|
289
|
+
(case
|
|
290
|
+
(case_pattern
|
|
291
|
+
(as_pattern
|
|
292
|
+
(type_identifier)
|
|
293
|
+
(type
|
|
294
|
+
(type_identifier))
|
|
295
|
+
(type
|
|
296
|
+
(type_identifier))
|
|
297
|
+
(var_identifier)))
|
|
298
|
+
(expression
|
|
299
|
+
(primary_expression
|
|
300
|
+
(integer))))
|
|
301
|
+
(case
|
|
302
|
+
(case_pattern)
|
|
303
|
+
(expression
|
|
304
|
+
(primary_expression
|
|
305
|
+
(integer))))))))
|
|
306
|
+
|
|
307
|
+
==================
|
|
308
|
+
compile-time built-in calls
|
|
309
|
+
==================
|
|
310
|
+
|
|
311
|
+
fun f() -> Str = @typeName(Button[Msg])
|
|
312
|
+
|
|
313
|
+
fun g() = @foo(x + 1, Self)
|
|
314
|
+
|
|
315
|
+
---
|
|
316
|
+
|
|
317
|
+
(source
|
|
318
|
+
(fn
|
|
319
|
+
(fn_identifier)
|
|
320
|
+
(type
|
|
321
|
+
(type_identifier))
|
|
322
|
+
(expression
|
|
323
|
+
(primary_expression
|
|
324
|
+
(builtin_call
|
|
325
|
+
(var_identifier)
|
|
326
|
+
(type
|
|
327
|
+
(type_identifier)
|
|
328
|
+
(type
|
|
329
|
+
(type_identifier)))))))
|
|
330
|
+
(fn
|
|
331
|
+
(fn_identifier)
|
|
332
|
+
(expression
|
|
333
|
+
(primary_expression
|
|
334
|
+
(builtin_call
|
|
335
|
+
(var_identifier)
|
|
336
|
+
(expression
|
|
337
|
+
(primary_expression
|
|
338
|
+
(binary_operator
|
|
339
|
+
(primary_expression
|
|
340
|
+
(var_identifier))
|
|
341
|
+
(primary_expression
|
|
342
|
+
(integer)))))
|
|
343
|
+
(type
|
|
344
|
+
(type_identifier)))))))
|
compiler/wasm-codegen/src/emit.rs
CHANGED
|
@@ -27,10 +27,15 @@ impl<'a> Emit<'a> {
|
|
|
27
27
|
subst: &u.subst,
|
|
28
28
|
types: unit_types(u),
|
|
29
29
|
};
|
|
30
|
+
let body = if crate::intrinsics::isTypeNameFn(f) {
|
|
31
|
+
compileFnBody(&crate::intrinsics::typeNameBody(f, &u.subst), &ctx, state, &uref)
|
|
32
|
+
.map_err(|e| format!("{e} (in '{}')", u.name))?
|
|
33
|
+
} else {
|
|
30
|
-
|
|
34
|
+
match compileIntrinsicFnBody(f, &u.subst) {
|
|
31
|
-
|
|
35
|
+
Some(body) => body,
|
|
32
|
-
|
|
36
|
+
None => compileFnBody(f, &ctx, state, &uref)
|
|
33
|
-
|
|
37
|
+
.map_err(|e| format!("{e} (in '{}')", u.name))?,
|
|
38
|
+
}
|
|
34
39
|
};
|
|
35
40
|
let idx = match u.inst {
|
|
36
41
|
Some(id) => ctx.inst_funcs[&id].0,
|
|
@@ -90,7 +95,11 @@ impl<'a> Emit<'a> {
|
|
|
90
95
|
let unit_types = |u: &UnitDef| unitTypesOf(&ctx.inst_types, &ctx.base_types, u);
|
|
91
96
|
// Compile each closure literal's own body into its reserved function slot.
|
|
92
97
|
let mut closure_bodies: Vec<(u32, Vec<u8>)> = Vec::new();
|
|
98
|
+
// In function order: `closures` is a hash map, and the data segments the bodies add
|
|
99
|
+
// (string literals) must come out in the same order on every compile.
|
|
100
|
+
let mut ordered: Vec<(&(usize, usize), &ClosureInfo)> = ctx.closures.iter().collect();
|
|
101
|
+
ordered.sort_by_key(|(_, info)| info.func_idx);
|
|
93
|
-
for ((ui, ptr), info) in
|
|
102
|
+
for ((ui, ptr), info) in ordered {
|
|
94
103
|
let cl = ctx
|
|
95
104
|
.closure_asts
|
|
96
105
|
.get(&(*ui, *ptr))
|
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: named, name } => {
|
|
67
|
+
ast::CasePattern::As { ty: named, name, args } => {
|
|
68
|
-
self.bind(name, asPatternType(named, ty, &self.types.subst));
|
|
68
|
+
self.bind(name, asPatternType(named, args, ty, &self.types.subst));
|
|
69
69
|
}
|
|
70
70
|
ast::CasePattern::Class { name, fields, .. } => {
|
|
71
71
|
let key = patKey(pat);
|
compiler/wasm-codegen/src/intrinsics.rs
CHANGED
|
@@ -22,6 +22,27 @@ pub(crate) fn compileIntrinsicFnBody(f: &ast::Fn, subst: &Subst) -> Option<Vec<u
|
|
|
22
22
|
None
|
|
23
23
|
}
|
|
24
24
|
|
|
25
|
+
/// `str.typeName[T]()` (std/Str.plum): its body is the name of the type `T` its
|
|
26
|
+
/// instantiation has, without type arguments.
|
|
27
|
+
pub(crate) fn isTypeNameFn(f: &ast::Fn) -> bool {
|
|
28
|
+
f.type_param.is_none() && f.name == "typeName" && f.file.replace('\\', "/").ends_with("std/Str.plum")
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/// The body of `typeName[T]` with `T` as `subst` has it: the bare name as a string
|
|
32
|
+
/// literal (`Button[Msg]` gives "Button"), compiled like any body.
|
|
33
|
+
pub(crate) fn typeNameBody(f: &ast::Fn, subst: &Subst) -> ast::Fn {
|
|
34
|
+
let name = match f.generics.first().and_then(|g| subst.get(g)) {
|
|
35
|
+
Some(t) => plum_checker::nominalName(t).map(|n| n.to_string()).unwrap_or_else(|| {
|
|
36
|
+
let s = t.to_string();
|
|
37
|
+
s.split('[').next().unwrap_or("").to_string()
|
|
38
|
+
}),
|
|
39
|
+
None => String::new(),
|
|
40
|
+
};
|
|
41
|
+
let mut g = f.clone();
|
|
42
|
+
g.body = ast::FnBody::Expr(ast::Expr::String(ast::StringExpr { parts: vec![ast::StringPart::Text(name)] }));
|
|
43
|
+
g
|
|
44
|
+
}
|
|
45
|
+
|
|
25
46
|
/// A function of the std module `mem` (`std/mem.plum`): its bodies are intrinsics.
|
|
26
47
|
pub(crate) fn isMemFn(f: &ast::Fn) -> bool {
|
|
27
48
|
f.type_param.is_none() && f.file.replace('\\', "/").ends_with("std/mem.plum")
|
compiler/wasm-codegen/src/matching.rs
CHANGED
|
@@ -351,14 +351,14 @@ pub(crate) fn compileCasePositions(
|
|
|
351
351
|
let pat = &case.patterns[pos];
|
|
352
352
|
let (subject_vt, scratch_local) = all_subjects[pos];
|
|
353
353
|
match pat {
|
|
354
|
-
ast::CasePattern::As { ty, name } => {
|
|
354
|
+
ast::CasePattern::As { ty, name, args } => {
|
|
355
355
|
let subject_ty = ctx
|
|
356
356
|
.subject_ptypes
|
|
357
357
|
.borrow()
|
|
358
358
|
.get(&scratch_local)
|
|
359
359
|
.cloned()
|
|
360
360
|
.unwrap_or_else(|| plumTypeFromValtypeHint(subject_vt));
|
|
361
|
-
let target = asTarget(ty, &subject_ty, ctx.unit_subst, ctx.gc_types);
|
|
361
|
+
let target = asTarget(ty, args, &subject_ty, ctx.unit_subst, ctx.gc_types);
|
|
362
362
|
let bind = |cast: Option<u32>, t: &PlumType, body: &mut Vec<u8>| -> Result<(), String> {
|
|
363
363
|
let idx = ctx
|
|
364
364
|
.locals
|
|
@@ -379,12 +379,11 @@ pub(crate) fn compileCasePositions(
|
|
|
379
379
|
compileCasePositions(case, pos + 1, all_subjects, rest, result_vt, exhaustive_fallback, body, ctx, state)
|
|
380
380
|
}
|
|
381
381
|
AsTarget::Never => compileMatchArmsMulti(rest, all_subjects, result_vt, exhaustive_fallback, body, ctx, state),
|
|
382
|
-
AsTarget::Test(
|
|
382
|
+
AsTarget::Test(tags, cast, t) => {
|
|
383
|
-
Instruction::LocalGet(scratch_local).encode(
|
|
383
|
+
AsTarget::emitTest(&tags, body, &mut |b| Instruction::LocalGet(scratch_local).encode(b));
|
|
384
|
-
Instruction::RefTestNonNull(HeapType::Concrete(tag)).encode(body);
|
|
385
384
|
Instruction::If(blockTypeFor(result_vt)).encode(body);
|
|
386
385
|
let _tg = TailDepth::enter(&ctx.tail_depth);
|
|
387
|
-
bind(
|
|
386
|
+
bind(cast, &t, body)?;
|
|
388
387
|
compileCasePositions(case, pos + 1, all_subjects, rest, result_vt, exhaustive_fallback, body, ctx, state)?;
|
|
389
388
|
Instruction::Else.encode(body);
|
|
390
389
|
compileMatchArmsMulti(rest, all_subjects, result_vt, exhaustive_fallback, body, ctx, state)?;
|
|
@@ -792,8 +791,8 @@ pub(crate) fn compileFieldPatterns(
|
|
|
792
791
|
let inst_vt = plumTypeToValtype(field_ty);
|
|
793
792
|
|
|
794
793
|
match pat {
|
|
795
|
-
ast::CasePattern::As { ty, name } => {
|
|
794
|
+
ast::CasePattern::As { ty, name, args } => {
|
|
796
|
-
let target = asTarget(ty, field_ty, ctx.unit_subst, ctx.gc_types);
|
|
795
|
+
let target = asTarget(ty, args, field_ty, ctx.unit_subst, ctx.gc_types);
|
|
797
796
|
let idx = ctx
|
|
798
797
|
.locals
|
|
799
798
|
.get(name)
|
|
@@ -817,12 +816,11 @@ pub(crate) fn compileFieldPatterns(
|
|
|
817
816
|
compileFieldPatterns(fields, field_types, inst_types, fpos + 1, container_local, container_type_idx, leaf_map, rest, all_subjects, result_vt, exhaustive_fallback, body, ctx, state, on_match)
|
|
818
817
|
}
|
|
819
818
|
AsTarget::Never => compileMatchArmsMulti(rest, all_subjects, result_vt, exhaustive_fallback, body, ctx, state),
|
|
820
|
-
AsTarget::Test(
|
|
819
|
+
AsTarget::Test(tags, cast, t) => {
|
|
821
|
-
|
|
820
|
+
AsTarget::emitTest(&tags, body, &mut |b| emitContainerField(b, ctx, container_local, container_type_idx, fpos, leaf_map));
|
|
822
|
-
Instruction::RefTestNonNull(HeapType::Concrete(tag)).encode(body);
|
|
823
821
|
Instruction::If(blockTypeFor(result_vt)).encode(body);
|
|
824
822
|
let _tg = TailDepth::enter(&ctx.tail_depth);
|
|
825
|
-
load(
|
|
823
|
+
load(cast, &t, body)?;
|
|
826
824
|
compileFieldPatterns(fields, field_types, inst_types, fpos + 1, container_local, container_type_idx, leaf_map, rest, all_subjects, result_vt, exhaustive_fallback, body, ctx, state, on_match)?;
|
|
827
825
|
Instruction::Else.encode(body);
|
|
828
826
|
compileMatchArmsMulti(rest, all_subjects, result_vt, exhaustive_fallback, body, ctx, state)?;
|
compiler/wasm-codegen/src/traits.rs
CHANGED
|
@@ -307,18 +307,47 @@ pub(crate) fn compileTraitEq(
|
|
|
307
307
|
|
|
308
308
|
/// What a downcast pattern `ty as name` does against a subject of type `subject`.
|
|
309
309
|
pub(crate) enum AsTarget {
|
|
310
|
-
/// The subject is already of the type (a generic `T as x` where `T` is the subject's
|
|
310
|
+
/// The subject is already of the type (a generic `T as x` where `T` is the subject's
|
|
311
|
+
/// type, or a trait the subject's trait extends).
|
|
311
312
|
Always(PlumType),
|
|
312
313
|
/// No value of the subject's type is ever of this type.
|
|
313
314
|
Never,
|
|
314
|
-
/// A `ref.test` against the
|
|
315
|
+
/// A `ref.test` against each of the tags (any one matches), then the bound value cast
|
|
316
|
+
/// to the type (`Some`), or kept as an `anyref` (a trait object: `None`).
|
|
317
|
+
Test(Vec<u32>, Option<u32>, PlumType),
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
impl AsTarget {
|
|
321
|
+
/// Leaves 1 on the stack if the value `load` pushes is one of `tags`, else 0.
|
|
322
|
+
pub(crate) fn emitTest(tags: &[u32], body: &mut Vec<u8>, load: &mut dyn FnMut(&mut Vec<u8>)) {
|
|
323
|
+
for (i, tag) in tags.iter().enumerate() {
|
|
324
|
+
load(body);
|
|
325
|
+
Instruction::RefTestNonNull(HeapType::Concrete(*tag)).encode(body);
|
|
326
|
+
if i > 0 {
|
|
327
|
+
Instruction::I32Or.encode(body);
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
/// `ty` (a downcast's written type argument) with the generics of `subst` substituted.
|
|
334
|
+
fn astTypeIn(ty: &ast::Type, subst: &Subst) -> PlumType {
|
|
335
|
+
if ty.generics.is_empty() {
|
|
336
|
+
if let Some(t) = subst.get(&ty.name) {
|
|
315
|
-
|
|
337
|
+
return t.clone();
|
|
338
|
+
}
|
|
339
|
+
return plum_checker::plumTypeFromName(&ty.name);
|
|
340
|
+
}
|
|
341
|
+
PlumType::TApp(ty.name.clone(), ty.generics.iter().map(|g| astTypeIn(g, subst)).collect())
|
|
316
342
|
}
|
|
317
343
|
|
|
318
344
|
/// The type a downcast pattern names: a declared type, (in an instantiated body) the type a
|
|
319
345
|
/// generic parameter stands for, or a generic implementer with the arguments the trait
|
|
320
346
|
/// object `subject` gives it (`Box as b` on an `Actor[Msg]`: `Box[Msg]`).
|
|
321
|
-
pub(crate) fn asPatternType(ty: &str, subject: &PlumType, subst: &Subst) -> PlumType {
|
|
347
|
+
pub(crate) fn asPatternType(ty: &str, args: &[ast::Type], subject: &PlumType, subst: &Subst) -> PlumType {
|
|
348
|
+
if !args.is_empty() {
|
|
349
|
+
return PlumType::TApp(ty.to_string(), args.iter().map(|a| astTypeIn(a, subst)).collect());
|
|
350
|
+
}
|
|
322
351
|
if let Some(t) = subst.get(ty) {
|
|
323
352
|
return t.clone();
|
|
324
353
|
}
|
|
@@ -327,16 +356,30 @@ pub(crate) fn asPatternType(ty: &str, subject: &PlumType, subst: &Subst) -> Plum
|
|
|
327
356
|
.unwrap_or_else(|| plum_checker::plumTypeFromName(ty))
|
|
328
357
|
}
|
|
329
358
|
|
|
330
|
-
pub(crate) fn asTarget(ty: &str, subject: &PlumType, subst: &Subst, reg: &GcTypeRegistry) -> AsTarget {
|
|
359
|
+
pub(crate) fn asTarget(ty: &str, args: &[ast::Type], subject: &PlumType, subst: &Subst, reg: &GcTypeRegistry) -> AsTarget {
|
|
331
|
-
let target = asPatternType(ty, subject, subst);
|
|
360
|
+
let target = asPatternType(ty, args, subject, subst);
|
|
332
361
|
if canonTy(&target) == canonTy(subject) {
|
|
333
362
|
return AsTarget::Always(target);
|
|
334
363
|
}
|
|
335
|
-
if !isTraitObjectTy(subject) ||
|
|
364
|
+
if !isTraitObjectTy(subject) || isValueTy(&target) {
|
|
336
365
|
return AsTarget::Never;
|
|
337
366
|
}
|
|
367
|
+
if isTraitObjectTy(&target) {
|
|
368
|
+
// A downcast to a trait: a test over the types that implement it (each also a
|
|
369
|
+
// `subject`, or the test never passes for it), and the value stays a trait object.
|
|
370
|
+
let traits = programTraits();
|
|
371
|
+
if traits.supertraitsOf(subject).iter().any(|s| canonTy(s) == canonTy(&target)) {
|
|
372
|
+
return AsTarget::Always(target);
|
|
373
|
+
}
|
|
374
|
+
let tags: Vec<u32> = implementersOf(&target, reg, &traits)
|
|
375
|
+
.iter()
|
|
376
|
+
.filter(|c| implementersOf(subject, reg, &traits).contains(c))
|
|
377
|
+
.filter_map(|c| tagIdx(c, reg))
|
|
378
|
+
.collect();
|
|
379
|
+
return if tags.is_empty() { AsTarget::Never } else { AsTarget::Test(tags, None, target) };
|
|
380
|
+
}
|
|
338
381
|
match tagIdx(&target, reg) {
|
|
339
|
-
Some(idx) => AsTarget::Test(idx, target),
|
|
382
|
+
Some(idx) => AsTarget::Test(vec![idx], Some(idx), target),
|
|
340
383
|
None => AsTarget::Never,
|
|
341
384
|
}
|
|
342
385
|
}
|
compiler/wasm-codegen/tests/wasm_codegen/fusion_alloc_test.rs
CHANGED
|
@@ -791,6 +791,79 @@ fun main() -> Int = spin(Ship(label: \"a\", x: 0, y: 0), 10, 0) + spin(rock(), 3
|
|
|
791
791
|
assert_eq!(runInt(&engine(false), &wasm).0, 54);
|
|
792
792
|
}
|
|
793
793
|
|
|
794
|
+
// ---- trait inheritance and downcasts to a trait ----
|
|
795
|
+
|
|
796
|
+
const SCREENS: &str = "trait Actor =
|
|
797
|
+
fun key(self) -> Int
|
|
798
|
+
fun step(self) -> Self = self
|
|
799
|
+
|
|
800
|
+
trait Screen is Actor =
|
|
801
|
+
fun react(self, n: Int) -> Self = self
|
|
802
|
+
|
|
803
|
+
struct Ship(label: Str, x: Int, y: Int) is Actor =
|
|
804
|
+
fun key(self) -> Int = self.x + self.y
|
|
805
|
+
fun step(self) -> Ship = Ship(..self, x: self.x + 1)
|
|
806
|
+
|
|
807
|
+
struct Play(label: Str, n: Int) is Screen =
|
|
808
|
+
fun key(self) -> Int = self.n
|
|
809
|
+
fun step(self) -> Play = Play(..self, n: self.n + 1)
|
|
810
|
+
fun react(self, n: Int) -> Play = Play(..self, n: self.n + n)
|
|
811
|
+
|
|
812
|
+
struct Menu(label: Str, n: Int) is Screen =
|
|
813
|
+
fun key(self) -> Int = self.n * 1000
|
|
814
|
+
|
|
815
|
+
fun ship() -> Actor = Ship(label: \"s\", x: 1, y: 2)
|
|
816
|
+
|
|
817
|
+
";
|
|
818
|
+
|
|
819
|
+
/// `Screen as s` on an `Actor` is a `ref.test` over Screen's implementers; the binder is a
|
|
820
|
+
/// trait object, and the unshared actor moves into it, so `Play.react`'s spread (through
|
|
821
|
+
/// Screen's dispatcher) writes in place. `s.step()` on a `Screen` is Actor's method through
|
|
822
|
+
/// Screen's dispatcher, and writes in place too.
|
|
823
|
+
#[test]
|
|
824
|
+
fn downcast_to_a_trait_moves_the_actor_and_reuses_it() {
|
|
825
|
+
let body = "fun poke(a: Actor) -> Actor = match a
|
|
826
|
+
Screen as s => s.react(5)
|
|
827
|
+
_ => a
|
|
828
|
+
|
|
829
|
+
fun spin(s: Screen, n: Int) -> Screen = if n == 0 then s else spin(s.step(), n - 1)
|
|
830
|
+
|
|
831
|
+
fun main() -> Int =
|
|
832
|
+
m: Screen := Menu(label: \"m\", n: 2)
|
|
833
|
+
poke(Play(label: \"p\", n: 1)).key() + poke(ship()).key() + spin(Play(label: \"q\", n: 0), 100).key() + spin(m, 3).key()
|
|
834
|
+
";
|
|
835
|
+
let src = load("trait_downcast_to_trait", &format!("{PRE}{SCREENS}{body}"));
|
|
836
|
+
let wasm = compileFbip(&src, true);
|
|
837
|
+
// the play reacts (6), the ship isn't a screen (3), 100 steps, the menu's default step
|
|
838
|
+
assert_eq!(runInt(&engine(false), &wasm).0, 6 + 3 + 100 + 2000);
|
|
839
|
+
assert_eq!(newsIn(&wasm, "Play.react"), 0, "the react writes the screen in place");
|
|
840
|
+
assert_eq!(newsIn(&wasm, "Play.step"), 0, "the step writes the screen in place");
|
|
841
|
+
let copying = compileFbip(&src, false);
|
|
842
|
+
assert_eq!(newsIn(©ing, "Play.react"), 1, "--no-fbip: each react copies");
|
|
843
|
+
assert_eq!(newsIn(©ing, "Play.step"), 1, "--no-fbip: each step copies");
|
|
844
|
+
assert_eq!(runInt(&engine(false), ©ing).0, 6 + 3 + 100 + 2000);
|
|
845
|
+
}
|
|
846
|
+
|
|
847
|
+
/// The actor read after the downcast's arm keeps the arm's calls copies.
|
|
848
|
+
#[test]
|
|
849
|
+
fn downcast_to_a_trait_with_a_live_subject_copies() {
|
|
850
|
+
let body = "fun poke(a: Actor) -> Int = match a
|
|
851
|
+
Screen as s =>
|
|
852
|
+
t := s.react(5)
|
|
853
|
+
t.key() * 100 + a.key()
|
|
854
|
+
_ => a.key()
|
|
855
|
+
|
|
856
|
+
fun main() -> Int =
|
|
857
|
+
_ := ship()
|
|
858
|
+
m: Actor := Menu(label: \"m\", n: 0)
|
|
859
|
+
poke(Play(label: \"p\", n: 1)) + poke(m)
|
|
860
|
+
";
|
|
861
|
+
let src = load("trait_downcast_to_trait_live", &format!("{PRE}{SCREENS}{body}"));
|
|
862
|
+
let wasm = compileFbip(&src, true);
|
|
863
|
+
assert_eq!(newsIn(&wasm, "Play.react"), 1, "`a` is read after the react: a copy");
|
|
864
|
+
assert_eq!(runInt(&engine(false), &wasm).0, 601);
|
|
865
|
+
}
|
|
866
|
+
|
|
794
867
|
// ---- a spread of a field inside a spread of its owner ----
|
|
795
868
|
|
|
796
869
|
/// A trait with a place, and an actor that is never stepped. `Place` is a value struct (its fields
|
|
@@ -907,3 +980,24 @@ fun main() -> Int = spin(Ship(label: \"s\", at: Place(x: 0, y: 0, r: 0, tag: \"p
|
|
|
907
980
|
assert!(newsIn(&wasm, "Place.moveTo") >= 1, "the getter's result is kept: the place copies");
|
|
908
981
|
assert_eq!(runInt(&engine(false), &wasm).0, 57);
|
|
909
982
|
}
|
|
983
|
+
|
|
984
|
+
/// Closure bodies are compiled in function order, not a hash map's: the string literals
|
|
985
|
+
/// they add as data segments come out in the same order on every compile (a dev server
|
|
986
|
+
/// rebuilding an unchanged file must serve the same wasm).
|
|
987
|
+
#[test]
|
|
988
|
+
fn closures_with_string_literals_compile_the_same_every_time() {
|
|
989
|
+
let body = "fun names(xs: List[Int]) -> List[Str] =
|
|
990
|
+
a := xs.map(|x| \"a{x}\")
|
|
991
|
+
b := a.map(|s| \"{s}b\")
|
|
992
|
+
c := b.map(|s| if s == \"\" then \"empty\" else \"<{s}>\")
|
|
993
|
+
d := c.map(|s| \"d {s} d\")
|
|
994
|
+
d.map(|s| \"{s},e,{s}\")
|
|
995
|
+
|
|
996
|
+
fun main() -> Int = names([1, 2, 3]).length()
|
|
997
|
+
";
|
|
998
|
+
let src = load("closure_literal_order", &format!("{PRE}{body}"));
|
|
999
|
+
let first = compile(&src, true);
|
|
1000
|
+
for _ in 0..8 {
|
|
1001
|
+
assert!(compile(&src, true) == first, "the same program compiled to different bytes");
|
|
1002
|
+
}
|
|
1003
|
+
}
|
docs/language.md
CHANGED
|
@@ -580,7 +580,9 @@ fun widthOf(s: Shape) -> Float = match s
|
|
|
580
580
|
_ => 0.0
|
|
581
581
|
```
|
|
582
582
|
|
|
583
|
-
The type may be a generic parameter (`T as t`, with `T` set by the caller: `firstOf[Rect](xs)`), or a generic type whose arguments the trait object fixes (`Keep as k` on a `Reducer[Int]` binds a `Keep[Int]`)
|
|
583
|
+
The type may be a generic parameter (`T as t`, with `T` set by the caller: `firstOf[Rect](xs)`), or a generic type whose arguments the trait object fixes (`Keep as k` on a `Reducer[Int]` binds a `Keep[Int]`) or that you write (`Keep[Int] as k`).
|
|
584
|
+
|
|
585
|
+
It may also be another trait: `Screen[S, M] as s` on an `Actor[M]` matches a value of any type that implements both, and binds it as a `Screen[S, M]` trait object. A trait with type parameters needs them written, and a downcast to a trait that no type implements together with the subject's is an error.
|
|
584
586
|
|
|
585
587
|
**Type parameters.** A trait takes them like a struct, and an implementer names them:
|
|
586
588
|
|
|
@@ -598,6 +600,46 @@ struct Keep[M](last: M) is Reducer[M] =
|
|
|
598
600
|
|
|
599
601
|
`Reducer[Int]` is a trait object, and two of them are the same type when their arguments are equal. A generic implementer built where its trait is expected takes the trait's arguments (`Keep(..)` as a `Reducer[Int]` is a `Keep[Int]`); one built first and used there later takes them from that first use.
|
|
600
602
|
|
|
603
|
+
### Statics
|
|
604
|
+
|
|
605
|
+
A trait may declare a static, a `fun` without `self`. Like a method, it is required without a body and optional with one; a default is copied into each implementer, so `Self` in it is that type. A default may call the type's statics as `Self.name()`, and on a trait object that runs the value's own type's static:
|
|
606
|
+
|
|
607
|
+
```plum
|
|
608
|
+
trait Named =
|
|
609
|
+
fun name() -> Str = @typeName(Self) # each type's own name by default
|
|
610
|
+
fun label(self) -> Str = "<{Self.name()}>"
|
|
611
|
+
|
|
612
|
+
struct PlayScreen(id: Int) is Named # PlayScreen.name() is "PlayScreen"
|
|
613
|
+
|
|
614
|
+
struct Menu(id: Int) is Named =
|
|
615
|
+
fun name() -> Str = "menu" # an override
|
|
616
|
+
```
|
|
617
|
+
|
|
618
|
+
A static and a method can't share a name on one type (a type has one function per name), so a trait that wants both gives them different names (`name()` and `label(self)` above). A type's static where the trait has a method, or the other way round, is an error.
|
|
619
|
+
|
|
620
|
+
### Inheritance
|
|
621
|
+
|
|
622
|
+
A trait may extend others, written like a type's `is` clause:
|
|
623
|
+
|
|
624
|
+
```plum
|
|
625
|
+
trait Actor[M] =
|
|
626
|
+
fun key(self) -> Int
|
|
627
|
+
fun step(self, dt: Float) -> Self = self
|
|
628
|
+
|
|
629
|
+
trait Screen[S, M] is Actor[M] =
|
|
630
|
+
fun react(self, state: S, msg: M) -> Self = self
|
|
631
|
+
fun title(self) -> Str = "screen {self.key()}" # a default may call Actor's methods
|
|
632
|
+
|
|
633
|
+
struct Play(id: Int, score: Int) is Screen[Int, Msg] =
|
|
634
|
+
fun key(self) -> Int = self.id # Actor's required method
|
|
635
|
+
fun react(self, state: Int, msg: Msg) -> Play = Play(..self, score: state)
|
|
636
|
+
```
|
|
637
|
+
|
|
638
|
+
- A type that `is Screen[Int, Msg]` is an `Actor[Msg]` as well: `is Screen[..]` implies `is Actor[..]`, with the arguments carried over, so the type must define Actor's required methods too and takes Actor's defaults for the rest. An error about one of them names the `Actor` entry and where it comes from (`Play is missing method 'key' of Actor[Msg] (Screen[Int, Msg] extends Actor[Msg])`). Writing `is Screen[Int, Msg], Actor[Msg]` is the same.
|
|
639
|
+
- On a `Screen[S, M]` trait object you can call Actor's methods too (`s.key()`, `s.step(dt)`, which returns a `Screen[S, M]`), and so can Screen's defaults on `self`.
|
|
640
|
+
- A `Screen[S, M]` is accepted wherever an `Actor[M]` is expected, with no cast and no runtime cost (both are the same reference). The other way is a downcast: `Screen[S, M] as s`.
|
|
641
|
+
- A subtrait can't declare a method its supertrait has, and a trait can't extend itself.
|
|
642
|
+
|
|
601
643
|
### Bounds
|
|
602
644
|
|
|
603
645
|
`[T: Shape]` (or `[T: Tr[X]]`, `[T: A + B]`) on a fn, method, struct or enum says `T` must implement the trait. In the body a `T` has the trait's methods, and one returning `Self` returns a `T`. A bound's arguments may name the other parameters:
|
|
@@ -620,10 +662,19 @@ A value of an implementing type becomes a trait object, with no cast, where one
|
|
|
620
662
|
- a duplicate `is` entry, or a type implementing the same trait twice with methods that clash;
|
|
621
663
|
- `Self` outside a trait;
|
|
622
664
|
- a method that isn't in the trait called on a trait object, or a field read on one (match `Type as x` first);
|
|
623
|
-
- a value used as a trait it doesn't implement, or a downcast to a type that doesn't implement it;
|
|
665
|
+
- a value used as a trait it doesn't implement, or a downcast to a type that doesn't implement it, or to a trait no type shares with it;
|
|
666
|
+
- a supertrait that isn't a trait or has the wrong number of arguments, a trait that extends itself, or a subtrait that declares its supertrait's method again;
|
|
624
667
|
- a bound not met at a use, naming the missing trait;
|
|
625
668
|
- a method whose `Self` inside a parameter or the result can't be checked with the trait object there (`xs: List[Rect] := ..; xs` as a `List[Self]`): build the value where it is returned.
|
|
626
669
|
|
|
670
|
+
## Compile-time built-ins
|
|
671
|
+
|
|
672
|
+
`@name(args)` calls a built-in the compiler evaluates while it compiles. Each built-in says what its arguments are, types or values. An unknown `@name`, or the wrong arguments, is an error that lists what exists.
|
|
673
|
+
|
|
674
|
+
| Built-in | Gives |
|
|
675
|
+
|---|---|
|
|
676
|
+
| `@typeName(T)` | the name of the type `T` as a `Str`, without type arguments: `@typeName(Button[Msg])` is `"Button"`. With a generic `T` it is the type of each instantiation, and `@typeName(Self)` in a trait's default is each implementer's own name (see [Statics](#statics)). |
|
|
677
|
+
|
|
627
678
|
## Modules
|
|
628
679
|
|
|
629
680
|
Each file is a module. A file starts with its imports. Nothing is implicit, not even `Int` or `Str` methods, and each file imports what it uses.
|
std/Str.plum
CHANGED
|
@@ -654,6 +654,13 @@ struct Str(data: Array[Byte], start: Int, len: Int) =
|
|
|
654
654
|
# `"{expr}"` interpolation is a compiler/codegen feature (not a Str method
|
|
655
655
|
# above), but Str is what it produces, so its regression coverage lives here.
|
|
656
656
|
|
|
657
|
+
|
|
658
|
+
# The name of the type `T`, without its type arguments (`Button[Msg]` gives "Button"):
|
|
659
|
+
# a compiler intrinsic, resolved once `T` is a concrete type (see `wasm-codegen`'s
|
|
660
|
+
# intrinsics). `typeName[Self]()` in a trait's default gives each implementer's own name.
|
|
661
|
+
fun typeName[T]() -> Str =
|
|
662
|
+
todo
|
|
663
|
+
|
|
657
664
|
test "split divides on every occurrence of the separator"
|
|
658
665
|
parts := "a,b,c".split(",", 0)
|
|
659
666
|
assert parts.length() == 3
|
tests/traits/inlined_arg_pin.plum
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import std/Int
|
|
2
|
+
import std/Str
|
|
3
|
+
|
|
4
|
+
# A generic static call whose type argument only the callee's parameter fixes
|
|
5
|
+
# (`use(Holder.of(Lit(n: 3)))`: `Holder[M]` pinned by `use`'s `Holder[Int]`). When `use` is
|
|
6
|
+
# inlined, its parameter becomes a local, which keeps the parameter's type (it was
|
|
7
|
+
# untyped, so the call's `M` was never fixed and codegen found no `Holder.of`).
|
|
8
|
+
|
|
9
|
+
trait Thing[M] =
|
|
10
|
+
fun key(self) -> Int
|
|
11
|
+
|
|
12
|
+
struct Holder[M](top: Thing[M]) =
|
|
13
|
+
fun of(top: Thing[M]) -> Holder[M] = Holder(top: top)
|
|
14
|
+
|
|
15
|
+
struct Lit(n: Int) is Thing[Int] =
|
|
16
|
+
fun key(self) -> Int = self.n
|
|
17
|
+
|
|
18
|
+
fun use(h: Holder[Int]) -> Int = h.top.key()
|
|
19
|
+
|
|
20
|
+
# Generic: its parameter's type names `T`, so the local stays untyped.
|
|
21
|
+
fun twice[T](x: T, f: fn(T) -> Int) -> Int = f(x) + f(x)
|
|
22
|
+
|
|
23
|
+
fun keyOf(h: Holder[Int]) -> Int =
|
|
24
|
+
k := h.top.key()
|
|
25
|
+
k * 1
|
|
26
|
+
|
|
27
|
+
test "an inlined callee's parameter pins a generic argument"
|
|
28
|
+
assert use(Holder.of(Lit(n: 3))) == 3
|
|
29
|
+
n := use(Holder.of(Lit(n: 4)))
|
|
30
|
+
assert n == 4
|
|
31
|
+
assert twice(keyOf(Holder.of(Lit(n: 5))), |x| x * 2) == 20
|
tests/traits/statics_and_type_name.plum
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import std/Int
|
|
2
|
+
import std/Str
|
|
3
|
+
import std/List
|
|
4
|
+
|
|
5
|
+
# Trait statics (`fun name() -> Str`, no self) with defaults, `Self.name()` in a default,
|
|
6
|
+
# and the compile-time built-in `@typeName(T)`: the bare name, per instantiation of a
|
|
7
|
+
# generic `T`, per implementer through a trait's default, and through dispatch.
|
|
8
|
+
|
|
9
|
+
trait Named =
|
|
10
|
+
fun name() -> Str = @typeName(Self)
|
|
11
|
+
fun label(self) -> Str = "<{Self.name()}>"
|
|
12
|
+
|
|
13
|
+
struct PlayScreen(id: Int) is Named
|
|
14
|
+
|
|
15
|
+
struct Own(id: Int) is Named =
|
|
16
|
+
fun name() -> Str = "mine"
|
|
17
|
+
|
|
18
|
+
trait Kind[M] =
|
|
19
|
+
fun kind() -> Str = @typeName(Self)
|
|
20
|
+
fun kindOf(self) -> Str = Self.kind()
|
|
21
|
+
|
|
22
|
+
struct Box[M](id: Int) is Kind[M]
|
|
23
|
+
|
|
24
|
+
struct Plain(id: Int) is Kind[Int]
|
|
25
|
+
|
|
26
|
+
fun gen[T]() -> Str = @typeName(T)
|
|
27
|
+
|
|
28
|
+
test "@typeName gives the bare name of a type"
|
|
29
|
+
assert @typeName(Int) == "Int"
|
|
30
|
+
assert @typeName(Box[Str]) == "Box"
|
|
31
|
+
assert @typeName(PlayScreen) == "PlayScreen"
|
|
32
|
+
|
|
33
|
+
test "@typeName of a generic parameter is its type per instantiation"
|
|
34
|
+
assert gen[Box[Int]]() == "Box"
|
|
35
|
+
assert gen[Str]() == "Str"
|
|
36
|
+
assert gen[Own]() == "Own"
|
|
37
|
+
|
|
38
|
+
test "a trait's static default is each implementer's, and an override wins"
|
|
39
|
+
assert PlayScreen.name() == "PlayScreen"
|
|
40
|
+
assert Own.name() == "mine"
|
|
41
|
+
assert Box.kind() == "Box"
|
|
42
|
+
assert PlayScreen(id: 2).label() == "<PlayScreen>"
|
|
43
|
+
|
|
44
|
+
test "through dispatch, Self.name() is the value's own type's static"
|
|
45
|
+
xs: List[Named] := [PlayScreen(id: 1), Own(id: 2)]
|
|
46
|
+
assert xs.map(|n| n.label()).fold("", |a, s| a + s) == "<PlayScreen><mine>"
|
|
47
|
+
ks: List[Kind[Int]] := [Box[Int](id: 1), Plain(id: 2)]
|
|
48
|
+
assert ks.map(|k| k.kindOf()).fold("", |a, s| a + s) == "BoxPlain"
|
tests/traits/supertraits.plum
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import std/Int
|
|
2
|
+
import std/Float
|
|
3
|
+
import std/Str
|
|
4
|
+
import std/List
|
|
5
|
+
import std/Option
|
|
6
|
+
|
|
7
|
+
# Trait inheritance (`trait Screen[S, M] is Actor[M]`) and downcasts to a trait
|
|
8
|
+
# (`Screen[S, M] as s` on an `Actor[M]`).
|
|
9
|
+
|
|
10
|
+
enum Msg = Go | Stop
|
|
11
|
+
|
|
12
|
+
trait Actor[M] =
|
|
13
|
+
fun key(self) -> Int
|
|
14
|
+
fun step(self, dt: Float) -> Self = self
|
|
15
|
+
fun name(self) -> Str = "actor"
|
|
16
|
+
|
|
17
|
+
# A screen is an actor too: its types implement `Actor[M]` through it.
|
|
18
|
+
trait Screen[S, M] is Actor[M] =
|
|
19
|
+
fun react(self, state: S, msg: M) -> Self = self
|
|
20
|
+
# A default may call the supertrait's methods on self.
|
|
21
|
+
fun title(self) -> Str = "{self.name()} {self.key()}"
|
|
22
|
+
|
|
23
|
+
struct Orb(id: Int, x: Float) is Actor[Msg] =
|
|
24
|
+
fun key(self) -> Int = self.id
|
|
25
|
+
fun step(self, dt: Float) -> Orb = Orb(..self, x: self.x + dt)
|
|
26
|
+
|
|
27
|
+
struct Play(id: Int, seen: Int) is Screen[Int, Msg] =
|
|
28
|
+
fun key(self) -> Int = self.id
|
|
29
|
+
fun name(self) -> Str = "play"
|
|
30
|
+
fun react(self, state: Int, msg: Msg) -> Play = Play(..self, seen: self.seen + state)
|
|
31
|
+
|
|
32
|
+
struct Menu(id: Int) is Screen[Int, Msg] =
|
|
33
|
+
fun key(self) -> Int = self.id
|
|
34
|
+
fun step(self, dt: Float) -> Menu = Menu(id: self.id + 100)
|
|
35
|
+
|
|
36
|
+
# A screen of another state: an `Actor[Msg]`, never a `Screen[Int, Msg]`.
|
|
37
|
+
struct Other(id: Int) is Screen[Str, Msg] =
|
|
38
|
+
fun key(self) -> Int = self.id
|
|
39
|
+
|
|
40
|
+
fun keyOf(a: Actor[Msg]) -> Int = a.key()
|
|
41
|
+
|
|
42
|
+
fun asScreen(a: Actor[Msg]) -> Option[Screen[Int, Msg]] = match a
|
|
43
|
+
Screen[Int, Msg] as s => Some(s)
|
|
44
|
+
_ => None
|
|
45
|
+
|
|
46
|
+
fun reacted(a: Actor[Msg], n: Int) -> Actor[Msg] = match a
|
|
47
|
+
Screen[Int, Msg] as s => s.react(n, Go)
|
|
48
|
+
_ => a
|
|
49
|
+
|
|
50
|
+
fun seenOf(a: Actor[Msg]) -> Int = match a
|
|
51
|
+
Play as p => p.seen
|
|
52
|
+
_ => -1
|
|
53
|
+
|
|
54
|
+
test "a screen is an actor: upcast with no cast, and Actor's calls on it"
|
|
55
|
+
p := Play(id: 1, seen: 0)
|
|
56
|
+
s: Screen[Int, Msg] := p
|
|
57
|
+
a: Actor[Msg] := s
|
|
58
|
+
assert keyOf(p) == 1
|
|
59
|
+
assert keyOf(s) == 2 - 1
|
|
60
|
+
assert a.name() == "play"
|
|
61
|
+
assert s.name() == "play"
|
|
62
|
+
assert s.key() == 1
|
|
63
|
+
m: Screen[Int, Msg] := Menu(id: 5)
|
|
64
|
+
assert m.name() == "actor"
|
|
65
|
+
assert m.step(1.0).key() == 105
|
|
66
|
+
|
|
67
|
+
test "a subtrait's default calls the supertrait's methods"
|
|
68
|
+
assert Play(id: 3, seen: 0).title() == "play 3"
|
|
69
|
+
m: Screen[Int, Msg] := Menu(id: 4)
|
|
70
|
+
assert m.title() == "actor 4"
|
|
71
|
+
|
|
72
|
+
test "a downcast to a trait matches its implementers only"
|
|
73
|
+
xs: List[Actor[Msg]] := [Orb(id: 1, x: 0.0), Play(id: 2, seen: 0), Menu(id: 3), Other(id: 4)]
|
|
74
|
+
found := xs.map(|a| match asScreen(a)
|
|
75
|
+
Some(s) => s.key()
|
|
76
|
+
None => 0)
|
|
77
|
+
assert found.get(0).unwrap() == 0
|
|
78
|
+
assert found.get(1).unwrap() == 2
|
|
79
|
+
assert found.get(2).unwrap() == 3
|
|
80
|
+
assert found.get(3).unwrap() == 0
|
|
81
|
+
|
|
82
|
+
test "a downcast binder is a trait object: Self methods return the screen"
|
|
83
|
+
a: Actor[Msg] := Play(id: 2, seen: 1)
|
|
84
|
+
b := reacted(reacted(a, 5), 7)
|
|
85
|
+
assert seenOf(b) == 13
|
|
86
|
+
assert seenOf(a) == 1
|
|
87
|
+
o: Actor[Msg] := Orb(id: 1, x: 0.0)
|
|
88
|
+
assert keyOf(reacted(o, 5)) == 1
|