plum

#treesitter#compiler#wasm

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

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


a94fa57 — Peter John 2026-11-16T21:13:35+05:30
U4c: closures inlined by callee size, not a program-wide cap
compiler/cli/tests/cli/game_in_place_test.rs CHANGED
@@ -117,10 +117,10 @@ fn menuKeepsItsInPlaceSpreads() {
117
117
  }
118
118
 
119
119
  /// Closures handed to one callee elsewhere in the program don't decide whether a spread is in
120
- /// place (U1). Closure specialisation copies a callee for at most `MAX_COPIES` (8) closures,
120
+ /// place (U1). Closure specialisation copied a callee for at most 8 closures, program-wide, in
121
- /// program-wide, in the order it meets them; past that a closure stays a closure. Here
121
+ /// the order it met them; past that a closure stayed a closure. Here `Other.many` took all of
122
- /// `Other.many` takes all of `List.any`'s copies first, so `Board.hit`'s closure, which reads
122
+ /// `List.any`'s copies first, so `Board.hit`'s closure, which reads `self`, stayed one (since U4c
123
- /// `self`, stays one. It still keeps nothing (`any` never lets it escape), so `hit` only reads
123
+ /// a small callee like `any` gets a copy for every closure, so it is one no longer). It still keeps nothing (`any` never lets it escape), so `hit` only reads
124
124
  /// `self` and both of `step`'s spreads are in place. Before, `hit` counted as keeping `self` and
125
125
  /// the second spread copied: a `filter` or `any` added to std/game's `Looping` cost Orbit
126
126
  /// Runner's `PlayingScreen.update` four of its five spreads the same way.
compiler/core/src/closure_escape.rs CHANGED
@@ -4,10 +4,12 @@
4
4
  //! Anything else -- storing, returning, aliasing, assigning, capturing in a closure,
5
5
  //! passing to an unknown or escaping callee -- makes it escape.
6
6
  //!
7
- //! Pure AST analysis, conservative: calls are resolved by name only. A free fn call
7
+ //! Pure AST analysis, conservative: calls are resolved by name. A free fn call resolves to the
8
- //! resolves to the free fn of that name; a method call `x.m(..)` (receiver type unknown)
8
+ //! free fn of that name; a method call `x.m(..)` resolves to the `m` of the receiver type the
9
- //! resolves to every method named `m` that takes that many args (`Type.m(..)` to that
9
+ //! checker stamped on it (`FnCall.recv`, `closure_spec::stampReceivers`; `self.m(..)` to the
10
+ //! enclosing type's) when that type has one, else to every method named `m` that takes that
10
- //! type's), and the argument is safe only if it is safe in all of them. No candidate
11
+ //! many args (`Type.m(..)` to that type's), and the argument is safe only if it is safe in all
12
+ //! of them. No candidate
11
13
  //! (extern, closure value, constructor) means escape. Solved as a greatest fixpoint, so
12
14
  //! recursion with the same param stays non-escaping.
13
15
  use crate::ast::*;
@@ -51,7 +53,7 @@ pub fn nonEscapingFnParams(src: &Source) -> HashMap<String, Vec<usize>> {
51
53
  let mut drop = Vec::new();
52
54
  for &(i, j) in &ok {
53
55
  let f = fns[i].1;
54
- let cx = Cx { fns: &fns, free: &free, methods: &methods, ok: &ok, p: &f.params[j].name };
56
+ let cx = Cx { fns: &fns, free: &free, methods: &methods, ok: &ok, p: &f.params[j].name, selfTy: f.type_param.as_deref() };
55
57
  if cx.fnEscapes(f) {
56
58
  drop.push((i, j));
57
59
  }
@@ -87,6 +89,8 @@ struct Cx<'a> {
87
89
  ok: &'a HashSet<(usize, usize)>,
88
90
  /// The param under test.
89
91
  p: &'a str,
92
+ /// The type of the fn under test, when it is a method: the type of `self`.
93
+ selfTy: Option<&'a str>,
90
94
  }
91
95
 
92
96
  impl<'a> Cx<'a> {
@@ -180,6 +184,19 @@ impl<'a> Cx<'a> {
180
184
  return true;
181
185
  }
182
186
  let want = if let ExprKind::TypeName(t) = &object.kind { Some(t.as_str()) } else { None };
187
+ // The receiver's type, when known: the call goes to that type's method alone.
188
+ let recv = match &object.kind {
189
+ ExprKind::Self_ => self.selfTy,
190
+ _ => c.recv.as_deref(),
191
+ };
192
+ if let (None, Some(t)) = (want, recv) {
193
+ let typed: Vec<usize> = self.methods.get(c.name.as_str()).map_or(vec![], |v| {
194
+ v.iter().copied().filter(|&i| self.fns[i].1.has_self && self.fns[i].1.type_param.as_deref() == Some(t) && self.fns[i].1.params.len() >= c.args.len()).collect()
195
+ });
196
+ if !typed.is_empty() {
197
+ return self.args(&c.args, &typed, cl);
198
+ }
199
+ }
183
200
  let callees: Vec<usize> = self
184
201
  .methods
185
202
  .get(c.name.as_str())
compiler/core/src/closure_spec.rs CHANGED
@@ -9,15 +9,29 @@
9
9
  //! original arguments. The fn-typed parameter itself stays in the copy's signature (so
10
10
  //! generics keep being inferred from the argument) but is unused apart from being passed
11
11
  //! on to the copies of callees it was handed to. Recursive calls passing the parameter
12
- //! along go to the copy. At most `MAX_COPIES` copies per callee; past that, or when the
12
+ //! along go to the copy. A small callee (`SMALL_CALLEE` expression nodes or fewer: every walk
13
+ //! of std) gets a copy for every closure handed to it, so which calls are inlined does not depend
14
+ //! on the rest of the program; a bigger one gets at most `MAX_BIG_COPIES`, in the order its calls
15
+ //! are met. Copies made inside copies stop at `MAX_DEPTH` levels. Past those, or when the closure
13
- //! closure cannot be inlined, the call is left alone.
16
+ //! cannot be inlined, the call is left alone.
14
17
  use crate::ast::*;
15
18
  use crate::closure_escape::nonEscapingFnParams;
16
19
  use crate::rename::{renameStmts, typesInExpr, typesInStmts, Name};
17
20
  use crate::visit::{countVar, innerBlockRefs, innerBlocks, stmtBlockRefs, stmtBlocks, stmtExprRefs, stmtExprs, visitBlock, visitExpr, walkBlockRef, walkRef};
18
21
  use std::collections::{HashMap, HashSet};
19
22
 
23
+ /// A callee of at most this many expression nodes (`fnSize`) is small: it gets a copy for every
24
+ /// closure handed to it, however many. Every closure-taking fn of std's walks is small
25
+ /// (2026-11-16: `List.map` 3, `List.fold` 8, `List.filter` 13, `Range.fold` 33, `Range.find` 35,
26
+ /// `Slice.mergeRun` 59); the biggest in the repository's programs is 68 (a segment tree's query).
27
+ pub const SMALL_CALLEE: usize = 64;
28
+ /// A bigger callee gets at most this many copies, in the order its calls are met.
20
- pub const MAX_COPIES: usize = 8;
29
+ pub const MAX_BIG_COPIES: usize = 8;
30
+ /// A copy made while specialising a copy is one level deeper; past this depth no more copies are
31
+ /// made (a callee handing itself a new closure built around its own closure would nest forever).
32
+ pub const MAX_DEPTH: usize = 4;
33
+ /// Safety net for a small callee: copies past this many (one per distinct closure) are refused.
34
+ pub const MAX_SMALL_COPIES: usize = 256;
21
35
 
22
36
  /// Receiver type of a method call site: (declaring fn's file, call line, call column,
23
37
  /// method name) -> type name. Supplied by the checker, which knows the types.
@@ -80,6 +94,9 @@ fn baseName(n: &str) -> &str {
80
94
  }
81
95
 
82
96
  pub fn specialiseWith(src: &mut Source, hints: &Hints) -> Vec<String> {
97
+ // The receiver types let the escape analysis resolve `t.all(keep)` to `List.all` alone,
98
+ // not to every `all` of the program (one that captures its closure made them all escape).
99
+ stampReceivers(src, hints);
83
100
  let ne = nonEscapingFnParams(src);
84
101
  if ne.is_empty() {
85
102
  return Vec::new();
@@ -97,6 +114,9 @@ pub fn specialiseWith(src: &mut Source, hints: &Hints) -> Vec<String> {
97
114
  perName: HashMap::new(),
98
115
  out: Vec::new(),
99
116
  outKeys: Vec::new(),
117
+ outDepth: Vec::new(),
118
+ depth: 1,
119
+ sizes: HashMap::new(),
100
120
  fresh: 0,
101
121
  };
102
122
  for item in &src.items {
@@ -132,6 +152,7 @@ pub fn specialiseWith(src: &mut Source, hints: &Hints) -> Vec<String> {
132
152
  }
133
153
  let mut done = 0;
134
154
  while done < cx.out.len() {
155
+ cx.depth = cx.outDepth[done] + 1;
135
156
  if let Some(mut f) = cx.out[done].clone() {
136
157
  if cx.processFn(&mut f) {
137
158
  cx.out[done] = Some(f);
@@ -222,6 +243,12 @@ struct Ctx<'h> {
222
243
  perName: HashMap<String, usize>,
223
244
  out: Vec<Option<Fn>>,
224
245
  outKeys: Vec<String>,
246
+ /// How deep each copy of `out` is: 1 for a copy made at a call in the program's own fns.
247
+ outDepth: Vec<usize>,
248
+ /// The depth of the copies made now.
249
+ depth: usize,
250
+ /// `fnSize` of each callee, by key.
251
+ sizes: HashMap<String, usize>,
225
252
  fresh: usize,
226
253
  }
227
254
 
@@ -496,10 +523,15 @@ impl<'h> Ctx<'h> {
496
523
  return v.clone();
497
524
  }
498
525
  let n = *self.perCallee.get(key).unwrap_or(&0);
499
- if n >= MAX_COPIES {
526
+ if self.depth > MAX_DEPTH {
500
527
  return None;
501
528
  }
502
529
  let orig = self.fns.get(key)?.clone();
530
+ let size = *self.sizes.entry(key.to_string()).or_insert_with(|| fnSize(&orig));
531
+ let cap = if size <= SMALL_CALLEE { MAX_SMALL_COPIES } else { MAX_BIG_COPIES };
532
+ if n >= cap {
533
+ return None;
534
+ }
503
535
  if orig.is_extern || orig.is_export {
504
536
  return None;
505
537
  }
@@ -520,6 +552,7 @@ impl<'h> Ctx<'h> {
520
552
  let idx = self.out.len();
521
553
  self.out.push(None);
522
554
  self.outKeys.push(newKey.clone());
555
+ self.outDepth.push(self.depth);
523
556
  // Everything made from here on belongs to this copy until it succeeds.
524
557
  let copiesBefore: HashSet<(String, usize, usize)> = self.copies.keys().cloned().collect();
525
558
  let perBefore = self.perCallee.clone();
@@ -549,6 +582,7 @@ impl<'h> Ctx<'h> {
549
582
  }
550
583
  self.out.truncate(idx);
551
584
  self.outKeys.truncate(idx);
585
+ self.outDepth.truncate(idx);
552
586
  let now: Vec<_> = self.copies.keys().cloned().collect();
553
587
  for k in now {
554
588
  if !copiesBefore.contains(&k) {
@@ -1038,6 +1072,18 @@ fn zeroBlock(b: &mut Block) {
1038
1072
  }
1039
1073
  }
1040
1074
 
1075
+ /// The number of expression nodes in `f`'s body: how big a copy of it is.
1076
+ pub fn fnSize(f: &Fn) -> usize {
1077
+ let mut n = 0;
1078
+ let mut cb = |_: &Expr| n += 1;
1079
+ match &f.body {
1080
+ FnBody::Expr(e) => walkRef(e, &mut cb),
1081
+ FnBody::Block(b) => walkBlockRef(b, &mut cb),
1082
+ FnBody::Extern => {}
1083
+ }
1084
+ n
1085
+ }
1086
+
1041
1087
  fn hasPArg(c: &FnCall, p: &str) -> bool {
1042
1088
  c.args.iter().any(|a| match a {
1043
1089
  Arg::Positional(Expr { kind: ExprKind::Var(n), .. }) | Arg::Keyword { value: Expr { kind: ExprKind::Var(n), .. }, .. } => n == p,
compiler/core/tests/core/closure_spec_test.rs CHANGED
@@ -257,7 +257,8 @@ fn dedup_same_closure_twice() {
257
257
  }
258
258
 
259
259
  #[test]
260
- fn cap_eight_copies() {
260
+ fn every_closure_to_a_std_walk_gets_a_copy() {
261
+ // std's walks are small (`closure_spec::SMALL_CALLEE`): 10 closures to `map`, 10 copies.
261
262
  let mut body = String::from("import std/App\nprimitive Main[App] =\n fun main() -> Int =\n xs := [1, 2, 3]\n");
262
263
  for i in 0..10 {
263
264
  body.push_str(&format!(" r{0} := xs.map(|x| x + {0}).fold(0, |a, x| a + x)\n", i));
@@ -265,7 +266,7 @@ fn cap_eight_copies() {
265
266
  body.push_str(" r0 + r1 + r2 + r3 + r4 + r5 + r6 + r7 + r8 + r9\n");
266
267
  let src = withHead(&body);
267
268
  let names = copies("cap8", &src);
268
- assert_eq!(names.iter().filter(|n| n.starts_with("List.map$")).count(), 8, "{names:?}");
269
+ assert_eq!(names.iter().filter(|n| n.starts_with("List.map$")).count(), 10, "{names:?}");
269
270
  // sum over i of (6 + 3i) = 60 + 3 * 45
270
271
  assert_eq!(runInt("cap8", &src), 195);
271
272
  }
@@ -386,15 +387,33 @@ fn deep_recursive_closure_callee() {
386
387
  }
387
388
 
388
389
  #[test]
389
- fn many_call_sites_capped() {
390
+ fn a_small_callee_gets_a_copy_for_every_closure() {
390
- // 20 distinct closures to one callee: exactly MAX_COPIES (8) copies, the rest left as
391
+ // 20 distinct closures to one small callee: 20 copies, no closure call left, so which
391
- // ordinary closure calls, every result right.
392
+ // calls are inlined does not depend on how many others the program has (U4c).
392
393
  let mut body = String::from("import std/App\nprimitive Main[App] =\n fun apply(x: Int, f: fn(Int) -> Int) -> Int = f(x)\n\n fun main() -> Int =\n");
393
394
  for i in 0..20 {
394
395
  body.push_str(&format!(" r{1} := Main.apply(5, |x| x * {0} + {1})\n", i + 1, i));
395
396
  }
396
397
  body.push_str(" r0 + r1 + r2 + r3 + r4 + r5 + r6 + r7 + r8 + r9 + r10 + r11 + r12 + r13 + r14 + r15 + r16 + r17 + r18 + r19\n");
397
398
  let src = withHead(&body);
399
+ let names = copies("small20", &src);
400
+ assert_eq!(copiesOf(&names, "apply"), 20, "{names:?}");
401
+ let bytes = compile("small20", &src);
402
+ assert_eq!(callRefs(&bytes), 0, "every call site inlined");
403
+ assert_eq!(runIntBytes(&bytes), 1240);
404
+ }
405
+
406
+ #[test]
407
+ fn many_call_sites_capped() {
408
+ // 20 distinct closures to one big callee (more than SMALL_CALLEE nodes): exactly
409
+ // MAX_BIG_COPIES (8) copies, the rest left as ordinary closure calls, every result right.
410
+ let pad: String = (0..30).map(|i| format!(" + x * {i}")).collect();
411
+ let mut body = format!("import std/App\nprimitive Main[App] =\n fun apply(x: Int, f: fn(Int) -> Int) -> Int = f(x) - {{0{pad}}} + {{0{pad}}}\n\n fun main() -> Int =\n");
412
+ for i in 0..20 {
413
+ body.push_str(&format!(" r{1} := Main.apply(5, |x| x * {0} + {1})\n", i + 1, i));
414
+ }
415
+ body.push_str(" r0 + r1 + r2 + r3 + r4 + r5 + r6 + r7 + r8 + r9 + r10 + r11 + r12 + r13 + r14 + r15 + r16 + r17 + r18 + r19\n");
416
+ let src = withHead(&body);
398
417
  let names = copies("many20", &src);
399
418
  assert_eq!(copiesOf(&names, "apply"), 8, "{names:?}");
400
419
  // sum over i of (5 * (i + 1) + i) = 5 * 210 + 190
@@ -425,3 +444,31 @@ fn identical_closures_share_a_copy() {
425
444
  assert!(!names.contains(&"List.map$c1".to_string()), "{names:?}");
426
445
  assert_eq!(runInt("dedup", &src), 18);
427
446
  }
447
+
448
+ #[test]
449
+ fn a_callee_nesting_its_own_closure_stops_at_max_depth() {
450
+ // A copy of `nest` would hand `nest` a new closure built around the one it inlined: without
451
+ // a depth limit, copies could be made forever. (Today `g` captured by a closure counts as
452
+ // escaping, so `nest` is not specialised at all; MAX_DEPTH is the guard if that changes.)
453
+ let src = withHead(
454
+ "import std/App\nprimitive Main[App] =\n fun nest(n: Int, g: fn(Int) -> Int) -> Int = if n == 0 then g(0) else Main.nest(n - 1, |x| g(x) + 1)\n\n fun main() -> Int = Main.nest(10, |x| x + 5)\n",
455
+ );
456
+ let names = copies("nest", &src);
457
+ let n = copiesOf(&names, "nest");
458
+ assert!(n <= plum_core::closure_spec::MAX_DEPTH, "{n} copies in {names:?}");
459
+ assert_eq!(runInt("nest", &src), 15);
460
+ }
461
+
462
+ #[test]
463
+ fn a_walk_passing_its_closure_on_is_resolved_by_receiver_type() {
464
+ // `Bag.all` hands `keep` on to `all` of a `Bag`: the escape analysis resolves that call by
465
+ // the checker's receiver type, not to every `all` of the program, so `Keeper.all` storing
466
+ // its closure doesn't make `Bag.all`'s escape and the call is specialised (U4c: std's
467
+ // `List.all` was never specialised, as `Set.all` captures its closure).
468
+ let src = withHead(
469
+ "import std/App\nstruct Keeper(f: fn(Int) -> Bool) =\n fun all(self, keep: fn(Int) -> Bool) -> Bool = Keeper(f: keep).f(1)\n\nstruct Bag(n: Int) =\n fun all(self, keep: fn(Int) -> Bool) -> Bool = if self.n == 0 then true else if keep(self.n) then Bag(n: self.n - 1).all(keep) else false\n\nprimitive Main[App] =\n fun main() -> Int =\n k := 0\n a := if Bag(n: 3).all(|x| x > k) then 1 else 0\n b := if Keeper(f: |x| x > 5).all(|x| x > 0) then 10 else 0\n a + b\n",
470
+ );
471
+ let names = copies("bag_all", &src);
472
+ assert!(names.iter().any(|n| n.starts_with("Bag.all$c")), "{names:?}");
473
+ assert_eq!(runInt("bag_all", &src), 11);
474
+ }