plum

#treesitter#compiler#wasm

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

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


e325f30 — Peter John 2026-11-13T17:52:37+05:30
statics compile and optimise like free fns: a static's wasm signature has no receiver (`FuncSig::recv`, 0 for a free fn and a static) and a call pushes no stand-in, so `optimize::inlineLeaves` copies a small static into its callers (`Tool.digit` read its parameters from local 1 and was never copied); `simplify` inlines `T.f(..)` as it does `f(..)` (statics keyed `T.f`, not a trait's; in the recursion graph, `isPure`, `caseOfCase`), TRMC rewrites a static calling itself as `T.f(..)`; std's `Array.copy`/`equal` and native op bodies read their parameters from local 0; tests: simplify (a static inlined like the free fn, case-of-case through one, a recursive one not), TRMC (`Gen.upTo`), codegen (a static's loop is the free fn's code, a several-leaf owner adds no parameters); benchmarks/static_calls: static 0.79 s -> 0.57 s, free 0.57 s
benchmarks/static_calls/static_vs_free.plum CHANGED
@@ -8,6 +8,12 @@
8
8
  # `return_call` per step, the free fn's a branch). With that fixed `static` takes 0.78 s:
9
9
  # the rest of the gap is still open (the small static `digit` called from the loop is
10
10
  # the suspect: a free fn of that size is inlined).
11
+ #
12
+ # 2026-11-13: that was the rest. A static's wasm signature began with its type's receiver
13
+ # (`self`'s leaves) and every call pushed a stand-in for it, so `Tool.digit` read its
14
+ # parameters from local 1 and `optimize::inlineLeaves` did not copy it into the loop. A
15
+ # static now takes its arguments alone, like a free fn (and `simplify` and TRMC take `T.f(..)`
16
+ # as they take `f(..)`): `static` 0.57 s, `free` 0.57 s, the same code.
11
17
  import std/Io
12
18
  import std/Int
13
19
  import std/Float
compiler/core/src/simplify.rs CHANGED
@@ -1,4 +1,5 @@
1
- //! Simplifier: inline small pure non-recursive fns, pick the arm of a `match` on a known
1
+ //! Simplifier: inline small pure non-recursive fns (free fns and statics alike: `f(..)` and
2
+ //! `T.f(..)` are both candidates, keyed `f` and `T.f`), pick the arm of a `match` on a known
2
3
  //! constructor, push an outer `match` into the arms of an inner one (case-of-case), and
3
4
  //! read a field off a just-built record. Impure arguments are let-bound (or the inline is
4
5
  //! declined), never duplicated or dropped; every binder of an inlined body is renamed fresh.
@@ -87,6 +88,19 @@ pub fn mentions(b: &Block, names: &HashSet<String>) -> bool {
87
88
  hit
88
89
  }
89
90
 
91
+ /// The fn key `e` calls: `f` for a free call `f(..)`, `T.f` for a static call `T.f(..)` (a
92
+ /// method call on a bare type name; `Color.White.withAlpha(..)` is a method on a constant).
93
+ fn callKey(e: &Expr) -> Option<(String, &FnCall)> {
94
+ match &e.kind {
95
+ ExprKind::FnCall(c) => Some((c.name.clone(), c)),
96
+ ExprKind::Attribute(a) => match (&a.object.kind, &a.attr) {
97
+ (ExprKind::TypeName(t), AttrKind::Method(c)) if !t.contains('.') => Some((format!("{t}.{}", c.name), c)),
98
+ _ => None,
99
+ },
100
+ _ => None,
101
+ }
102
+ }
103
+
90
104
  /// The names `b` calls.
91
105
  pub fn calledNames(b: &Block) -> HashSet<String> {
92
106
  let mut out = HashSet::new();
@@ -156,6 +170,7 @@ enum M {
156
170
  /// The tables a `Cx` reads, built from the whole program: built once by a caller that
157
171
  /// simplifies many pieces of one program (drive), not once per piece.
158
172
  pub struct Tables {
173
+ /// free fns by name and statics by `T.f` (see `callKey`); not methods with `self`
159
174
  fns: HashMap<String, Fn>,
160
175
  recursive: HashSet<String>,
161
176
  /// constructor name -> declared field names (empty for nullary).
@@ -188,8 +203,8 @@ fn trivial(e: &Expr) -> bool {
188
203
  fn calls(f: &Fn) -> HashSet<String> {
189
204
  let mut out = HashSet::new();
190
205
  let mut note = |e: &Expr| {
191
- if let ExprKind::FnCall(c) = &e.kind {
206
+ if let Some((k, _)) = callKey(e) {
192
- out.insert(c.name.clone());
207
+ out.insert(k);
193
208
  }
194
209
  };
195
210
  match &f.body {
@@ -294,15 +309,18 @@ impl Tables {
294
309
  let mut fns = HashMap::new();
295
310
  let mut ctors: HashMap<String, Vec<String>> = HashMap::new();
296
311
  let mut variants = HashMap::new();
297
- let mut traits = HashSet::new();
312
+ let traits: HashSet<String> =
313
+ src.items.iter().filter_map(|i| if let Item::Trait(t) = i { Some(t.name.clone()) } else { None }).collect();
298
314
  for item in &src.items {
299
315
  match item {
300
- Item::Trait(t) => {
301
- traits.insert(t.name.clone());
302
- }
303
316
  Item::Fn(f) if f.type_param.is_none() => {
304
317
  fns.insert(f.name.clone(), f.clone());
305
318
  }
319
+ // A static, called `T.f(..)`: inlined like a free fn. Not a trait's (its
320
+ // calls go to the implementing type's).
321
+ Item::Fn(f) if !f.has_self && f.type_param.as_ref().is_some_and(|t| !traits.contains(t)) => {
322
+ fns.insert(fnKey(f), f.clone());
323
+ }
306
324
  Item::Enum(e) => {
307
325
  if crate::layout::isBoxedIn(e, &src.items) {
308
326
  ctors.insert(e.name.clone(), Vec::new());
@@ -355,7 +373,11 @@ impl<'a> Cx<'a> {
355
373
  ExprKind::FnCall(c) => !self.bound.contains(&c.name) && self.pure.contains(&c.name) && c.args.iter().all(|a| self.isPure(argRef(a))),
356
374
  ExprKind::Attribute(a) => match &a.attr {
357
375
  AttrKind::Field(_) => self.isPure(&a.object),
376
+ // a static call is pure as a free call is
358
- AttrKind::Method(_) => false,
377
+ AttrKind::Method(c) => match callKey(e) {
378
+ Some((k, _)) => self.pure.contains(&k) && c.args.iter().all(|a| self.isPure(argRef(a))),
379
+ None => false,
380
+ },
359
381
  },
360
382
  _ => childRefs(e).into_iter().all(|c| self.isPure(c)),
361
383
  }
@@ -373,7 +395,6 @@ impl<'a> Cx<'a> {
373
395
  && !f.is_fip
374
396
  && !f.is_export
375
397
  && !f.has_self
376
- && f.type_param.is_none()
377
398
  && !matches!(f.body, FnBody::Extern)
378
399
  && f.params.iter().all(|p| matches!(p.ty, ParamType::Type(_) | ParamType::Fn(..)))
379
400
  && sizeOf(f) <= MAX_SIZE
@@ -403,6 +424,9 @@ impl<'a> Cx<'a> {
403
424
  fn simExpr(&mut self, mut e: Expr, lets: Option<&mut Vec<Stmt>>) -> Expr {
404
425
  self.simChildren(&mut e);
405
426
  let (id, span) = (e.id, e.span);
427
+ if matches!(e.kind, ExprKind::FnCall(_)) || callKey(&e).is_some() {
428
+ return self.inlineCall(e, lets);
429
+ }
406
430
  match e.kind {
407
431
  ExprKind::Attribute(a) => match self.fieldOfCtor(*a) {
408
432
  Ok(v) => self.simExpr(v, None),
@@ -413,7 +437,6 @@ impl<'a> Cx<'a> {
413
437
  ExprKind::BoolLit(false) => t.else_,
414
438
  _ => Expr { id, span, kind: ExprKind::InlineIf(t) },
415
439
  },
416
- ExprKind::FnCall(c) => self.inlineCall(c, lets),
417
440
  other => Expr { id, span, kind: other },
418
441
  }
419
442
  }
@@ -451,25 +474,34 @@ impl<'a> Cx<'a> {
451
474
  Ok(c.fields.iter().find(|x| &x.name == f).map(|x| x.value.clone()).unwrap())
452
475
  }
453
476
 
477
+ /// `e`, a free call `f(..)` or a static call `T.f(..)` (see `callKey`), with the callee's
478
+ /// body in its place when it is `eligible`; else `e` as it was.
454
- fn inlineCall(&mut self, c: FnCall, lets: Option<&mut Vec<Stmt>>) -> Expr {
479
+ fn inlineCall(&mut self, e: Expr, lets: Option<&mut Vec<Stmt>>) -> Expr {
480
+ let Some((key, c)) = callKey(&e) else { return e };
481
+ let args = c.args.clone();
482
+ // a declined free call is rebuilt as before
483
+ let keep = |e: Expr| match e.kind {
484
+ ExprKind::FnCall(c) => Expr::FnCall(c),
485
+ _ => e,
486
+ };
455
- if self.depth >= MAX_DEPTH || self.eligible(&c.name).is_none() {
487
+ if self.depth >= MAX_DEPTH || self.eligible(&key).is_none() {
456
- return Expr::FnCall(c);
488
+ return keep(e);
457
489
  }
458
- let f = self.t.fns[&c.name].clone();
490
+ let f = self.t.fns[&key].clone();
459
- match self.instantiate(&f, &c.args, lets.is_some()) {
491
+ match self.instantiate(&f, &args, lets.is_some()) {
460
492
  // A body that is a block value is not inlined as an expression (its constructors
461
493
  // cannot be pinned through the statements).
462
494
  Some((binds, body))
463
495
  if body.stmts.len() == 1
464
496
  && matches!(&body.stmts[0].kind, StmtKind::Expr(e, ..) if !matches!(e.kind, ExprKind::Block(_))) =>
465
497
  {
466
- let Some(Stmt { kind: StmtKind::Expr(e, ..), .. }) = body.stmts.into_iter().next() else { unreachable!() };
498
+ let Some(Stmt { kind: StmtKind::Expr(b, ..), .. }) = body.stmts.into_iter().next() else { unreachable!() };
467
499
  if lets.is_none() && !binds.is_empty() {
468
- return Expr::FnCall(c);
500
+ return keep(e);
469
501
  }
470
- self.stack.push(c.name.clone());
502
+ self.stack.push(key);
471
503
  self.depth += 1;
472
- let r = self.simExpr(e, None);
504
+ let r = self.simExpr(b, None);
473
505
  self.depth -= 1;
474
506
  self.stack.pop();
475
507
  // The call's declared result type pinned a generic enum's instantiation
@@ -482,7 +514,7 @@ impl<'a> Cx<'a> {
482
514
  self.scope = outer;
483
515
  match pinned {
484
516
  Some(r) => r,
485
- None => return Expr::FnCall(c),
517
+ None => return keep(e),
486
518
  }
487
519
  }
488
520
  None => r,
@@ -492,7 +524,7 @@ impl<'a> Cx<'a> {
492
524
  }
493
525
  r
494
526
  }
495
- _ => Expr::FnCall(c),
527
+ _ => keep(e),
496
528
  }
497
529
  }
498
530
 
@@ -983,13 +1015,14 @@ impl<'a> Cx<'a> {
983
1015
  /// `match f(a) ..outer` where `f`'s body is a `match` whose arms each end in a value the
984
1016
  /// outer match resolves: the outer arm is chosen inside each inner arm.
985
1017
  fn caseOfCase(&mut self, m: &Match) -> Option<Vec<Stmt>> {
986
- let ExprKind::FnCall(c) = &m.subjects[0].kind else { return None };
1018
+ let (key, c) = callKey(&m.subjects[0])?;
987
1019
  if self.depth >= MAX_DEPTH {
988
1020
  return None;
989
1021
  }
990
- self.eligible(&c.name)?;
1022
+ self.eligible(&key)?;
991
- let f = self.t.fns[&c.name].clone();
1023
+ let f = self.t.fns[&key].clone();
1024
+ let args = c.args.clone();
992
- let (mut binds, mut body) = self.instantiate(&f, &c.args, true)?;
1025
+ let (mut binds, mut body) = self.instantiate(&f, &args, true)?;
993
1026
  if body.stmts.len() != 1 {
994
1027
  return None;
995
1028
  }
compiler/core/src/trmc.rs CHANGED
@@ -19,7 +19,8 @@
19
19
  //! code cannot assign a variant field). Evaluation order is unchanged: fields before the
20
20
  //! recursive one, then the recursive call's arguments, in source order.
21
21
  //!
22
+ //! Only rewrites non-export free fns, statics (calling themselves as `T.f(..)`) and methods
22
- //! Only rewrites free, non-export fns whose return type is an enum with an inline
23
+ //! whose return type is an enum with an inline
23
24
  //! variant and a nullary variant, with exactly one recursive field; fields after
24
25
  //! the recursive one must be plain variables or literals. Nothing under
25
26
  //! `?`/`!` or closures, no other `return`s outside tail
@@ -83,7 +84,7 @@ impl Cx<'_> {
83
84
  fn rewriteFn(f: &Fn, enums: &[Enum]) -> Option<Fn> {
84
85
  if f.is_export
85
86
  || f.is_extern
86
- || f.type_param.is_some() != f.has_self
87
+ || (f.has_self && f.type_param.is_none())
87
88
  || f.is_test
88
89
  {
89
90
  return None;
@@ -468,13 +469,18 @@ impl<'a> Cx<'a> {
468
469
  Some(Some(stmts))
469
470
  }
470
471
 
471
- /// A direct self call: `name(..)` in a free fn, `recv.name(..)` in a method.
472
+ /// A direct self call: `name(..)` in a free fn, `T.name(..)` in a static of `T`,
472
- /// Returns the receiver (methods only) and the call.
473
+ /// `recv.name(..)` in a method. Returns the receiver (methods only) and the call.
473
474
  fn selfCall<'e>(&self, e: &'e Expr) -> Option<(Option<&'e Expr>, &'e FnCall)> {
475
+ let f = self.f;
474
476
  match &e.kind {
475
- ExprKind::FnCall(c) if !self.f.has_self && c.name == self.f.name => Some((None, c)),
477
+ ExprKind::FnCall(c) if !f.has_self && f.type_param.is_none() && c.name == f.name => Some((None, c)),
476
- ExprKind::Attribute(a) if self.f.has_self => match &a.attr {
478
+ ExprKind::Attribute(a) if f.has_self => match &a.attr {
477
- AttrKind::Method(c) if c.name == self.f.name => Some((Some(&a.object), c)),
479
+ AttrKind::Method(c) if c.name == f.name => Some((Some(&a.object), c)),
480
+ _ => None,
481
+ },
482
+ ExprKind::Attribute(a) => match (&a.object.kind, &a.attr, &f.type_param) {
483
+ (ExprKind::TypeName(t), AttrKind::Method(c), Some(owner)) if t == owner && c.name == f.name => Some((None, c)),
478
484
  _ => None,
479
485
  },
480
486
  _ => None,
compiler/core/tests/core/simplify_test.rs CHANGED
@@ -293,3 +293,30 @@ fn nullaryGenericCtorIsNotInlined() {
293
293
  );
294
294
  assert!(matches!(onlyExpr(&b), Expr { kind: ExprKind::FnCall(c), .. } if c.name == "none"), "{b:?}");
295
295
  }
296
+
297
+ /// A static (`T.f(..)`) is inlined as a free fn is: the same body, nothing left of the call.
298
+ /// `caseOfCase` sees through a static call too.
299
+ #[test]
300
+ fn staticCallIsInlinedLikeAFreeCall() {
301
+ let src = "struct Sq(x: Int) =\n fun sq(n: Int) -> Int = n * n + 1\n fun mk(b: Bool) -> Lst = match b\n true => Nil\n false => Cons(head: 1, tail: Nil)\n\
302
+ fun sq(n: Int) -> Int = n * n + 1\n\
303
+ fun a(v: Int) -> Int = sq(v) + 2\n\
304
+ fun b(v: Int) -> Int = Sq.sq(v) + 2\n\
305
+ fun c(b: Bool) -> Int = match Sq.mk(b)\n Nil => 0\n Cons(h, _) => h\n";
306
+ let free = simp(src, "a", &["sq"]);
307
+ let st = simp(src, "b", &["Sq.sq"]);
308
+ assert_eq!(plum_test_support::debugNoIds(&st), plum_test_support::debugNoIds(&free));
309
+ assert!(!format!("{st:?}").contains("Attribute"), "{st:?}");
310
+ let m = simp(src, "c", &["Sq.mk"]);
311
+ let [Stmt { kind: StmtKind::Match(m), .. }] = &m.stmts[..] else { panic!("{m:?}") };
312
+ assert!(matches!(&m.subjects[0], Expr { kind: ExprKind::Var(v), .. } if v.starts_with('b')), "{m:?}");
313
+ }
314
+
315
+ /// A static that calls itself is recursive, as a free fn would be: not inlined.
316
+ #[test]
317
+ fn recursiveStaticIsNotInlined() {
318
+ let src = "struct Sq(x: Int) =\n fun down(n: Int) -> Int = if n <= 0 then 0 else down(n - 1)\n\
319
+ fun g(v: Int) -> Int = Sq.down(v)\n";
320
+ let b = simp(src, "g", &["Sq.down"]);
321
+ assert!(matches!(onlyExpr(&b), Expr { kind: ExprKind::Attribute(_), .. }), "{b:?}");
322
+ }
compiler/core/tests/core/trmc_test.rs CHANGED
@@ -186,6 +186,24 @@ fun main() -> Int =
186
186
  assert_eq!(runInt("fromTo2", &p), 1);
187
187
  }
188
188
 
189
+ /// A static calling itself (`Gen.upTo(..)`) is rewritten as the free `fromTo` is.
190
+ #[test]
191
+ fn static_rewritten_like_free() {
192
+ let p = prog(
193
+ "\
194
+ struct Gen(x: Int) =
195
+ fun upTo(a: Int, b: Int) -> Link<Int> =
196
+ if a >= b then Nil else Cons(head: a, tail: Gen.upTo(a + 1, b))
197
+
198
+ fun main() -> Int =
199
+ big := Gen.upTo(0, 1000000)
200
+ if count(Gen.upTo(3, 3)) == 0 && toInt(Gen.upTo(1, 5)) == 1234 && count(big) == 1000000 && sum(big) == 499999500000 then 1 else 0
201
+ ",
202
+ );
203
+ assert!(isRewritten("static1", &p, "upTo"));
204
+ assert_eq!(runInt("static2", &p), 1);
205
+ }
206
+
189
207
  #[test]
190
208
  fn append_rewritten() {
191
209
  let p = prog(
compiler/wasm-codegen/src/calls.rs CHANGED
@@ -293,7 +293,9 @@ pub(crate) fn compileMethodCallAs(
293
293
  {
294
294
  let recv = plum_checker::methodReceiverName(obj_ty).unwrap_or_default();
295
295
  if matches!(object, ast::Expr { kind: ast::ExprKind::TypeName(n), .. } if *n == recv || typeParamOwner(n, ctx)) {
296
+ // A static takes no receiver (`sig.recv` is 0); a method called on a bare type
297
+ // name gets a stand-in its body never reads.
296
- for vt in sig.params.iter().take(leafCount(obj_ty) as usize) {
298
+ for vt in sig.params.iter().take(sig.recv) {
297
299
  pushSelfPlaceholder(*vt, body);
298
300
  }
299
301
  } else {
@@ -330,26 +332,15 @@ pub(crate) fn compileMethodCallAs(
330
332
  .func_ids
331
333
  .get(&key)
332
334
  .ok_or_else(|| format!("codegen: unknown method '{}.{}'", class_name, method))?;
333
- // A "static"-style call (`Bool.parse("true")`, `Float.fromStr("3.14")`) on a
335
+ // A call on the type's bare name (`Bool.parse("true")`, `Tool.digit(s, i)`): a static,
334
- // self-less method declared inside a `type`/`enum` body — its receiver is a
336
+ // which takes its arguments alone, like a free fn (`FuncSig::recv` is 0), so it is
335
- // bare reference to the type's own name, not a real value. Every method still
337
+ // optimised like one (`optimize::inlineLeaves`, tail calls). A method with `self`
336
- // reserves a leading self slot in its wasm signature regardless of whether its
337
- // Plum source declares a `self` param (see `fnWasmParamTypes`), so something of
338
- // the right type must still be pushed — the body simply never reads it.
338
+ // called on a bare type name still gets a stand-in receiver its body never reads.
339
339
  let is_static_call = matches!(object, ast::Expr { kind: ast::ExprKind::TypeName(n), .. } if *n == class_name || typeParamOwner(n, ctx));
340
- // A static native op (`Float.fromBits`) is its instruction on the arguments alone: no
341
- // self slot.
342
- let native = withGen(|s| s.native_fns.contains_key(&func_idx));
343
340
  if is_static_call {
344
- if !native {
345
- match ctx.func_sigs.get(&key) {
341
+ if let Some(s) = ctx.func_sigs.get(&key) {
346
- Some(s) if !s.params.is_empty() => {
347
- let n = leafCount(&PlumType::TNamed(class_name.clone())) as usize;
348
- for vt in s.params.iter().take(n) {
342
+ for vt in s.params.iter().take(s.recv) {
349
- pushSelfPlaceholder(*vt, body);
343
+ pushSelfPlaceholder(*vt, body);
350
- }
351
- }
352
- _ => pushSelfPlaceholder(ValType::I32, body),
353
344
  }
354
345
  }
355
346
  } else {
compiler/wasm-codegen/src/context.rs CHANGED
@@ -19,6 +19,9 @@ pub struct FuncSig {
19
19
  /// The instantiation this is the signature of (`None` for a plain fn): the checker
20
20
  /// recorded the types of `param_defaults` there.
21
21
  pub inst: Option<usize>,
22
+ /// How many of `params` are the receiver (`self`'s leaves): 0 for a free fn and for a
23
+ /// static, which takes its declared parameters only, like a free fn.
24
+ pub recv: usize,
22
25
  }
23
26
 
24
27
  /// Everything codegen needs to know about one closure *literal* found in the program.
compiler/wasm-codegen/src/fnbody.rs CHANGED
@@ -392,7 +392,7 @@ pub(crate) fn compileFnBodyImpl(
392
392
  let mut groups: Vec<ValType> = Vec::new();
393
393
  let mut idx = 0u32;
394
394
 
395
- if f.type_param.is_some() {
395
+ if f.type_param.is_some() && f.has_self {
396
396
  locals.insert("self".to_string(), idx);
397
397
  idx += decl_types.get("self").map(leafCount).unwrap_or(1);
398
398
  }
compiler/wasm-codegen/src/intrinsics.rs CHANGED
@@ -78,9 +78,8 @@ pub(crate) fn castToEq(vt: &ValType, body: &mut Vec<u8>) {
78
78
  }
79
79
 
80
80
  /// The body of a std native op (`plum_core::native`), for a call that is not in line (the fn
81
- /// passed as a value): its parameters, each one wasm local, then the instruction. A self-less
81
+ /// passed as a value): its parameters, each one wasm local, then the instruction. A
82
- /// one in a type (`Float.fromBits`) still has the type's leading self slot (one local: the
82
+ /// self-less one in a type (`Float.fromBits`) is a static: no receiver, like a free fn.
83
- /// receivers are `Int` and `Float`), which it skips.
84
83
  pub(crate) fn compileNativeFnBody(f: &ast::Fn, op: plum_core::native::NativeOp) -> Vec<u8> {
85
84
  use plum_core::native::NativeOp as N;
86
85
  let mut body = vec![0u8];
@@ -110,9 +109,8 @@ pub(crate) fn compileNativeFnBody(f: &ast::Fn, op: plum_core::native::NativeOp)
110
109
  Instruction::I32Add.encode(&mut body);
111
110
  }
112
111
  _ => {
113
- let skip = u32::from(f.type_param.is_some() && !f.has_self);
114
112
  let n = f.params.len() as u32 + u32::from(f.has_self);
115
- for local in skip..skip + n {
113
+ for local in 0..n {
116
114
  get(local, &mut body);
117
115
  }
118
116
  emitNativeOp(op, &mut body);
@@ -228,10 +226,9 @@ pub(crate) fn wrapBytesAsStr(body: &mut Vec<u8>) {
228
226
  /// `Array<T>`'s `init`/`at`/`set`/`length` — the intrinsic is backed by ONE wasm-gc `array<anyref>` type
229
227
  /// (`GcTypeRegistry::array_type_idx`, see `isArraySpecialization`), so these
230
228
  /// compile identically regardless of the concrete `T`.
231
- /// Every `type_param`-bearing `Fn` — methods AND non-`self` nested
232
- /// "static" constructors like `init` (see `fnWasmParamTypes`) — gets an
233
- /// implicit receiver as wasm param 0, so a declared plum param at position `k`
229
+ /// A method (`at`, `push`) has its receiver as wasm param 0, so its declared param `k` is
230
+ /// wasm local `k + 1`; a static (`init`, `copy`, `equal`) has none, so its param `k` is
234
- /// is always wasm local `k + 1`. `at` is the one case that also needs a
231
+ /// local `k` (see `units::unitDeclTypes`). `at` is the one case that also needs a
235
232
  /// `ref.cast` back from the raw stored `anyref` down to `T`'s own concrete
236
233
  /// type; `set`/`init` need no such cast the other way, since any concrete ref
237
234
  /// is already a valid subtype wherever `anyref` is expected.
@@ -388,16 +385,16 @@ pub(crate) fn compileArrayIntrinsicFnBody(f: &ast::Fn, subst: &Subst) -> Option<
388
385
  Some(body)
389
386
  }
390
387
  // Array.copy(dst, dstStart, src, srcStart, n) — `array.copy`; overlapping
391
- // ranges are handled. Local 0 is the unused static `self` slot.
388
+ // ranges are handled. A static: its parameters are locals 0..4.
392
389
  "copy" => {
393
390
  let mut body = vec![0u8];
394
- Instruction::LocalGet(1).encode(&mut body); // dst
391
+ Instruction::LocalGet(0).encode(&mut body); // dst
395
- Instruction::LocalGet(2).encode(&mut body); // dstStart
392
+ Instruction::LocalGet(1).encode(&mut body); // dstStart
396
393
  Instruction::I32WrapI64.encode(&mut body);
397
- Instruction::LocalGet(3).encode(&mut body); // src
394
+ Instruction::LocalGet(2).encode(&mut body); // src
398
- Instruction::LocalGet(4).encode(&mut body); // srcStart
395
+ Instruction::LocalGet(3).encode(&mut body); // srcStart
399
396
  Instruction::I32WrapI64.encode(&mut body);
400
- Instruction::LocalGet(5).encode(&mut body); // n
397
+ Instruction::LocalGet(4).encode(&mut body); // n
401
398
  Instruction::I32WrapI64.encode(&mut body);
402
399
  Instruction::ArrayCopy {
403
400
  array_type_index_dst: array_type_idx,
@@ -409,7 +406,7 @@ pub(crate) fn compileArrayIntrinsicFnBody(f: &ast::Fn, subst: &Subst) -> Option<
409
406
  }
410
407
  // Array.equal(a, aStart, b, bStart, n) -> Bool for a scalar `T` — the
411
408
  // memcmp analog: a tight loop with early exit on mismatch.
412
- // Local 0 is the unused static `self` slot; 6 = i, 7 = n, 8 = aStart, 9 = bStart (i32).
409
+ // A static: locals 0..4 are its parameters; 5 = i, 6 = n, 7 = aStart, 8 = bStart (i32).
413
410
  "equal" => {
414
411
  let (get, ne): (fn(u32) -> Instruction<'static>, Instruction<'static>) =
415
412
  match array_elem {
@@ -424,29 +421,29 @@ pub(crate) fn compileArrayIntrinsicFnBody(f: &ast::Fn, subst: &Subst) -> Option<
424
421
  Instruction::LocalGet(l).encode(b);
425
422
  Instruction::I32WrapI64.encode(b);
426
423
  };
427
- wrap(&mut body, 5);
424
+ wrap(&mut body, 4);
425
+ Instruction::LocalSet(6).encode(&mut body);
426
+ wrap(&mut body, 1);
428
427
  Instruction::LocalSet(7).encode(&mut body);
429
- wrap(&mut body, 2);
428
+ wrap(&mut body, 3);
430
429
  Instruction::LocalSet(8).encode(&mut body);
431
- wrap(&mut body, 4);
432
- Instruction::LocalSet(9).encode(&mut body);
433
430
  Instruction::Block(BlockType::Result(ValType::I32)).encode(&mut body);
434
431
  Instruction::Loop(BlockType::Empty).encode(&mut body);
432
+ Instruction::LocalGet(5).encode(&mut body);
435
433
  Instruction::LocalGet(6).encode(&mut body);
436
- Instruction::LocalGet(7).encode(&mut body);
437
434
  Instruction::I32GeS.encode(&mut body);
438
435
  Instruction::If(BlockType::Empty).encode(&mut body);
439
436
  Instruction::I32Const(1).encode(&mut body);
440
437
  Instruction::Br(2).encode(&mut body);
441
438
  Instruction::End.encode(&mut body);
442
- Instruction::LocalGet(1).encode(&mut body);
439
+ Instruction::LocalGet(0).encode(&mut body);
443
- Instruction::LocalGet(8).encode(&mut body);
440
+ Instruction::LocalGet(7).encode(&mut body);
444
- Instruction::LocalGet(6).encode(&mut body);
441
+ Instruction::LocalGet(5).encode(&mut body);
445
442
  Instruction::I32Add.encode(&mut body);
446
443
  get(array_type_idx).encode(&mut body);
447
- Instruction::LocalGet(3).encode(&mut body);
444
+ Instruction::LocalGet(2).encode(&mut body);
448
- Instruction::LocalGet(9).encode(&mut body);
445
+ Instruction::LocalGet(8).encode(&mut body);
449
- Instruction::LocalGet(6).encode(&mut body);
446
+ Instruction::LocalGet(5).encode(&mut body);
450
447
  Instruction::I32Add.encode(&mut body);
451
448
  get(array_type_idx).encode(&mut body);
452
449
  ne.encode(&mut body);
@@ -454,10 +451,10 @@ pub(crate) fn compileArrayIntrinsicFnBody(f: &ast::Fn, subst: &Subst) -> Option<
454
451
  Instruction::I32Const(0).encode(&mut body);
455
452
  Instruction::Br(2).encode(&mut body);
456
453
  Instruction::End.encode(&mut body);
457
- Instruction::LocalGet(6).encode(&mut body);
454
+ Instruction::LocalGet(5).encode(&mut body);
458
455
  Instruction::I32Const(1).encode(&mut body);
459
456
  Instruction::I32Add.encode(&mut body);
460
- Instruction::LocalSet(6).encode(&mut body);
457
+ Instruction::LocalSet(5).encode(&mut body);
461
458
  Instruction::Br(0).encode(&mut body);
462
459
  Instruction::End.encode(&mut body); // loop
463
460
  Instruction::Unreachable.encode(&mut body);
compiler/wasm-codegen/src/traits.rs CHANGED
@@ -195,6 +195,7 @@ fn dispatcherSig(obj: &PlumType, method: &str, traits: &Traits, reg: &GcTypeRegi
195
195
  decl_params: params,
196
196
  decl_ret: *ret,
197
197
  inst: None,
198
+ recv: 1,
198
199
  })
199
200
  }
200
201
 
compiler/wasm-codegen/src/units.rs CHANGED
@@ -34,14 +34,15 @@ pub(crate) fn recvPlumType(recv: &str, subst: &Subst, eg: &EnumGenerics) -> Plum
34
34
  }
35
35
  }
36
36
 
37
- /// `(self type, declared param types, return type)`, generics substituted.
37
+ /// `(self type, declared param types, return type)`, generics substituted. A static (a fn
38
+ /// in a type's body without `self`) has no self type: its wasm signature is a free fn's.
38
39
  pub(crate) fn unitDeclTypes(
39
40
  f: &ast::Fn,
40
41
  subst: &Subst,
41
42
  eg: &EnumGenerics,
42
43
  ) -> (Option<PlumType>, Vec<PlumType>, PlumType) {
43
44
  let sub = |t: PlumType| plum_checker::types::substitute(&t, subst);
44
- let self_ty = f.type_param.as_deref().map(|r| recvPlumType(r, subst, eg));
45
+ let self_ty = f.type_param.as_deref().filter(|_| f.has_self).map(|r| recvPlumType(r, subst, eg));
45
46
  let owner: Vec<String> = f
46
47
  .type_param
47
48
  .as_deref()
@@ -65,6 +66,7 @@ pub(crate) fn unitFuncSig(f: &ast::Fn, subst: &Subst, eg: &EnumGenerics, g: &GcT
65
66
  if let Some(s) = &self_ty {
66
67
  leafTypes(s, g, &mut vts);
67
68
  }
69
+ let recv = vts.len();
68
70
  for p in &params {
69
71
  leafTypes(p, g, &mut vts);
70
72
  }
@@ -88,6 +90,7 @@ pub(crate) fn unitFuncSig(f: &ast::Fn, subst: &Subst, eg: &EnumGenerics, g: &GcT
88
90
  decl_params: params,
89
91
  decl_ret: ret,
90
92
  inst: None,
93
+ recv,
91
94
  }
92
95
  }
93
96
 
compiler/wasm-codegen/tests/wasm_codegen/optimize_test.rs CHANGED
@@ -180,6 +180,44 @@ fun main() -> Int =
180
180
  assert_eq!(runInt("cmp", src), (-10 + 1) * 100 + (10 - 1));
181
181
  }
182
182
 
183
+ /// A static (`Tool.digit(..)`, a fn in a type's body without `self`) takes its arguments alone,
184
+ /// as a free fn does: no receiver stand-in is pushed, so a small one is copied into its callers
185
+ /// like a free fn, and a static's loop compiles to the free fn's code (benchmarks/static_calls).
186
+ /// An owner of several leaves (`Pair2`) adds no parameters either.
187
+ #[test]
188
+ fn staticCompilesLikeAFreeFn() {
189
+ let src = "\
190
+ import std/Int
191
+ import std/Str
192
+
193
+ struct Tool(x: Int) =
194
+ fun digitsValue(ds: Str, i: Int, j: Int, acc: Int) -> Int =
195
+ if i >= j then acc else digitsValue(ds, i + 1, j, acc * 10 + digit(ds, i))
196
+
197
+ fun digit(ds: Str, i: Int) -> Int = ds.byteAtUnchecked(i) - 48
198
+
199
+ struct Pair2(a: Int, b: Int, c: Str) =
200
+ fun twice(n: Int) -> Int = if n > 100 then n else Pair2.twice(n * 2)
201
+
202
+ fun digitsValue(ds: Str, i: Int, j: Int, acc: Int) -> Int =
203
+ if i >= j then acc else digitsValue(ds, i + 1, j, acc * 10 + digit(ds, i))
204
+
205
+ fun digit(ds: Str, i: Int) -> Int = ds.byteAtUnchecked(i) - 48
206
+
207
+ fun main() -> Int =
208
+ Tool.digitsValue(\"1234\", 0, 4, 0) * 10000 + digitsValue(\"5678\", 0, 4, 0) + Pair2.twice(3)
209
+ ";
210
+ let all = bodies(&compile("statics", src));
211
+ let names: Vec<&str> = all.iter().map(|b| b.0.as_str()).collect();
212
+ assert!(!names.contains(&"Tool.digit") && !names.contains(&"digit"), "{names:?}");
213
+ assert_eq!(body(&all, "Tool.digitsValue"), body(&all, "digitsValue"));
214
+ // `n` is local 0: no receiver leaves before it
215
+ let twice = body(&all, "Pair2.twice");
216
+ assert!(twice.iter().any(|op| op == "LocalGet { local_index: 0 }"), "{twice:?}");
217
+ assert!(!twice.iter().any(|op| op.starts_with("LocalGet { local_index: ") && op != "LocalGet { local_index: 0 }"), "{twice:?}");
218
+ assert_eq!(runInt("statics", src), 1234 * 10000 + 5678 + 192);
219
+ }
220
+
183
221
  /// A fn's closures get distinct names: `f.closure`, `f.closure2`.
184
222
  #[test]
185
223
  fn closuresOfOneFnHaveDistinctNames() {