plum

#treesitter#compiler#wasm

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

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


383c28e — Peter John 2026-11-11T00:49:56+05:30
drive: build the simplifier's tables once per drive, not once per call
compiler/core/src/drive.rs CHANGED
@@ -11,7 +11,7 @@
11
11
  use crate::ast::*;
12
12
  use crate::generics::Scope;
13
13
  use crate::rename::{renameStmts, substPT, substStmts, substType, Name};
14
- use crate::simplify::{boundNames, calledNames, mentions, pinExpr, simplifyBlock, simplifyBlockIn};
14
+ use crate::simplify::{boundNames, calledNames, mentions, pinExprWith, simplifyBlockInWith, simplifyBlockWith};
15
15
  use crate::visit::{argRef, innerBlockRefs, isTag, walkBlockRef, walkRef};
16
16
  use crate::visit::{childRefs, stmtBlockRefs, stmtBlocks, stmtExprRefs, visitBlock, visitExpr};
17
17
  use crate::whistle::embeds;
@@ -62,7 +62,8 @@ struct Call {
62
62
  }
63
63
 
64
64
  struct Driver {
65
+ /// The simplifier's tables of the program being driven (it is read, never changed).
65
- snap: Source,
66
+ simp: crate::simplify::Tables,
66
67
  fns: HashMap<String, Fn>,
67
68
  free: HashSet<String>,
68
69
  /// names the fn being driven binds: a call of one is not a call of the free fn of that name
@@ -511,7 +512,7 @@ impl Driver {
511
512
 
512
513
  fn new(src: &Source, pure: &HashSet<String>) -> Driver {
513
514
  let mut d = Driver {
514
- snap: src.clone(),
515
+ simp: crate::simplify::Tables::new(src),
515
516
  fns: HashMap::new(),
516
517
  free: HashSet::new(),
517
518
  bound: HashSet::new(),
@@ -1334,7 +1335,7 @@ impl Driver {
1334
1335
  });
1335
1336
  pre.extend(blk.stmts);
1336
1337
  let mut out = Block { stmts: pre };
1337
- out = simplifyBlockIn(out, &self.snap, &self.pure, &self.bound);
1338
+ out = simplifyBlockInWith(out, &self.simp, &self.pure, &self.bound);
1338
1339
  let stuck = out.stmts.iter().any(|s| match &s.kind {
1339
1340
  StmtKind::Match(m) => m.subjects.len() == 1 && self.ctorType(&m.subjects[0]).is_some(),
1340
1341
  _ => false,
@@ -1348,7 +1349,7 @@ impl Driver {
1348
1349
  let ty = known.clone().or(c.f.returns.clone());
1349
1350
  if let (Some(t), Some(Stmt { kind: StmtKind::Expr(r, ..), .. })) = (ty, out.stmts.last_mut()) {
1350
1351
  let v = std::mem::replace(r, Expr::Int(0));
1351
- match pinExpr(v, &t, &self.snap, &self.pure, &self.scopeOf(&c.f)) {
1352
+ match pinExprWith(v, &t, &self.simp, &self.pure, &self.scopeOf(&c.f)) {
1352
1353
  Ok(v) => *r = v,
1353
1354
  Err(v) if known.is_none() => {
1354
1355
  *r = v;
@@ -1501,7 +1502,7 @@ impl Driver {
1501
1502
  });
1502
1503
  // the wrapper's result type pinned its constructors' generics
1503
1504
  if let Some(t) = self.resultType(c).or(c.f.returns.clone()) {
1504
- body = pinExpr(body, &t, &self.snap, &self.pure, &self.scopeOf(&c.f))
1505
+ body = pinExprWith(body, &t, &self.simp, &self.pure, &self.scopeOf(&c.f))
1505
1506
  .map_err(|_| format!("wrapper {} builds a value only its result type can type", c.key))?;
1506
1507
  }
1507
1508
  Ok(body)
@@ -1919,7 +1920,7 @@ impl Driver {
1919
1920
  }
1920
1921
  }
1921
1922
  let pscope = sc.merge(&Scope::named(&fresh));
1922
- let pin = |e: Expr| pinExpr(e, &pret, &self.snap, &self.pure, &pscope).unwrap_or_else(|e| e);
1923
+ let pin = |e: Expr| pinExprWith(e, &pret, &self.simp, &self.pure, &pscope).unwrap_or_else(|e| e);
1923
1924
  let tcx = Tcx { pin: &pin, cases, callee: c.f.clone(), k, cn: cn.clone(), ctors: self.ctors.clone(), built: Default::default(), called: Default::default() };
1924
1925
  let mut body = tcx
1925
1926
  .tailMap(&pbody)
@@ -1927,7 +1928,7 @@ impl Driver {
1927
1928
  if tcx.built.get() == 0 && tcx.called.get() == 0 {
1928
1929
  return Err(format!("producer {} has no constructor or call at a tail (nothing to eliminate)", p.key));
1929
1930
  }
1930
- body = simplifyBlock(body, &self.snap, &self.pure);
1931
+ body = simplifyBlockWith(body, &self.simp, &self.pure);
1931
1932
  if blockSize(&body) > GROWTH * (blockSize(&cbody) + blockSize(&pbody)) + 100 {
1932
1933
  return Err(format!("budget: the fused body exceeds the size budget ({} nodes)", blockSize(&body)));
1933
1934
  }
compiler/core/src/simplify.rs CHANGED
@@ -25,18 +25,29 @@ fn fresh() -> usize {
25
25
  }
26
26
 
27
27
  pub fn simplifyExpr(e: Expr, src: &Source, pure: &HashSet<String>) -> Expr {
28
+ let t = Tables::new(src);
28
- let mut cx = Cx::new(src, pure);
29
+ let mut cx = Cx::new(&t, pure);
29
30
  cx.bound = boundNames(&[], &FnBody::Expr(e.clone()));
30
31
  cx.simExpr(e, None)
31
32
  }
32
33
 
33
34
  pub fn simplifyBlock(b: Block, src: &Source, pure: &HashSet<String>) -> Block {
35
+ simplifyBlockWith(b, &Tables::new(src), pure)
36
+ }
37
+
38
+ /// `simplifyBlock` with the program's tables built already.
39
+ pub fn simplifyBlockWith(b: Block, t: &Tables, pure: &HashSet<String>) -> Block {
34
- simplifyBlockIn(b, src, pure, &HashSet::new())
40
+ simplifyBlockInWith(b, t, pure, &HashSet::new())
35
41
  }
36
42
 
37
43
  /// `simplifyBlock` for a block that will sit in a scope binding `outer`.
38
44
  pub fn simplifyBlockIn(b: Block, src: &Source, pure: &HashSet<String>, outer: &HashSet<String>) -> Block {
45
+ simplifyBlockInWith(b, &Tables::new(src), pure, outer)
46
+ }
47
+
48
+ /// `simplifyBlockIn` with the program's tables built already.
49
+ pub fn simplifyBlockInWith(b: Block, t: &Tables, pure: &HashSet<String>, outer: &HashSet<String>) -> Block {
39
- let mut cx = Cx::new(src, pure);
50
+ let mut cx = Cx::new(t, pure);
40
51
  cx.bound = boundNames(&[], &FnBody::Block(b.clone()));
41
52
  cx.bound.extend(outer.iter().cloned());
42
53
  cx.simBlock(b)
@@ -91,21 +102,27 @@ pub fn calledNames(b: &Block) -> HashSet<String> {
91
102
  /// written with `t`'s type arguments (see `Cx::pin`). `Err(e)` when a context-typed tail
92
103
  /// constructor cannot carry them (a nullary variant, a positional payload, an open `t`).
93
104
  pub fn pinExpr(e: Expr, t: &Type, src: &Source, pure: &HashSet<String>, scope: &Scope) -> Result<Expr, Expr> {
105
+ pinExprWith(e, t, &Tables::new(src), pure, scope)
106
+ }
107
+
108
+ /// `pinExpr` with the program's tables built already.
109
+ pub fn pinExprWith(e: Expr, t: &Type, tables: &Tables, pure: &HashSet<String>, scope: &Scope) -> Result<Expr, Expr> {
94
- let mut cx = Cx::new(src, pure);
110
+ let mut cx = Cx::new(tables, pure);
95
111
  cx.scope = scope.clone();
96
112
  cx.pin(e.clone(), t, true).ok_or(e)
97
113
  }
98
114
 
99
115
  /// Simplifies every fn body; returns the names of the fns that changed.
100
116
  pub fn simplify(src: &mut Source, pure: &HashSet<String>) -> Vec<String> {
117
+ let t = Tables::new(src);
101
- let mut cx = Cx::new(src, pure);
118
+ let mut cx = Cx::new(&t, pure);
102
119
  let mut changed = Vec::new();
103
120
  for item in &mut src.items {
104
121
  let Item::Fn(f) = item else { continue };
105
122
  if f.is_extern {
106
123
  continue;
107
124
  }
108
- cx.scope = Scope::in_(&cx.owners, f);
125
+ cx.scope = Scope::in_(&cx.t.owners, f);
109
126
  cx.bound = boundNames(&f.params, &f.body);
110
127
  let before = f.body.clone();
111
128
  let block = match std::mem::replace(&mut f.body, FnBody::Extern) {
@@ -136,21 +153,16 @@ enum M {
136
153
  Unknown,
137
154
  }
138
155
 
156
+ /// The tables a `Cx` reads, built from the whole program: built once by a caller that
157
+ /// simplifies many pieces of one program (drive), not once per piece.
139
- struct Cx<'a> {
158
+ pub struct Tables {
140
- pure: &'a HashSet<String>,
141
159
  fns: HashMap<String, Fn>,
142
160
  recursive: HashSet<String>,
143
161
  /// constructor name -> declared field names (empty for nullary).
144
162
  ctors: HashMap<String, Vec<String>>,
145
163
  /// constructor name -> (its enum, the enum's generics, field types in declared order)
146
164
  variants: HashMap<String, (String, Vec<String>, Vec<Type>)>,
147
- stack: Vec<String>,
148
- depth: usize,
149
- /// generic names in scope in the fn being simplified
150
- scope: Scope,
151
165
  owners: HashMap<String, Vec<String>>,
152
- /// names the fn being simplified binds: see `boundNames`
153
- bound: HashSet<String>,
154
166
  /// trait names: a fn whose signature names one is not inlined (see `eligible`)
155
167
  traits: HashSet<String>,
156
168
  /// fns whose body names one of their own generics (`T.Max`, `x: List<T> := ..`): inlined,
@@ -158,6 +170,17 @@ struct Cx<'a> {
158
170
  namesGenerics: HashSet<String>,
159
171
  }
160
172
 
173
+ struct Cx<'a> {
174
+ pure: &'a HashSet<String>,
175
+ t: &'a Tables,
176
+ stack: Vec<String>,
177
+ depth: usize,
178
+ /// generic names in scope in the fn being simplified
179
+ scope: Scope,
180
+ /// names the fn being simplified binds: see `boundNames`
181
+ bound: HashSet<String>,
182
+ }
183
+
161
184
  fn trivial(e: &Expr) -> bool {
162
185
  matches!(&e.kind, ExprKind::Var(_) | ExprKind::Int(_) | ExprKind::Float(_) | ExprKind::BoolLit(_) | ExprKind::TypeName(_))
163
186
  }
@@ -266,8 +289,8 @@ fn usesOf(e: &Expr, name: &str, lazy: bool, acc: &mut (usize, usize)) {
266
289
  }
267
290
  }
268
291
 
269
- impl<'a> Cx<'a> {
292
+ impl Tables {
270
- fn new(src: &Source, pure: &'a HashSet<String>) -> Self {
293
+ pub fn new(src: &Source) -> Tables {
271
294
  let mut fns = HashMap::new();
272
295
  let mut ctors: HashMap<String, Vec<String>> = HashMap::new();
273
296
  let mut variants = HashMap::new();
@@ -313,7 +336,13 @@ impl<'a> Cx<'a> {
313
336
  }
314
337
  let owners = crate::generics::ownerGenerics(src);
315
338
  let namesGenerics = fns.iter().filter(|(_, f)| bodyNamesGenerics(f, &owners)).map(|(k, _)| k.clone()).collect();
339
+ Tables { fns, recursive, ctors, variants, owners, traits, namesGenerics }
340
+ }
341
+ }
342
+
343
+ impl<'a> Cx<'a> {
344
+ fn new(t: &'a Tables, pure: &'a HashSet<String>) -> Self {
316
- Cx { pure, fns, recursive, ctors, variants, stack: vec![], depth: 0, scope: Scope::default(), owners, bound: HashSet::new(), traits, namesGenerics }
345
+ Cx { pure, t, stack: vec![], depth: 0, scope: Scope::default(), bound: HashSet::new() }
317
346
  }
318
347
 
319
348
  fn isPure(&self, e: &Expr) -> bool {
@@ -336,9 +365,9 @@ impl<'a> Cx<'a> {
336
365
  if self.bound.contains(name) {
337
366
  return None;
338
367
  }
339
- let f = self.fns.get(name)?;
368
+ let f = self.t.fns.get(name)?;
340
369
  let ok = self.pure.contains(name)
341
- && !self.recursive.contains(name)
370
+ && !self.t.recursive.contains(name)
342
371
  && !self.stack.iter().any(|s| s == name)
343
372
  && !f.is_extern
344
373
  && !f.is_fip
@@ -349,7 +378,7 @@ impl<'a> Cx<'a> {
349
378
  && f.params.iter().all(|p| matches!(p.ty, ParamType::Type(_) | ParamType::Fn(..)))
350
379
  && sizeOf(f) <= MAX_SIZE
351
380
  && !self.upcasts(f)
352
- && !self.namesGenerics.contains(name);
381
+ && !self.t.namesGenerics.contains(name);
353
382
  if ok { Some(f) } else { None }
354
383
  }
355
384
 
@@ -360,7 +389,7 @@ impl<'a> Cx<'a> {
360
389
  fn names(t: &Type, traits: &HashSet<String>) -> bool {
361
390
  traits.contains(&t.name) || t.generics.iter().any(|g| names(g, traits))
362
391
  }
363
- let t = &self.traits;
392
+ let t = &self.t.traits;
364
393
  f.returns.as_ref().is_some_and(|r| names(r, t))
365
394
  || f.params.iter().any(|p| match &p.ty {
366
395
  ParamType::Type(x) => names(x, t),
@@ -426,7 +455,7 @@ impl<'a> Cx<'a> {
426
455
  if self.depth >= MAX_DEPTH || self.eligible(&c.name).is_none() {
427
456
  return Expr::FnCall(c);
428
457
  }
429
- let f = self.fns[&c.name].clone();
458
+ let f = self.t.fns[&c.name].clone();
430
459
  match self.instantiate(&f, &c.args, lets.is_some()) {
431
460
  // A body that is a block value is not inlined as an expression (its constructors
432
461
  // cannot be pinned through the statements).
@@ -448,7 +477,7 @@ impl<'a> Cx<'a> {
448
477
  // `f.returns` names the callee's generics, so it is read in the callee's scope.
449
478
  let r = match &f.returns {
450
479
  Some(t) => {
451
- let outer = std::mem::replace(&mut self.scope, Scope::in_(&self.owners, &f));
480
+ let outer = std::mem::replace(&mut self.scope, Scope::in_(&self.t.owners, &f));
452
481
  let pinned = self.pin(r, t, true);
453
482
  self.scope = outer;
454
483
  match pinned {
@@ -475,7 +504,7 @@ impl<'a> Cx<'a> {
475
504
  /// nullary variant, a positional payload, a result type with open generics): the call
476
505
  /// is then not inlined. A constructor whose fields fix its type stays as it is.
477
506
  fn pin(&self, e: Expr, t: &Type, top: bool) -> Option<Expr> {
478
- let generic = |name: &str| self.variants.get(name).is_some_and(|(_, g, _)| !g.is_empty());
507
+ let generic = |name: &str| self.t.variants.get(name).is_some_and(|(_, g, _)| !g.is_empty());
479
508
  let fail = |e: Expr| {
480
509
  let name = match &e.kind {
481
510
  ExprKind::Var(n) | ExprKind::TypeName(n) => n.as_str(),
@@ -497,7 +526,7 @@ impl<'a> Cx<'a> {
497
526
  }
498
527
  ExprKind::Var(ref n) | ExprKind::TypeName(ref n) if generic(n) => fail(e),
499
528
  ExprKind::FnCall(ref c) if generic(&c.name) => {
500
- let names = self.ctors.get(&c.name).cloned().unwrap_or_default();
529
+ let names = self.t.ctors.get(&c.name).cloned().unwrap_or_default();
501
530
  let mut fields = Vec::new();
502
531
  let mut pos = 0;
503
532
  for a in &c.args {
@@ -547,7 +576,7 @@ impl<'a> Cx<'a> {
547
576
  /// A constructor of a generic enum whose field types leave some of the enum's generics
548
577
  /// out (`Err(err: E)` of `Result<T, E>`, nullary `None`): only its context types it.
549
578
  fn contextTyped(&self, name: &str) -> bool {
550
- let Some((_, gens, ftys)) = self.variants.get(name) else { return false };
579
+ let Some((_, gens, ftys)) = self.t.variants.get(name) else { return false };
551
580
  let mut seen = HashSet::new();
552
581
  let sc = Scope::named(gens);
553
582
  ftys.iter().for_each(|t| openGenerics(&sc, t, &mut seen));
@@ -557,12 +586,12 @@ impl<'a> Cx<'a> {
557
586
  /// `c` with `t`'s type arguments and its fields pinned; `None` unless `t` is `c`'s
558
587
  /// enum, fully concrete.
559
588
  fn pinCall(&self, mut c: ClassCall, t: &Type, open: &HashSet<String>) -> Option<Expr> {
560
- let (owner, gens, ftys) = self.variants.get(&c.type_name)?;
589
+ let (owner, gens, ftys) = self.t.variants.get(&c.type_name)?;
561
590
  if owner != &t.name || gens.len() != t.generics.len() || !open.is_empty() {
562
591
  return None;
563
592
  }
564
593
  let sub: HashMap<String, Type> = gens.iter().cloned().zip(t.generics.iter().cloned()).collect();
565
- let names = self.ctors.get(&c.type_name)?;
594
+ let names = self.t.ctors.get(&c.type_name)?;
566
595
  for fa in &mut c.fields {
567
596
  let i = names.iter().position(|n| n == &fa.name)?;
568
597
  let ft = crate::rename::substType(ftys.get(i)?, &sub);
@@ -653,7 +682,7 @@ impl<'a> Cx<'a> {
653
682
  // parameter fixed (`use(Holder.of(lit))`, `Holder<M>` pinned by `use`'s
654
683
  // `Holder<Int>`) keeps it. Not when the type names the callee's generics.
655
684
  let mut gens: Vec<&String> = f.generics.iter().collect();
656
- if let Some(o) = f.type_param.as_ref().and_then(|t| self.owners.get(t)) {
685
+ if let Some(o) = f.type_param.as_ref().and_then(|t| self.t.owners.get(t)) {
657
686
  gens.extend(o.iter());
658
687
  }
659
688
  let ty = match &f.params[i].ty {
@@ -804,13 +833,13 @@ impl<'a> Cx<'a> {
804
833
  /// `(ctor name, field values in declared order)` of a just-built value.
805
834
  fn ctorOf(&self, e: &Expr) -> Option<(String, Vec<Expr>)> {
806
835
  match &e.kind {
807
- ExprKind::TypeName(n) | ExprKind::Var(n) if self.ctors.get(n).is_some_and(|f| f.is_empty()) => {
836
+ ExprKind::TypeName(n) | ExprKind::Var(n) if self.t.ctors.get(n).is_some_and(|f| f.is_empty()) => {
808
837
  Some((n.clone(), vec![]))
809
838
  }
810
839
  // explicit type arguments on a built variant (`pin`) do not hide its fields;
811
840
  // a fieldless `List<Int>()` is an `init` call, not a constructor
812
841
  ExprKind::ClassCall(c) if c.spread.is_none() && (c.generics.is_empty() || !c.fields.is_empty()) => {
813
- let decl = self.ctors.get(&c.type_name)?;
842
+ let decl = self.t.ctors.get(&c.type_name)?;
814
843
  if decl.len() != c.fields.len() {
815
844
  return None;
816
845
  }
@@ -830,7 +859,7 @@ impl<'a> Cx<'a> {
830
859
 
831
860
  fn matchPat(&self, p: &CasePattern, v: &Expr, binds: &mut Vec<(Option<String>, Expr)>) -> M {
832
861
  let asClass = match p {
833
- CasePattern::Name(n) if self.ctors.contains_key(n) => Some((n.as_str(), &[][..])),
862
+ CasePattern::Name(n) if self.t.ctors.contains_key(n) => Some((n.as_str(), &[][..])),
834
863
  CasePattern::Class { name, fields, .. } => Some((name.as_str(), &fields[..])),
835
864
  _ => None,
836
865
  };
@@ -959,7 +988,7 @@ impl<'a> Cx<'a> {
959
988
  return None;
960
989
  }
961
990
  self.eligible(&c.name)?;
962
- let f = self.fns[&c.name].clone();
991
+ let f = self.t.fns[&c.name].clone();
963
992
  let (mut binds, mut body) = self.instantiate(&f, &c.args, true)?;
964
993
  if body.stmts.len() != 1 {
965
994
  return None;