plum

#treesitter#compiler#wasm

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

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


f03cb30 — Peter John 2026-11-10T10:54:21+05:30
Passes: keep the types a rewrite used to drop with the whole program
compiler/core/src/closure_spec.rs CHANGED
@@ -13,8 +13,8 @@
13
13
  //! closure cannot be inlined, the call is left alone.
14
14
  use crate::ast::*;
15
15
  use crate::closure_escape::nonEscapingFnParams;
16
- use crate::rename::{renameStmts, Name};
16
+ use crate::rename::{renameStmts, typesInExpr, typesInStmts, Name};
17
- use crate::visit::{countVar, innerBlockRefs, innerBlocks, stmtBlocks, stmtExprRefs, stmtExprs, visitBlock, visitExpr, walkBlockRef, walkRef};
17
+ use crate::visit::{countVar, innerBlockRefs, innerBlocks, stmtBlockRefs, stmtBlocks, stmtExprRefs, stmtExprs, visitBlock, visitExpr, walkBlockRef, walkRef};
18
18
  use std::collections::{HashMap, HashSet};
19
19
 
20
20
  pub const MAX_COPIES: usize = 8;
@@ -88,6 +88,7 @@ pub fn specialiseWith(src: &mut Source, hints: &Hints) -> Vec<String> {
88
88
  hints,
89
89
  ne,
90
90
  fns: HashMap::new(),
91
+ typeGens: HashMap::new(),
91
92
  methodsByName: HashMap::new(),
92
93
  specs: Vec::new(),
93
94
  copies: HashMap::new(),
@@ -98,6 +99,9 @@ pub fn specialiseWith(src: &mut Source, hints: &Hints) -> Vec<String> {
98
99
  fresh: 0,
99
100
  };
100
101
  for item in &src.items {
102
+ if let Item::Enum(e) = item {
103
+ cx.typeGens.insert(e.name.clone(), e.generics.iter().map(|g| g.name.clone()).collect());
104
+ }
101
105
  if let Item::Fn(f) = item {
102
106
  if f.is_extern || f.is_test {
103
107
  continue;
@@ -172,11 +176,19 @@ struct Enc {
172
176
  struct Site {
173
177
  enc: Enc,
174
178
  locals: HashSet<String>,
179
+ /// The type names that are generics here (the fn's own, its type's, any single letter):
180
+ /// a closure naming one cannot move into another fn.
181
+ gens: HashSet<String>,
182
+ /// The locals whose type is written down and that are bound once (params, `self`,
183
+ /// annotated `x: T := v`): a capture's type argument when the call writes its own.
184
+ typed: HashMap<String, Type>,
175
185
  }
176
186
 
177
187
  struct Tx {
178
188
  p: String,
179
189
  spec: usize,
190
+ /// The copy's capture types (its fresh generics), passed on by a call with type arguments.
191
+ capTys: Vec<Type>,
180
192
  enc: Enc,
181
193
  handled: usize,
182
194
  err: bool,
@@ -186,6 +198,8 @@ struct Ctx<'h> {
186
198
  hints: &'h Hints,
187
199
  ne: HashMap<String, Vec<usize>>,
188
200
  fns: HashMap<String, Fn>,
201
+ /// Each type's declared generics.
202
+ typeGens: HashMap<String, Vec<String>>,
189
203
  methodsByName: HashMap<String, Vec<String>>,
190
204
  specs: Vec<Spec>,
191
205
  /// (callee key, param index, spec) -> copy fn name; `None` when it cannot be made.
@@ -204,12 +218,17 @@ impl<'h> Ctx<'h> {
204
218
  fn processFn(&mut self, f: &mut Fn) -> bool {
205
219
  let mut locals: HashSet<String> = f.params.iter().map(|p| p.name.clone()).collect();
206
220
  collectBinders(&mut f.body, &mut locals);
221
+ let typeGens = f.type_param.as_ref().and_then(|t| self.typeGens.get(t)).cloned().unwrap_or_default();
222
+ let mut gens: HashSet<String> = f.generics.iter().cloned().collect();
223
+ gens.extend(typeGens.iter().cloned());
207
224
  let site = Site {
208
225
  enc: Enc {
209
226
  file: f.file.clone(),
210
227
  ty: f.type_param.clone(),
211
228
  },
212
229
  locals,
230
+ gens,
231
+ typed: typedLocals(f, &typeGens),
213
232
  };
214
233
  let mut changed = false;
215
234
  let mut cb = |e: &mut Expr| {
@@ -305,10 +324,22 @@ impl<'h> Ctx<'h> {
305
324
  for j in idxs {
306
325
  let Arg::Positional(arg) = &c.args[j] else { continue };
307
326
  let Some(spec) = self.mkSpec(arg, site) else { continue };
327
+ // The copy takes one more generic per capture: a call writing its type
328
+ // arguments must write those too, so each capture's type must be known here.
329
+ let capTys: Vec<Type> = if c.type_args.is_empty() {
330
+ Vec::new()
331
+ } else {
332
+ match spec.caps.iter().map(|n| site.typed.get(n).cloned()).collect() {
333
+ Some(v) => v,
334
+ None => continue,
335
+ }
336
+ };
308
337
  let sid = self.specId(spec);
309
338
  let Some(name) = self.getCopy(&key, j, sid) else { continue };
339
+ if !c.type_args.is_empty() {
340
+ c.type_args.extend(capTys);
341
+ }
310
- for (i, cap) in self.specs[sid].caps.iter().enumerate() {
342
+ for cap in self.specs[sid].caps.iter() {
311
- let _ = i;
312
343
  c.args.push(Arg::Positional(if cap == "self" {
313
344
  Expr::Self_
314
345
  } else {
@@ -344,6 +375,13 @@ impl<'h> Ctx<'h> {
344
375
  fn mkSpec(&self, arg: &Expr, site: &Site) -> Option<Spec> {
345
376
  match &arg.kind {
346
377
  ExprKind::Closure(cl) => {
378
+ // `|a| nameOf[S, M](a)`: moved into the callee, `S` and `M` would name nothing
379
+ // (or the callee's own generics).
380
+ let mut named = HashSet::new();
381
+ closureTypeNames(cl, &mut named);
382
+ if named.iter().any(|n| site.gens.contains(n) || isLetter(n)) {
383
+ return None;
384
+ }
347
385
  let caps = self.analyze(cl, &site.locals)?;
348
386
  let mut z = (**cl).clone();
349
387
  zeroBlock(&mut z.body);
@@ -526,6 +564,7 @@ impl<'h> Ctx<'h> {
526
564
  }
527
565
  }
528
566
  // Extra params for the captures, each a fresh generic type.
567
+ let mut capTys = Vec::new();
529
568
  if !spec.caps.is_empty() {
530
569
  let mut used = HashSet::new();
531
570
  for q in &f.params {
@@ -535,10 +574,14 @@ impl<'h> Ctx<'h> {
535
574
  typeNames(r, &mut used);
536
575
  }
537
576
  bodyTypeNames(&mut f.body, &mut used);
577
+ if let Kind::Lit(cl) = &spec.kind {
578
+ closureTypeNames(cl, &mut used);
579
+ }
538
580
  let mut letters = ('A'..='Z').rev().map(|c| c.to_string()).filter(|l| !used.contains(l));
539
581
  for i in 0..spec.caps.len() {
540
582
  let letter = letters.next()?;
541
583
  f.generics.push(letter.clone());
584
+ capTys.push(Type { name: letter.clone(), generics: vec![] });
542
585
  f.params.push(Param {
543
586
  name: capName(sid, i),
544
587
  ty: ParamType::Type(Type {
@@ -553,6 +596,7 @@ impl<'h> Ctx<'h> {
553
596
  let mut tx = Tx {
554
597
  p: p.clone(),
555
598
  spec: sid,
599
+ capTys,
556
600
  enc: Enc {
557
601
  file: f.file.clone(),
558
602
  ty: f.type_param.clone(),
@@ -719,6 +763,9 @@ impl<'h> Ctx<'h> {
719
763
  return fail(tx);
720
764
  };
721
765
  c.name = name;
766
+ if !c.type_args.is_empty() {
767
+ c.type_args.extend(tx.capTys.iter().cloned());
768
+ }
722
769
  for i in 0..self.specs[tx.spec].caps.len() {
723
770
  c.args.push(Arg::Positional(Expr::Var(capName(tx.spec, i))));
724
771
  }
@@ -990,44 +1037,77 @@ fn paramTypeNames(t: &ParamType, out: &mut HashSet<String>) {
990
1037
  }
991
1038
  }
992
1039
 
993
- /// Type names written inside a body (annotated locals, closure params, explicit generics).
1040
+ /// Type names written inside a body (annotated locals, closure params, explicit generics
1041
+ /// of constructors and calls, `T[..] as x` patterns).
994
1042
  fn bodyTypeNames(body: &mut FnBody, out: &mut HashSet<String>) {
995
- let mut stmtCb = |e: &mut Expr| match &mut e.kind {
1043
+ let mut cb = |t: &mut Type| typeNames(t, out);
996
- ExprKind::Closure(c) => c.param_types.iter().flatten().for_each(|t| typeNames(t, out)),
997
- ExprKind::ClassCall(c) => c.generics.iter().for_each(|t| typeNames(t, out)),
998
- _ => {}
999
- };
1000
1044
  match body {
1001
- FnBody::Expr(e) => visitExpr(e, &mut stmtCb),
1045
+ FnBody::Expr(e) => typesInExpr(e, &mut cb),
1002
- FnBody::Block(b) => {
1003
- visitBlock(b, &mut stmtCb);
1004
- annotations(&b.stmts, out);
1046
+ FnBody::Block(b) => typesInStmts(&mut b.stmts, &mut cb),
1005
- }
1006
1047
  FnBody::Extern => {}
1007
1048
  }
1008
1049
  }
1009
1050
 
1051
+ /// Type names written in a closure (its param types and body).
1010
- fn annotations(stmts: &[Stmt], out: &mut HashSet<String>) {
1052
+ fn closureTypeNames(cl: &Closure, out: &mut HashSet<String>) {
1011
- for s in stmts {
1012
- match &s.kind {
1013
- StmtKind::Assign(a) => {
1053
+ let mut e = Expr::Closure(Box::new(cl.clone()));
1014
- if let Some(t) = &a.ty {
1015
- typeNames(t, out);
1054
+ typesInExpr(&mut e, &mut |t| typeNames(t, out));
1016
- }
1055
+ }
1056
+
1057
+ /// A single-letter type name: always a generic (see `Fn.generics`).
1058
+ fn isLetter(n: &str) -> bool {
1059
+ n.len() == 1 && n.chars().all(|c| c.is_ascii_uppercase())
1060
+ }
1061
+
1062
+ /// The locals of `f` whose type is written and that are bound once: params (of a plain type),
1063
+ /// `self` (its type with `typeGens`), and `x: T := v` declarations.
1064
+ fn typedLocals(f: &Fn, typeGens: &[String]) -> HashMap<String, Type> {
1065
+ let mut decls: HashMap<String, usize> = HashMap::new();
1066
+ let mut annotated: HashMap<String, Type> = HashMap::new();
1067
+ let mut body = f.body.clone();
1068
+ let mut stmts = match &mut body {
1069
+ FnBody::Block(b) => std::mem::take(&mut b.stmts),
1070
+ FnBody::Expr(e) => vec![Stmt::Expr(e.clone(), 0, 0)],
1071
+ FnBody::Extern => vec![],
1072
+ };
1073
+ renameStmts(&mut stmts, &mut |n, k| {
1074
+ if matches!(k, Name::Decl | Name::Pat | Name::Plain) {
1075
+ *decls.entry(n.clone()).or_default() += 1;
1076
+ }
1077
+ });
1078
+ annotatedDecls(&stmts, &mut annotated);
1079
+ let mut out: HashMap<String, Type> = HashMap::new();
1080
+ for p in &f.params {
1081
+ if let ParamType::Type(t) = &p.ty {
1082
+ if !decls.contains_key(&p.name) {
1083
+ out.insert(p.name.clone(), t.clone());
1017
1084
  }
1018
- StmtKind::While(w) => annotations(&w.body.stmts, out),
1019
- StmtKind::If(i) => {
1020
- annotations(&i.body.stmts, out);
1021
- i.else_ifs.iter().for_each(|e| annotations(&e.body.stmts, out));
1022
- if let Some(b) = &i.else_ {
1023
- annotations(&b.stmts, out);
1024
- }
1085
+ }
1086
+ }
1087
+ for (n, t) in annotated {
1088
+ if decls.get(&n) == Some(&1) && !f.params.iter().any(|p| p.name == n) {
1089
+ out.insert(n, t);
1090
+ }
1091
+ }
1092
+ if let (true, Some(t)) = (f.has_self, &f.type_param) {
1093
+ let generics = typeGens.iter().map(|g| Type { name: g.clone(), generics: vec![] }).collect();
1094
+ out.insert("self".to_string(), Type { name: t.clone(), generics });
1095
+ }
1096
+ out
1097
+ }
1098
+
1099
+ fn annotatedDecls(stmts: &[Stmt], out: &mut HashMap<String, Type>) {
1100
+ for s in stmts {
1101
+ if let StmtKind::Assign(Assign { declare: true, ty: Some(t), targets, .. }) = &s.kind {
1102
+ if let [AssignTarget::Var(n)] = &targets[..] {
1103
+ out.insert(n.clone(), t.clone());
1025
1104
  }
1105
+ }
1106
+ for b in stmtBlockRefs(s) {
1026
- StmtKind::Match(m) => m.cases.iter().for_each(|c| annotations(&c.body.stmts, out)),
1107
+ annotatedDecls(&b.stmts, out);
1027
- _ => {}
1028
1108
  }
1029
1109
  for e in stmtExprRefs(s) {
1030
- innerBlockRefs(e, &mut |b| annotations(&b.stmts, out));
1110
+ innerBlockRefs(e, &mut |b| annotatedDecls(&b.stmts, out));
1031
1111
  }
1032
1112
  }
1033
1113
  }
compiler/core/src/drive.rs CHANGED
@@ -105,6 +105,23 @@ struct Driver {
105
105
  /// name -> every method with a receiver of that name: what a call on an unknown
106
106
  /// receiver may run. `methods` is the part of it that may be inlined or fused.
107
107
  allMethods: HashMap<String, Vec<String>>,
108
+ /// trait names: a wrapper whose signature names one may be an upcast (see `unfold`)
109
+ traits: HashSet<String>,
110
+ }
111
+
112
+ fn tyNames(t: &Type, out: &mut HashSet<String>) {
113
+ out.insert(t.name.clone());
114
+ t.generics.iter().for_each(|g| tyNames(g, out));
115
+ }
116
+
117
+ fn ptNames(t: &ParamType, out: &mut HashSet<String>) {
118
+ match t {
119
+ ParamType::Type(t) => tyNames(t, out),
120
+ ParamType::Fn(ps, r) => {
121
+ ps.iter().for_each(|p| tyNames(p, out));
122
+ r.iter().for_each(|r| tyNames(r, out));
123
+ }
124
+ }
108
125
  }
109
126
 
110
127
  fn keyOf(f: &Fn) -> String {
@@ -517,6 +534,7 @@ impl Driver {
517
534
  recFields: HashMap::new(),
518
535
  selfMethods: HashMap::new(),
519
536
  allMethods: HashMap::new(),
537
+ traits: HashSet::new(),
520
538
  };
521
539
  let flat = crate::layout::flatStructs(&src.items);
522
540
  for item in &src.items {
@@ -567,6 +585,9 @@ impl Driver {
567
585
  d.sums.insert(e.name.clone());
568
586
  }
569
587
  }
588
+ Item::Trait(t) => {
589
+ d.traits.insert(t.name.clone());
590
+ }
570
591
  _ => {}
571
592
  }
572
593
  }
@@ -1376,6 +1397,19 @@ impl Driver {
1376
1397
  if c.args.len() != pnames(&c.f).len() {
1377
1398
  return Err("argument count".to_string().into());
1378
1399
  }
1400
+ // `fun group(kids: List[Tree[Actor]]) -> Tree[Actor] = Tree.of(Group(..), kids)`: the
1401
+ // signature upcasts `Group` to the trait `Actor`. Unfolded, the body's types are
1402
+ // inferred from the arguments alone (`Tree[Group]`), and the program no longer checks.
1403
+ let mut sig = HashSet::new();
1404
+ for p in &c.f.params {
1405
+ ptNames(&p.ty, &mut sig);
1406
+ }
1407
+ if let Some(r) = &c.f.returns {
1408
+ tyNames(r, &mut sig);
1409
+ }
1410
+ if sig.iter().any(|n| self.traits.contains(n)) {
1411
+ return Err(format!("wrapper {} names a trait in its signature", c.key).into());
1412
+ }
1379
1413
  let (names, rb) = self.renamed(&c.f, "$u").ok_or("extern consumer")?;
1380
1414
  if mentions(&rb, &self.bound) {
1381
1415
  return Err(format!("a local here shadows a name wrapper {} uses", c.key).into());
@@ -2106,8 +2140,8 @@ impl Driver {
2106
2140
 
2107
2141
  /// The fn key of `T.method(..)`: a static method of type `T`, or, when `T` is a nullary
2108
2142
  /// variant value (`Identity.matrix()` once a just-built `Identity` is substituted), its
2109
- /// enum's method with a receiver (`Transform.matrix`). Compiler-made copies (`fold$c0`)
2143
+ /// enum's method with a receiver (`Transform.matrix`), compiler-made copies (`fold$c0`)
2110
- /// are left out: moving a value past one on `Nil` miscompiles (open, see docs/backlog.md).
2144
+ /// included (`tests/core/nil_fold_copy.plum` moves a value past `Nil.fold$c0(..)`).
2111
2145
  fn typeNameMethodKey(&self, t: &str, method: &str) -> String {
2112
2146
  let own = format!("{t}.{method}");
2113
2147
  if self.fns.contains_key(&own) {
compiler/core/src/rename.rs CHANGED
@@ -98,41 +98,67 @@ pub fn substPT(p: &ParamType, m: &HashMap<String, Type>) -> Option<ParamType> {
98
98
  }
99
99
 
100
100
  /// Applies a generic substitution to the types written inside a body: annotated locals,
101
- /// closure parameter types and explicit constructor type arguments.
101
+ /// closure parameter types, explicit constructor and call type arguments, and the type
102
+ /// arguments of `T[..] as x` patterns.
102
103
  pub fn substStmts(stmts: &mut [Stmt], m: &HashMap<String, Type>) {
104
+ typesInStmts(stmts, &mut |t| *t = substType(t, m));
105
+ }
106
+
107
+ /// Calls `f` on every type written inside `stmts` (see `substStmts`), closure bodies and
108
+ /// block values included.
109
+ pub fn typesInStmts(stmts: &mut [Stmt], f: &mut dyn FnMut(&mut Type)) {
103
110
  for s in stmts {
111
+ match &mut s.kind {
104
- if let StmtKind::Assign(a) = &mut s.kind {
112
+ StmtKind::Assign(a) => {
105
- if let Some(t) = &a.ty {
113
+ if let Some(t) = &mut a.ty {
106
- a.ty = Some(substType(t, m));
114
+ f(t);
115
+ }
107
116
  }
117
+ StmtKind::Match(m) => {
118
+ for c in &mut m.cases {
119
+ for p in &mut c.patterns {
120
+ typesInPattern(p, f);
121
+ }
122
+ }
123
+ }
124
+ _ => {}
108
125
  }
109
126
  for e in stmtExprs(s) {
110
- substExpr(e, m);
127
+ typesInExpr(e, f);
111
128
  }
112
129
  for b in stmtBlocks(s) {
113
- substStmts(&mut b.stmts, m);
130
+ typesInStmts(&mut b.stmts, f);
114
131
  }
115
132
  }
116
133
  }
117
134
 
135
+ fn typesInPattern(p: &mut CasePattern, f: &mut dyn FnMut(&mut Type)) {
136
+ match p {
137
+ CasePattern::As { args, .. } => args.iter_mut().for_each(|t| f(t)),
138
+ CasePattern::Class { fields, .. } => fields.iter_mut().for_each(|x| typesInPattern(x, f)),
139
+ _ => {}
140
+ }
141
+ }
142
+
143
+ /// `typesInStmts` for one expression.
118
- fn substExpr(e: &mut Expr, m: &HashMap<String, Type>) {
144
+ pub fn typesInExpr(e: &mut Expr, f: &mut dyn FnMut(&mut Type)) {
119
145
  match &mut e.kind {
120
146
  ExprKind::Closure(c) => {
121
- for t in c.param_types.iter_mut().flatten() {
147
+ c.param_types.iter_mut().flatten().for_each(|t| f(t));
122
- *t = substType(t, m);
123
- }
124
- substStmts(&mut c.body.stmts, m);
148
+ typesInStmts(&mut c.body.stmts, f);
125
149
  }
126
- ExprKind::Block(b) => substStmts(&mut b.stmts, m),
150
+ ExprKind::Block(b) => typesInStmts(&mut b.stmts, f),
151
+ ExprKind::ClassCall(c) => c.generics.iter_mut().for_each(|t| f(t)),
152
+ ExprKind::FnCall(c) => c.type_args.iter_mut().for_each(|t| f(t)),
127
- ExprKind::ClassCall(c) => {
153
+ ExprKind::Attribute(a) => {
128
- for t in &mut c.generics {
154
+ if let AttrKind::Method(c) = &mut a.attr {
129
- *t = substType(t, m);
155
+ c.type_args.iter_mut().for_each(|t| f(t));
130
156
  }
131
157
  }
158
+ ExprKind::Bind(b) => b.case.patterns.iter_mut().for_each(|p| typesInPattern(p, f)),
132
159
  _ => {}
133
160
  }
134
161
  for ch in childExprs(e) {
135
- substExpr(ch, m);
162
+ typesInExpr(ch, f);
136
163
  }
137
164
  }
138
-
compiler/core/src/simplify.rs CHANGED
@@ -151,6 +151,8 @@ struct Cx<'a> {
151
151
  owners: HashMap<String, Vec<String>>,
152
152
  /// names the fn being simplified binds: see `boundNames`
153
153
  bound: HashSet<String>,
154
+ /// trait names: a fn whose signature names one is not inlined (see `eligible`)
155
+ traits: HashSet<String>,
154
156
  }
155
157
 
156
158
  fn trivial(e: &Expr) -> bool {
@@ -242,8 +244,12 @@ impl<'a> Cx<'a> {
242
244
  let mut fns = HashMap::new();
243
245
  let mut ctors: HashMap<String, Vec<String>> = HashMap::new();
244
246
  let mut variants = HashMap::new();
247
+ let mut traits = HashSet::new();
245
248
  for item in &src.items {
246
249
  match item {
250
+ Item::Trait(t) => {
251
+ traits.insert(t.name.clone());
252
+ }
247
253
  Item::Fn(f) if f.type_param.is_none() => {
248
254
  fns.insert(f.name.clone(), f.clone());
249
255
  }
@@ -278,7 +284,7 @@ impl<'a> Cx<'a> {
278
284
  }
279
285
  }
280
286
  }
281
- Cx { pure, fns, recursive, ctors, variants, stack: vec![], depth: 0, scope: Scope::default(), owners: crate::generics::ownerGenerics(src), bound: HashSet::new() }
287
+ Cx { pure, fns, recursive, ctors, variants, stack: vec![], depth: 0, scope: Scope::default(), owners: crate::generics::ownerGenerics(src), bound: HashSet::new(), traits }
282
288
  }
283
289
 
284
290
  fn isPure(&self, e: &Expr) -> bool {
@@ -312,10 +318,26 @@ impl<'a> Cx<'a> {
312
318
  && f.type_param.is_none()
313
319
  && !matches!(f.body, FnBody::Extern)
314
320
  && f.params.iter().all(|p| matches!(p.ty, ParamType::Type(_) | ParamType::Fn(..)))
315
- && sizeOf(f) <= MAX_SIZE;
321
+ && sizeOf(f) <= MAX_SIZE
322
+ && !self.upcasts(f);
316
323
  if ok { Some(f) } else { None }
317
324
  }
318
325
 
326
+ /// `fun grp(kids: List[Holder[Shape]]) -> Holder[Shape] = Holder.of(Sq(..), kids)`: the
327
+ /// signature names a trait, so it may upcast. Inlined, the body's types are inferred from
328
+ /// the arguments alone (`Holder[Sq]`) and the program no longer checks.
329
+ fn upcasts(&self, f: &Fn) -> bool {
330
+ fn names(t: &Type, traits: &HashSet<String>) -> bool {
331
+ traits.contains(&t.name) || t.generics.iter().any(|g| names(g, traits))
332
+ }
333
+ let t = &self.traits;
334
+ f.returns.as_ref().is_some_and(|r| names(r, t))
335
+ || f.params.iter().any(|p| match &p.ty {
336
+ ParamType::Type(x) => names(x, t),
337
+ ParamType::Fn(ps, r) => ps.iter().any(|x| names(x, t)) || r.as_ref().is_some_and(|r| names(r, t)),
338
+ })
339
+ }
340
+
319
341
  // ---------- expressions ----------
320
342
 
321
343
  /// `lets`: where the top node may bind non-substitutable arguments (statement level).
compiler/core/src/trmc.rs CHANGED
@@ -25,7 +25,6 @@
25
25
  //! `?`/`!` or closures, no other `return`s outside tail
26
26
  //! position. No binder named like the fn: its call would not be a self call.
27
27
  use crate::ast::*;
28
- use crate::generics::Scope;
29
28
  use crate::rename::substType;
30
29
  use std::collections::HashMap;
31
30
 
@@ -75,23 +74,9 @@ impl Cx<'_> {
75
74
  }
76
75
  let map: HashMap<String, Type> =
77
76
  owner.generics.iter().map(|g| g.name.clone()).zip(self.ret.generics.iter().cloned()).collect();
78
- let owner: Vec<String> = self
79
- .f
80
- .type_param
81
- .as_ref()
82
- .and_then(|r| self.enums.iter().find(|e| &e.name == r))
83
- .map(|e| e.generics.iter().map(|g| g.name.clone()).collect())
84
- .unwrap_or_default();
85
- let sc = Scope::of(&owner, self.f);
86
- fn open(sc: &Scope, t: &Type) -> bool {
87
- sc.isGeneric(&t.name) || t.generics.iter().any(|g| open(sc, g))
88
- }
89
- // Only a concrete type helps (and a generic fn's own `B` would not re-check).
77
+ // An open type (a generic fn's own `B`) is kept too: a closure inlined into a copy
78
+ // (`List.map$c0`) may build a `Tree[Orb]` its declared `B` (`Tree[Actor]`) upcasts.
90
- let t = substType(declared, &map);
79
+ Some(substType(declared, &map))
91
- if open(&sc, &t) {
92
- return None;
93
- }
94
- Some(t)
95
80
  }
96
81
  }
97
82
 
tests/core/nil_fold_copy.plum ADDED
@@ -0,0 +1,27 @@
1
+ import std/Int
2
+ import std/List
3
+
4
+ # A just-built value moved past a closure-specialised copy called on `Nil` (`Nil.fold$c0(..)`,
5
+ # which fusion's effect check resolves to `List.fold$c0`). This once miscompiled
6
+ # (codegen: unknown method 'List.fold$c0'); it runs under every pass setting here.
7
+
8
+ struct Acc(n: Int)
9
+
10
+ fun sumWith(xs: List[Int], k: Int) -> Int = xs.fold(0, |a, x| a + x + k)
11
+
12
+ fun total(k: Int) -> Int =
13
+ e: List[Int] := Nil
14
+ acc := Acc(n: k)
15
+ s := e.fold(acc.n, |a, x| a + x + k)
16
+ t := Nil.fold(1, |a, x| a + x * k)
17
+ s + t + sumWith(Nil, k) + acc.n
18
+
19
+ fun moved(k: Int) -> Int =
20
+ acc := Acc(n: k * 2)
21
+ none: List[Int] := Nil
22
+ folded := none.fold(0, |a, x| a + x + k)
23
+ acc.n + folded
24
+
25
+ test "a value moved past a specialised fold on Nil"
26
+ assert total(4) == 9
27
+ assert moved(5) == 10
tests/core/passes_upcasts.plum ADDED
@@ -0,0 +1,56 @@
1
+ import std/Str
2
+ import std/Int
3
+ import std/List
4
+ import std/Option
5
+
6
+ # Shapes that made a rewrite pass fail its re-check (and so be dropped for the whole
7
+ # program): `compiler/driver/tests/driver_tests.rs` asserts nothing is dropped for these;
8
+ # here they run under every pass setting.
9
+
10
+ trait Shape =
11
+ fun area(self) -> Int
12
+
13
+ struct Sq(s: Int) is Shape =
14
+ fun area(self) -> Int = self.s * self.s
15
+
16
+ struct Holder[T](v: T, rest: List[Holder[T]]) =
17
+ fun of(v: T, rest: List[Holder[T]]) -> Holder[T] = Holder(v: v, rest: rest)
18
+
19
+ # The signature upcasts `Sq` to `Shape`: inlined, `Holder.of(Sq(..), kids)` alone is a `Holder[Sq]`.
20
+ fun grp(n: Int, kids: List[Holder[Shape]]) -> Holder[Shape] =
21
+ Holder.of(Sq(s: n), kids)
22
+
23
+ # The closure upcasts each `Sq` to `Shape`: inlined into `List.map`'s copy, its cells must
24
+ # keep the declared element type (also once TRMC turns the copy into a loop).
25
+ fun holders(xs: List[Sq]) -> List[Holder[Shape]] =
26
+ hs: List[Holder[Shape]] := xs.map(|s| Holder.of(s, Nil))
27
+ hs
28
+
29
+ struct Box[T](v: T)
30
+
31
+ fun nameOf[S, M](b: Box[M]) -> Int = 1
32
+
33
+ # The closure names the enclosing fn's generics: moved into `Option.map`'s copy they would name nothing.
34
+ fun outer[S, M](b: Box[M]) -> Int =
35
+ o: Option[Box[M]] := Some(b)
36
+ o.map(|a| nameOf[S, M](a)).unwrapOr(0)
37
+
38
+ fun apply[S, M](b: Box[M], k: Int, f: fn(Box[M], Int) -> Int) -> Int = f(b, k)
39
+
40
+ # A call with type arguments whose closure captures: the copy takes one more generic per capture.
41
+ fun caller[S, M](b: Box[M], extra: Int) -> Int =
42
+ apply[S, M](b, 2, |x, y| y + extra)
43
+
44
+ test "a wrapper whose signature upcasts to a trait"
45
+ h := grp(3, Cons(head: grp(1, Nil), tail: Nil))
46
+ assert h.v.area() + h.rest.length() == 10
47
+
48
+ test "a closure that upcasts, inlined into a copy of map"
49
+ hs := holders([Sq(s: 2), Sq(s: 3)])
50
+ assert hs.fold(0, |a, h| a + h.v.area()) == 13
51
+
52
+ test "a closure naming the enclosing fn's generics"
53
+ assert outer[Str, Int](Box(v: 3)) == 1
54
+
55
+ test "a call with type arguments passing a capturing closure"
56
+ assert caller[Str, Int](Box(v: 3), 4) == 6