plum

#treesitter#compiler#wasm

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

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


6be890a — Peter John 2026-11-10T11:28:57+05:30
Passes: no drops left across std, examples and tests
compiler/core/src/closure_spec.rs CHANGED
@@ -89,6 +89,7 @@ pub fn specialiseWith(src: &mut Source, hints: &Hints) -> Vec<String> {
89
89
  ne,
90
90
  fns: HashMap::new(),
91
91
  typeGens: HashMap::new(),
92
+ ctxCtors: HashSet::new(),
92
93
  methodsByName: HashMap::new(),
93
94
  specs: Vec::new(),
94
95
  copies: HashMap::new(),
@@ -101,6 +102,13 @@ pub fn specialiseWith(src: &mut Source, hints: &Hints) -> Vec<String> {
101
102
  for item in &src.items {
102
103
  if let Item::Enum(e) = item {
103
104
  cx.typeGens.insert(e.name.clone(), e.generics.iter().map(|g| g.name.clone()).collect());
105
+ for v in &e.variants {
106
+ let mut named = HashSet::new();
107
+ v.fields.iter().for_each(|t| typeNames(t, &mut named));
108
+ if e.generics.iter().any(|g| !named.contains(&g.name)) {
109
+ cx.ctxCtors.insert(v.name.clone());
110
+ }
111
+ }
104
112
  }
105
113
  if let Item::Fn(f) = item {
106
114
  if f.is_extern || f.is_test {
@@ -189,6 +197,8 @@ struct Tx {
189
197
  spec: usize,
190
198
  /// The copy's capture types (its fresh generics), passed on by a call with type arguments.
191
199
  capTys: Vec<Type>,
200
+ /// The declared result type of the fn-typed parameter, when it has one.
201
+ ret: Option<Type>,
192
202
  enc: Enc,
193
203
  handled: usize,
194
204
  err: bool,
@@ -200,6 +210,9 @@ struct Ctx<'h> {
200
210
  fns: HashMap<String, Fn>,
201
211
  /// Each type's declared generics.
202
212
  typeGens: HashMap<String, Vec<String>>,
213
+ /// The constructors only their context types (`None`, `Err(e)` of `Result[T, E]`: their
214
+ /// fields leave a generic of their type open).
215
+ ctxCtors: HashSet<String>,
203
216
  methodsByName: HashMap<String, Vec<String>>,
204
217
  specs: Vec<Spec>,
205
218
  /// (callee key, param index, spec) -> copy fn name; `None` when it cannot be made.
@@ -593,10 +606,15 @@ impl<'h> Ctx<'h> {
593
606
  }
594
607
  }
595
608
  let before = countVar(&f.body, &p);
609
+ let ret = match &f.params[j].ty {
610
+ ParamType::Fn(_, Some(r)) => Some((**r).clone()),
611
+ _ => None,
612
+ };
596
613
  let mut tx = Tx {
597
614
  p: p.clone(),
598
615
  spec: sid,
599
616
  capTys,
617
+ ret,
600
618
  enc: Enc {
601
619
  file: f.file.clone(),
602
620
  ty: f.type_param.clone(),
@@ -679,7 +697,7 @@ impl<'h> Ctx<'h> {
679
697
  }
680
698
  }
681
699
  }
682
- let Some((binds, mut body)) = self.instantiate(&cl, tx.spec, args, false) else {
700
+ let Some((binds, mut body)) = self.instantiate(&cl, tx, args, false) else {
683
701
  tx.err = true;
684
702
  return Some(vec![]);
685
703
  };
@@ -789,7 +807,7 @@ impl<'h> Ctx<'h> {
789
807
  }
790
808
  Kind::Lit(c) => c.clone(),
791
809
  };
792
- if let Some((binds, mut body)) = self.instantiate(&cl, tx.spec, args.clone(), true) {
810
+ if let Some((binds, mut body)) = self.instantiate(&cl, tx, args.clone(), true) {
793
811
  if binds.is_empty() && body.len() == 1 {
794
812
  return match body.pop() {
795
813
  Some(Stmt { kind: StmtKind::Expr(e, ..), .. }) => Some(e),
@@ -800,7 +818,7 @@ impl<'h> Ctx<'h> {
800
818
  // A block closure (several statements, or arguments to bind): the call becomes a block
801
819
  // value, whose last line is the closure's value. Its binders are fresh, so the block
802
820
  // declares nothing that clashes with the enclosing fn.
803
- let (mut stmts, body) = self.instantiate(&cl, tx.spec, args, false)?;
821
+ let (mut stmts, body) = self.instantiate(&cl, tx, args, false)?;
804
822
  if !matches!(body.last(), Some(Stmt { kind: StmtKind::Expr(..), .. })) {
805
823
  return None;
806
824
  }
@@ -815,10 +833,11 @@ impl<'h> Ctx<'h> {
815
833
  fn instantiate(
816
834
  &mut self,
817
835
  cl: &Closure,
818
- sid: usize,
836
+ tx: &Tx,
819
837
  args: Vec<Expr>,
820
838
  exprMode: bool,
821
839
  ) -> Option<(Vec<Stmt>, Vec<Stmt>)> {
840
+ let sid = tx.spec;
822
841
  if cl.params.len() != args.len() {
823
842
  return None;
824
843
  }
@@ -897,10 +916,57 @@ impl<'h> Ctx<'h> {
897
916
  }
898
917
  });
899
918
  }
919
+ // `|x| Ok(x + 1)` for `f: fn(Int) -> Result[Int, BadError]`: out of the closure, only
920
+ // the parameter's result type types `Ok`; the value is bound to a local of that type.
921
+ if let (Some(r), Some(Stmt { kind: StmtKind::Expr(e, ..), .. })) = (&tx.ret, body.stmts.last_mut()) {
922
+ if self.contextTail(e) {
923
+ let v = format!("__r{}_{}", k, sid);
924
+ let value = std::mem::replace(e, Expr::Int(0));
925
+ *e = Expr::Block(Box::new(Block {
926
+ stmts: vec![
927
+ Stmt::Assign(Assign {
928
+ isSynthetic: false,
929
+ targets: vec![AssignTarget::Var(v.clone())],
930
+ values: vec![value],
931
+ declare: true,
932
+ ty: Some(r.clone()),
933
+ }),
934
+ Stmt::Expr(Expr::Var(v), 0, 0),
935
+ ],
936
+ }));
937
+ }
938
+ }
900
939
  Some((binds, body.stmts))
901
940
  }
902
941
  }
903
942
 
943
+ impl Ctx<'_> {
944
+ /// Whether a result of `e` is a constructor only its context types (`None`, `Ok(1)`).
945
+ fn contextTail(&self, e: &Expr) -> bool {
946
+ match &e.kind {
947
+ ExprKind::Var(n) | ExprKind::TypeName(n) => self.ctxCtors.contains(n),
948
+ ExprKind::FnCall(c) => self.ctxCtors.contains(&c.name),
949
+ ExprKind::ClassCall(c) => c.generics.is_empty() && self.ctxCtors.contains(&c.type_name),
950
+ ExprKind::InlineIf(i) => self.contextTail(&i.then) || self.contextTail(&i.else_),
951
+ ExprKind::Block(b) => match b.stmts.last() {
952
+ Some(Stmt { kind: StmtKind::Expr(e, ..), .. }) => self.contextTail(e),
953
+ Some(s) => {
954
+ // an `if` / `match` statement as the value: any branch
955
+ let mut any = false;
956
+ for blk in crate::visit::stmtBlockRefs(s) {
957
+ if let Some(Stmt { kind: StmtKind::Expr(e, ..), .. }) = blk.stmts.last() {
958
+ any |= self.contextTail(e);
959
+ }
960
+ }
961
+ any
962
+ }
963
+ None => false,
964
+ },
965
+ _ => false,
966
+ }
967
+ }
968
+ }
969
+
904
970
  /// Clears every source position inside `b`.
905
971
  fn zeroBlock(b: &mut Block) {
906
972
  for s in &mut b.stmts {
compiler/core/src/drive.rs CHANGED
@@ -353,7 +353,10 @@ fn rebinds(stmts: &[Stmt], name: &str) -> bool {
353
353
  hit
354
354
  }
355
355
 
356
- struct Tcx {
356
+ struct Tcx<'a> {
357
+ /// A just-built tail with its type arguments written from the producer's result type
358
+ /// (`Ok(5)` of `Result[Int, NegError]`): the match pushed onto it is its only context.
359
+ pin: &'a dyn std::ops::Fn(Expr) -> Expr,
357
360
  cases: Vec<Case>,
358
361
  callee: Fn,
359
362
  k: usize,
@@ -365,7 +368,7 @@ struct Tcx {
365
368
  called: std::cell::Cell<usize>,
366
369
  }
367
370
 
368
- impl Tcx {
371
+ impl Tcx<'_> {
369
372
  fn callWith(&self, subject: Expr) -> Expr {
370
373
  let mut args: Vec<Expr> = self
371
374
  .cn
@@ -416,8 +419,10 @@ impl Tcx {
416
419
 
417
420
  fn tail(&self, e: Expr) -> Vec<Stmt> {
418
421
  match e.kind {
419
- ExprKind::ClassCall(_) | ExprKind::TypeName(_) => self.pushed(e),
422
+ ExprKind::ClassCall(_) | ExprKind::TypeName(_) => self.pushed((self.pin)(e)),
420
- ExprKind::Var(ref n) if self.ctors.contains(n) => self.pushed(e),
423
+ ExprKind::Var(ref n) if self.ctors.contains(n) => self.pushed((self.pin)(e)),
424
+ // a positional constructor (`Ok(5)`) is built too, not a call to drive into
425
+ ExprKind::FnCall(ref c) if self.ctors.contains(&c.name) => self.pushed((self.pin)(e)),
421
426
  ExprKind::InlineIf(i) => {
422
427
  let i = *i;
423
428
  vec![Stmt::If(If {
@@ -703,11 +708,37 @@ impl Driver {
703
708
  }
704
709
  }
705
710
  bodies.extend(self.fused.iter().filter_map(bodyBlock));
711
+ // per fused fn, the generics each parameter's type names
712
+ let pgens: HashMap<String, Vec<HashSet<String>>> = self
713
+ .fused
714
+ .iter()
715
+ .filter(|f| dead.contains_key(&f.name))
716
+ .map(|f| {
717
+ let sc = self.scopeOf(f);
718
+ let gs = f.params.iter().map(|p| {
719
+ let mut g = HashSet::new();
720
+ ptGens(&sc, &p.ty, &mut g);
721
+ g
722
+ });
723
+ (f.name.clone(), gs.collect())
724
+ })
725
+ .collect();
706
726
  for b in &bodies {
707
727
  walkBlockRef(b, &mut |e| {
708
728
  if let ExprKind::FnCall(c) = &e.kind {
709
729
  if let Some(idx) = dead.get_mut(&c.name) {
710
730
  idx.retain(|&i| c.args.get(i).is_some_and(|a| self.argPure(argRef(a))));
731
+ // `len$push$0(Nil, 1)`: a kept bare `Nil` is typed by the argument
732
+ // of a parameter sharing its generic; that one stays too.
733
+ let Some(gs) = pgens.get(&c.name) else { return };
734
+ for (k, a) in c.args.iter().enumerate() {
735
+ if idx.contains(&k) || !self.contextTyped(argRef(a)) {
736
+ continue;
737
+ }
738
+ if let Some(gk) = gs.get(k) {
739
+ idx.retain(|&i| gs.get(i).is_none_or(|gi| gi.is_disjoint(gk)));
740
+ }
741
+ }
711
742
  }
712
743
  }
713
744
  });
@@ -762,6 +793,21 @@ impl Driver {
762
793
  }
763
794
  }
764
795
 
796
+ /// A constructor only its context types (`Nil`, `None`, `Err(e)`): its fields leave a
797
+ /// generic of its type open.
798
+ fn contextTyped(&self, e: &Expr) -> bool {
799
+ let name = match &e.kind {
800
+ ExprKind::Var(n) | ExprKind::TypeName(n) => n,
801
+ ExprKind::FnCall(c) => &c.name,
802
+ ExprKind::ClassCall(c) if c.generics.is_empty() => &c.type_name,
803
+ _ => return false,
804
+ };
805
+ let Some((gens, fields)) = self.ctorFields.get(name) else { return false };
806
+ let mut named = HashSet::new();
807
+ fields.iter().for_each(|t| tyNames(t, &mut named));
808
+ gens.iter().any(|g| !named.contains(g))
809
+ }
810
+
765
811
  fn rewriteBody(&mut self, body: &mut FnBody) {
766
812
  match body {
767
813
  FnBody::Expr(e) => {
@@ -1410,6 +1456,10 @@ impl Driver {
1410
1456
  if sig.iter().any(|n| self.traits.contains(n)) {
1411
1457
  return Err(format!("wrapper {} names a trait in its signature", c.key).into());
1412
1458
  }
1459
+ // (a one-expression body: cheap to scan at each call)
1460
+ if crate::simplify::bodyNamesGenerics(&c.f, &self.owners) {
1461
+ return Err(format!("wrapper {} names its own generics in its body", c.key).into());
1462
+ }
1413
1463
  let (names, rb) = self.renamed(&c.f, "$u").ok_or("extern consumer")?;
1414
1464
  if mentions(&rb, &self.bound) {
1415
1465
  return Err(format!("a local here shadows a name wrapper {} uses", c.key).into());
@@ -1846,7 +1896,9 @@ impl Driver {
1846
1896
  *g = e;
1847
1897
  }
1848
1898
  }
1899
+ let pscope = sc.merge(&Scope::named(&fresh));
1900
+ let pin = |e: Expr| pinExpr(e, &pret, &self.snap, &self.pure, &pscope).unwrap_or_else(|e| e);
1849
- let tcx = Tcx { cases, callee: c.f.clone(), k, cn: cn.clone(), ctors: self.ctors.clone(), built: Default::default(), called: Default::default() };
1901
+ let tcx = Tcx { pin: &pin, cases, callee: c.f.clone(), k, cn: cn.clone(), ctors: self.ctors.clone(), built: Default::default(), called: Default::default() };
1850
1902
  let mut body = tcx
1851
1903
  .tailMap(&pbody)
1852
1904
  .ok_or(format!("producer {} has a result outside a tail position", p.key))?;
compiler/core/src/simplify.rs CHANGED
@@ -153,6 +153,9 @@ struct Cx<'a> {
153
153
  bound: HashSet<String>,
154
154
  /// trait names: a fn whose signature names one is not inlined (see `eligible`)
155
155
  traits: HashSet<String>,
156
+ /// fns whose body names one of their own generics (`T.Max`, `x: List[T] := ..`): inlined,
157
+ /// the name would mean nothing (or the caller's generic of that name)
158
+ namesGenerics: HashSet<String>,
156
159
  }
157
160
 
158
161
  fn trivial(e: &Expr) -> bool {
@@ -182,6 +185,30 @@ fn openGenerics(sc: &Scope, t: &Type, out: &mut HashSet<String>) {
182
185
  t.generics.iter().for_each(|g| openGenerics(sc, g, out));
183
186
  }
184
187
 
188
+ /// Whether `f`'s body names one of `f`'s generics: as a type (annotations, type arguments) or a
189
+ /// static receiver (`T.Max`).
190
+ pub(crate) fn bodyNamesGenerics(f: &Fn, owners: &HashMap<String, Vec<String>>) -> bool {
191
+ let sc = Scope::in_(owners, f);
192
+ let mut stmts = match &f.body {
193
+ FnBody::Expr(e) => vec![Stmt::Expr(e.clone(), 0, 0)],
194
+ FnBody::Block(b) => b.stmts.clone(),
195
+ FnBody::Extern => return false,
196
+ };
197
+ let mut hit = false;
198
+ fn any(sc: &Scope, t: &Type) -> bool {
199
+ sc.isGeneric(&t.name) || t.generics.iter().any(|g| any(sc, g))
200
+ }
201
+ crate::rename::typesInStmts(&mut stmts, &mut |t| hit |= any(&sc, t));
202
+ let block = Block { stmts };
203
+ walkBlockRef(&block, &mut |e| {
204
+ if let ExprKind::TypeName(n) = &e.kind {
205
+ // `T.Max` is one name
206
+ hit |= sc.isGeneric(n.split('.').next().unwrap_or(n));
207
+ }
208
+ });
209
+ hit
210
+ }
211
+
185
212
  fn sizeOf(f: &Fn) -> usize {
186
213
  let mut n = 0;
187
214
  let mut count = |_: &Expr| n += 1;
@@ -284,7 +311,9 @@ impl<'a> Cx<'a> {
284
311
  }
285
312
  }
286
313
  }
314
+ let owners = crate::generics::ownerGenerics(src);
315
+ let namesGenerics = fns.iter().filter(|(_, f)| bodyNamesGenerics(f, &owners)).map(|(k, _)| k.clone()).collect();
287
- Cx { pure, fns, recursive, ctors, variants, stack: vec![], depth: 0, scope: Scope::default(), owners: crate::generics::ownerGenerics(src), bound: HashSet::new(), traits }
316
+ Cx { pure, fns, recursive, ctors, variants, stack: vec![], depth: 0, scope: Scope::default(), owners, bound: HashSet::new(), traits, namesGenerics }
288
317
  }
289
318
 
290
319
  fn isPure(&self, e: &Expr) -> bool {
@@ -319,7 +348,8 @@ impl<'a> Cx<'a> {
319
348
  && !matches!(f.body, FnBody::Extern)
320
349
  && f.params.iter().all(|p| matches!(p.ty, ParamType::Type(_) | ParamType::Fn(..)))
321
350
  && sizeOf(f) <= MAX_SIZE
322
- && !self.upcasts(f);
351
+ && !self.upcasts(f)
352
+ && !self.namesGenerics.contains(name);
323
353
  if ok { Some(f) } else { None }
324
354
  }
325
355
 
@@ -504,6 +534,16 @@ impl<'a> Cx<'a> {
504
534
  }
505
535
  }
506
536
 
537
+ /// An argument that is a context-typed constructor (see `contextTyped`): `Nil`, `None`, `Err(e)`.
538
+ fn contextTypedArg(&self, e: &Expr) -> bool {
539
+ match &e.kind {
540
+ ExprKind::Var(n) | ExprKind::TypeName(n) => self.contextTyped(n),
541
+ ExprKind::FnCall(c) => self.contextTyped(&c.name),
542
+ ExprKind::ClassCall(c) => c.generics.is_empty() && self.contextTyped(&c.type_name),
543
+ _ => false,
544
+ }
545
+ }
546
+
507
547
  /// A constructor of a generic enum whose field types leave some of the enum's generics
508
548
  /// out (`Err(err: E)` of `Result[T, E]`, nullary `None`): only its context types it.
509
549
  fn contextTyped(&self, name: &str) -> bool {
@@ -603,7 +643,10 @@ impl<'a> Cx<'a> {
603
643
  for (i, a) in argv {
604
644
  let p = &f.params[i].name;
605
645
  let fr = map[p].clone();
646
+ // `fBtLeafOf(Nil)`: only the parameter's type (`List[Int]`) types a bare `Nil`, so
647
+ // it is bound to a local of that type, or the call is not inlined.
648
+ let ctx = self.contextTypedArg(&a);
606
- if trivial(&a) && !assigned.contains(p) && !declared.contains(p) && !called.contains(&fr) {
649
+ if trivial(&a) && !ctx && !assigned.contains(p) && !declared.contains(p) && !called.contains(&fr) {
607
650
  subst.insert(fr, a);
608
651
  } else if allowLets {
609
652
  // The local has the parameter's declared type, so an argument whose type the
@@ -617,6 +660,26 @@ impl<'a> Cx<'a> {
617
660
  ParamType::Type(t) if !mentionsAny(t, &gens) => Some(t.clone()),
618
661
  _ => None,
619
662
  };
663
+ if ctx && ty.is_none() {
664
+ return None;
665
+ }
666
+ // `|x| x + i` for `f: fn(Int) -> Int`: a local holding the closure has no
667
+ // parameter type to check it against, so its params get the declared ones.
668
+ let mut a = a;
669
+ if let ExprKind::Closure(cl) = &mut a.kind {
670
+ if cl.param_types.iter().any(|t| t.is_none()) {
671
+ match &f.params[i].ty {
672
+ ParamType::Fn(ps, _) if ps.len() == cl.params.len() && !ps.iter().any(|t| mentionsAny(t, &gens)) => {
673
+ for (slot, t) in cl.param_types.iter_mut().zip(ps) {
674
+ if slot.is_none() {
675
+ *slot = Some(t.clone());
676
+ }
677
+ }
678
+ }
679
+ _ => return None,
680
+ }
681
+ }
682
+ }
620
683
  binds.push(Stmt::Assign(Assign {
621
684
  isSynthetic: false,
622
685
  targets: vec![AssignTarget::Var(fr)],
@@ -626,7 +689,7 @@ impl<'a> Cx<'a> {
626
689
  }));
627
690
  } else {
628
691
  let StmtKind::Expr(be, ..) = &body.stmts.first()?.kind else { return None };
629
- if body.stmts.len() != 1 || assigned.contains(p) || declared.contains(p) || called.contains(&fr) {
692
+ if ctx || body.stmts.len() != 1 || assigned.contains(p) || declared.contains(p) || called.contains(&fr) {
630
693
  return None;
631
694
  }
632
695
  let mut acc = (0, 0);
compiler/driver/tests/driver_tests.rs CHANGED
@@ -414,3 +414,36 @@ fn everyGameKeepsEveryPass() {
414
414
  }
415
415
  assert!(bad.is_empty(), "{}", bad.join("\n"));
416
416
  }
417
+
418
+ /// Test files whose rewrites once failed their re-check (a type only the removed context gave:
419
+ /// a positional `Ok(5)` under a fused consumer, an inlined `Nil` argument, a closure bound to a
420
+ /// local, `T.Max` inlined out of its fn, a dropped parameter that typed a kept `Nil`, a closure
421
+ /// `|x| Ok(x + 1)` inlined into a copy): built as `plum test` builds them, nothing is dropped.
422
+ #[test]
423
+ fn formerlyDroppingTestFilesKeepEveryPass() {
424
+ let root = plum_test_support::repoRoot();
425
+ let files = [
426
+ "std/collections/functional/FBTree.plum",
427
+ "tests/wasm_codegen/e2e_tail/closure_captures_iteration_value.plum",
428
+ "tests/wasm_codegen/e2e_tail/question_in_tail_not_tail_call.plum",
429
+ "tests/wasm_codegen/e2e_tail/result_mutual_million.plum",
430
+ "tests/wasm_codegen/e2e_types/bare_tag_fixed_by_other_link_arg.plum",
431
+ "tests/wasm_codegen/e2e_types/bare_tag_fixed_by_later_arg.plum",
432
+ "tests/wasm_codegen/e2e_types/chained_question_returns_first_err.plum",
433
+ "tests/wasm_codegen/e2e_types/closure_into_ref_option_and_result.plum",
434
+ "tests/wasm_codegen/e2e_types/list_literal_element_pinned_by_a_later_element.plum",
435
+ "tests/wasm_codegen/e2e_types/ok_unit_and_expression_position.plum",
436
+ "tests/wasm_codegen/e2e_types/static_on_builtin.plum",
437
+ ];
438
+ let mut bad = Vec::new();
439
+ for f in files {
440
+ let src = plum_core::loader::loadAndMergeDiag(&root.join(f), &root).unwrap_or_else(|e| panic!("{f}: {e:?}"));
441
+ let src = plum_core::tests_lower::lowerTests(&src).source;
442
+ let (r, dropped) = plum_driver::checkReport(&src, &PassOptions::default(), &PASSES);
443
+ r.unwrap_or_else(|e| panic!("{f}: {e:?}"));
444
+ if !dropped.is_empty() {
445
+ bad.push(format!("{f}: {dropped:?}"));
446
+ }
447
+ }
448
+ assert!(bad.is_empty(), "{}", bad.join("\n"));
449
+ }