plum

#treesitter#compiler#wasm

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

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


46ee3ec — Peter John 2026-11-10T11:03:16+05:30
wasm codegen: drop the functions nothing reaches
compiler/cli/src/main.rs CHANGED
@@ -295,7 +295,7 @@ fn compileToTestWasm(
295
295
  // continue to the rest of the directory instead of the whole run
296
296
  // dying on the first file with a type error. Checked once, on the
297
297
  // test-desugared source codegen then compiles.
298
- let out = plum_wasm_codegen::compile(&ast, &plum_wasm_codegen::CompileOptions { tests: true, passes: fusion }).map_err(|ds| anyhow::anyhow!("{}", renderAll(&ds, file)))?;
298
+ let out = plum_wasm_codegen::compile(&ast, &plum_wasm_codegen::CompileOptions { tests: true, passes: fusion, ..Default::default() }).map_err(|ds| anyhow::anyhow!("{}", renderAll(&ds, file)))?;
299
299
  let compiled = (out.wasm, out.test_names);
300
300
  // Debug aid: `PLUM_DUMP_WASM=out.wasm plum test file.plum` keeps the module.
301
301
  if let Some(path) = std::env::var_os("PLUM_DUMP_WASM") {
compiler/cli/src/program.rs CHANGED
@@ -61,7 +61,7 @@ pub fn tryCompileProgram(
61
61
  // the program as written is kept to report errors in the user's own `main`.
62
62
  let written = plum_core::main_result::resultMainReturn(&ast).is_some().then(|| ast.clone());
63
63
  let resultMain = plum_core::main_result::lowerResultMain(&mut ast);
64
- let options = plum_wasm_codegen::CompileOptions { tests: false, passes: fusion };
64
+ let options = plum_wasm_codegen::CompileOptions { tests: false, passes: fusion, ..Default::default() };
65
65
  let out = plum_core::timing::time("compile", || plum_wasm_codegen::compile(&ast, &options)).map_err(|mut ds| {
66
66
  if let Some(written) = &written {
67
67
  // Errors in the user's own `main` are reported under its name, not the renamed one.
compiler/core/tests/core/trmc_test.rs CHANGED
@@ -6,7 +6,8 @@ use plum_driver::PassOptions;
6
6
  use plum_wasm_codegen::CompileOptions;
7
7
 
8
8
  fn compileWith(source: &plum_core::ast::Source, fusion: bool) -> Result<Vec<u8>, String> {
9
+ // `keepDeadFns`: some tests read a fn the passes inlined everywhere.
9
- let opts = CompileOptions { passes: plum_driver::PassOptions { fusion: fusion, explain: false, ..plum_driver::PassOptions::default() }, ..Default::default() };
10
+ let opts = CompileOptions { passes: plum_driver::PassOptions { fusion: fusion, explain: false, ..plum_driver::PassOptions::default() }, keepDeadFns: true, ..Default::default() };
10
11
  plum_wasm_codegen::compile(source, &opts)
11
12
  .map(|o| o.wasm)
12
13
  .map_err(|ds| ds.iter().map(|d| d.to_string()).collect::<Vec<_>>().join("\n"))
compiler/wasm-codegen/src/emit.rs CHANGED
@@ -253,9 +253,9 @@ impl<'a> Emit<'a> {
253
253
  }
254
254
  }
255
255
 
256
- /// The module bytes and the sorted function keys.
256
+ /// The module and the sorted function keys.
257
- pub(crate) fn finish(self) -> Result<(Vec<u8>, Vec<String>), String> {
257
+ pub(crate) fn finish(self) -> Result<(WasmModule, Vec<String>), String> {
258
- let Emit { mut module, ctx, units, .. } = self;
258
+ let Emit { module, ctx, units, .. } = self;
259
259
  let mut fn_keys: Vec<String> = ctx
260
260
  .func_ids
261
261
  .keys()
@@ -269,6 +269,6 @@ impl<'a> Emit<'a> {
269
269
  .map(|u| u.name.clone()),
270
270
  );
271
271
  fn_keys.sort();
272
- Ok((module.finishOptimized(), fn_keys))
272
+ Ok((module, fn_keys))
273
273
  }
274
274
  }
compiler/wasm-codegen/src/lib.rs CHANGED
@@ -63,11 +63,15 @@ pub struct CompileOptions {
63
63
  pub tests: bool,
64
64
  /// Which rewrite passes run (`--no-fusion`, `--explain-fusion`).
65
65
  pub passes: plum_driver::PassOptions,
66
+ /// Keep the functions nothing in the module reaches (normally dropped after codegen;
67
+ /// see `optimize::removeDeadFunctions`): for tests that read a fn's body by name after
68
+ /// the passes inlined every call to it.
69
+ pub keepDeadFns: bool,
66
70
  }
67
71
 
68
72
  impl Default for CompileOptions {
69
73
  fn default() -> Self {
70
- CompileOptions { tests: false, passes: plum_driver::PassOptions::default() }
74
+ CompileOptions { tests: false, passes: plum_driver::PassOptions::default(), keepDeadFns: false }
71
75
  }
72
76
  }
73
77
 
@@ -110,11 +114,13 @@ pub fn compile(source: &ast::Source, opts: &CompileOptions) -> Result<Output, Ve
110
114
  let typed = plum_driver::check(&prog.source, &opts.passes)?;
111
115
  let mut extra = prog.extraExports.clone();
112
116
  extra.extend(gameExports(game));
113
- let (wasm, fn_keys) = compileSourceInner(&prog.source, &extra, typed).map_err(codegenDiag)?;
117
+ let (mut module, fn_keys) = compileSourceInner(&prog.source, &extra, typed).map_err(codegenDiag)?;
118
+ let wasm = module.finishOptimized(opts.keepDeadFns);
114
119
  Ok(Output { wasm, fn_keys, test_names: prog.names, isGame: game })
115
120
  } else {
116
121
  let typed = plum_core::timing::time("check + passes", || plum_driver::check(source, &opts.passes))?;
117
- let (wasm, fn_keys) = plum_core::timing::time("codegen", || compileSourceInner(source, &gameExports(game), typed)).map_err(codegenDiag)?;
122
+ let (mut module, fn_keys) = plum_core::timing::time("codegen", || compileSourceInner(source, &gameExports(game), typed)).map_err(codegenDiag)?;
123
+ let wasm = plum_core::timing::time("wasm passes", || module.finishOptimized(opts.keepDeadFns));
118
124
  Ok(Output { wasm, fn_keys, test_names: Vec::new(), isGame: game })
119
125
  }
120
126
  }
@@ -176,7 +182,7 @@ mod compileEntryTests {
176
182
  typed.inst_expr_types.clear();
177
183
  typed.annotated.clear();
178
184
  let r = compileSourceInner(&src, &[], typed);
179
- let msg = r.expect_err("no types");
185
+ let Err(msg) = r else { panic!("no types") };
180
186
  assert!(msg.contains("no type recorded"), "{msg}");
181
187
  }
182
188
 
@@ -192,7 +198,7 @@ fn compileSourceInner(
192
198
  source: &ast::Source,
193
199
  extra_exports: &[(String, String)],
194
200
  typed: plum_checker::TypedInfo,
195
- ) -> Result<(Vec<u8>, Vec<String>), String> {
201
+ ) -> Result<(WasmModule, Vec<String>), String> {
196
202
  let r = compileSourceUnits(source, extra_exports, typed);
197
203
  // A missing-type note is the root cause of any error after it: codegen carries on past it
198
204
  // with `Unit`, and the follow-on error describes that `Unit`, not the program.
@@ -206,7 +212,7 @@ fn compileSourceUnits(
206
212
  source: &ast::Source,
207
213
  extra_exports: &[(String, String)],
208
214
  mut typed: plum_checker::TypedInfo,
209
- ) -> Result<(Vec<u8>, Vec<String>), String> {
215
+ ) -> Result<(WasmModule, Vec<String>), String> {
210
216
  let lowered = typed.lowered.take();
211
217
  resetGenState(source);
212
218
  // The types are keyed by the node ids of the checker's lowered program.
compiler/wasm-codegen/src/module.rs CHANGED
@@ -168,19 +168,23 @@ impl WasmModule {
168
168
  self.encode()
169
169
  }
170
170
 
171
- /// The module's bytes after the passes in `optimize`. When the module as built does not
171
+ /// The module's bytes after the passes in `optimize` (with `keepDeadFns`, functions
172
+ /// nothing reaches stay, for tests that read a fn the passes inlined everywhere). When the module as built does not
172
173
  /// validate, it is returned as it is, so the engine reports the error; a pass that
173
174
  /// breaks a valid module is a compiler bug (a panic in debug builds, otherwise the
174
175
  /// unoptimised module is used).
175
- pub fn finishOptimized(&mut self) -> Vec<u8> {
176
+ pub fn finishOptimized(&mut self, keepDeadFns: bool) -> Vec<u8> {
176
177
  if crate::optimize::validates(self).is_err() {
177
178
  return self.encode();
178
179
  }
179
- let saved = self.functions.clone();
180
+ let saved = (self.functions.clone(), self.exports.clone(), self.start_function, self.table_elements.clone(), self.func_names.clone());
180
- let r = crate::optimize::removeRedundantCasts(self).and_then(|_| crate::optimize::validates(self));
181
+ let r = crate::optimize::removeRedundantCasts(self)
182
+ .and_then(|_| if keepDeadFns { Ok(0) } else { crate::optimize::removeDeadFunctions(self) })
183
+ .and_then(|_| crate::optimize::validates(self));
181
184
  if let Err(e) = r {
182
185
  debug_assert!(false, "wasm optimisation produced an invalid module: {e}");
186
+ (self.functions, self.exports, self.start_function, self.table_elements, self.func_names) = saved;
183
- self.functions = saved;
187
+ self.func_count = self.functions.len() as u32;
184
188
  }
185
189
  self.encode()
186
190
  }
compiler/wasm-codegen/src/optimize.rs CHANGED
@@ -121,3 +121,93 @@ pub(crate) fn removeRedundantCasts(module: &mut WasmModule) -> Result<usize, Str
121
121
  pub(crate) fn validates(module: &WasmModule) -> Result<(), String> {
122
122
  walk(&module.encode(), |_, _, _, _, _| {})
123
123
  }
124
+
125
+ /// Drops every defined function that no export, the start function, the table or a
126
+ /// reachable function's `call`/`return_call`/`ref.func` can reach, renumbering the rest
127
+ /// (bodies, exports, start, table, names). Codegen emits every unit and every helper it
128
+ /// may need up front; this keeps only the ones the program uses. Imports stay as they are.
129
+ /// Returns the number of functions removed.
130
+ pub(crate) fn removeDeadFunctions(module: &mut WasmModule) -> Result<usize, String> {
131
+ // A global initialiser naming a function would be another root to renumber: codegen
132
+ // never writes one, so such a module is left alone.
133
+ for (_, _, init) in &module.globals {
134
+ let mut r = wasmparser::BinaryReader::new(init, 0);
135
+ while !r.eof() {
136
+ match r.read_operator() {
137
+ Ok(Operator::RefFunc { .. }) | Err(_) => return Ok(0),
138
+ Ok(_) => {}
139
+ }
140
+ }
141
+ }
142
+ let bytes = module.encode();
143
+ let imports = module.func_import_count;
144
+ let n = module.functions.len();
145
+ // Per defined function: (named function, op start, op end, opcode byte).
146
+ let mut refs: Vec<Vec<(u32, usize, usize, u8)>> = vec![Vec::new(); n];
147
+ walk(&bytes, |fn_i, _, op, start, end| match op {
148
+ Operator::Call { function_index } => refs[fn_i].push((*function_index, start, end, 0x10)),
149
+ Operator::ReturnCall { function_index } => refs[fn_i].push((*function_index, start, end, 0x12)),
150
+ Operator::RefFunc { function_index } => refs[fn_i].push((*function_index, start, end, 0xD2)),
151
+ _ => {}
152
+ })?;
153
+ let mut live = vec![false; n];
154
+ let mut stack: Vec<u32> = module
155
+ .exports
156
+ .iter()
157
+ .filter(|(_, k, _)| *k == wasm_encoder::ExportKind::Func)
158
+ .map(|(_, _, i)| *i)
159
+ .chain(module.start_function)
160
+ .chain(module.table_elements.iter().copied())
161
+ .collect();
162
+ while let Some(f) = stack.pop() {
163
+ let Some(d) = f.checked_sub(imports).map(|d| d as usize) else { continue };
164
+ if d >= n || live[d] {
165
+ continue;
166
+ }
167
+ live[d] = true;
168
+ stack.extend(refs[d].iter().map(|r| r.0));
169
+ }
170
+ let removed = live.iter().filter(|l| !**l).count();
171
+ if removed == 0 {
172
+ return Ok(0);
173
+ }
174
+ let mut new_idx = vec![u32::MAX; n];
175
+ let mut next = imports;
176
+ for d in 0..n {
177
+ if live[d] {
178
+ new_idx[d] = next;
179
+ next += 1;
180
+ }
181
+ }
182
+ let remap = |f: u32| if f < imports { f } else { new_idx[(f - imports) as usize] };
183
+ let old = std::mem::take(&mut module.functions);
184
+ for (d, (ty, body)) in old.into_iter().enumerate() {
185
+ if !live[d] {
186
+ continue;
187
+ }
188
+ let edits: Vec<Edit> = refs[d]
189
+ .iter()
190
+ .map(|&(f, start, end, opcode)| {
191
+ let mut with = vec![opcode];
192
+ wasm_encoder::Encode::encode(&remap(f), &mut with);
193
+ Edit { start, end, with }
194
+ })
195
+ .collect();
196
+ module.functions.push((ty, applyEdits(&body, &edits)));
197
+ }
198
+ module.func_count = module.functions.len() as u32;
199
+ for (_, k, i) in module.exports.iter_mut() {
200
+ if *k == wasm_encoder::ExportKind::Func {
201
+ *i = remap(*i);
202
+ }
203
+ }
204
+ module.start_function = module.start_function.map(remap);
205
+ for e in module.table_elements.iter_mut() {
206
+ *e = remap(*e);
207
+ }
208
+ module.func_names.retain(|(i, _)| *i < imports || live.get((*i - imports) as usize).copied().unwrap_or(false));
209
+ for (i, _) in module.func_names.iter_mut() {
210
+ *i = remap(*i);
211
+ }
212
+ Ok(removed)
213
+ }
compiler/wasm-codegen/tests/wasm_codegen/codegen_tests.rs CHANGED
@@ -2132,7 +2132,8 @@ fun main() -> Int =
2132
2132
  /// short function name is shown as `fn.g` in the name section.
2133
2133
  #[test]
2134
2134
  fn short_function_names_get_a_prefix() {
2135
+ // Recursive, so the passes keep the call and `g` is in the module.
2135
- let src = "import std/Int\n\nfun g(n: Int) -> Int =\n n + 1\n\nfun main() -> Int =\n g(5)\n";
2136
+ let src = "import std/Int\n\nfun g(n: Int) -> Int =\n if n == 0 then 1 else g(n - 1) + 1\n\nfun main() -> Int =\n g(5)\n";
2136
2137
  let (r, _) = runWithCrash("shortname", src);
2137
2138
  assert_eq!(r, Ok(6));
2138
2139
  let dir = std::env::temp_dir().join(format!("plum_shortname_{}", std::process::id()));
compiler/wasm-codegen/tests/wasm_codegen/e2e_mem/reuse.rs CHANGED
@@ -37,6 +37,8 @@ fn structNewCountWith(name: &str, src: &str, reuse: bool, fusion: bool) -> usize
37
37
  let source = load(name, src, reuse).expect("load");
38
38
  let opts = plum_wasm_codegen::CompileOptions {
39
39
  passes: plum_driver::PassOptions { fusion: fusion, explain: false, ..plum_driver::PassOptions::default() },
40
+ // `main2`'s rebuild is counted though nothing calls it.
41
+ keepDeadFns: true,
40
42
  ..Default::default()
41
43
  };
42
44
  let bytes = plum_wasm_codegen::compile(&source, &opts)
compiler/wasm-codegen/tests/wasm_codegen/native_test.rs CHANGED
@@ -53,6 +53,8 @@ fn compile(name: &str, src: &str, fbip: bool) -> Vec<u8> {
53
53
  let source = plum_test_support::load(name, src).unwrap_or_else(|e| panic!("load: {e}"));
54
54
  let opts = plum_wasm_codegen::CompileOptions {
55
55
  passes: plum_driver::PassOptions { fbip, explain: false, ..plum_driver::PassOptions::default() },
56
+ // The fns read below are inlined into `main` by the passes.
57
+ keepDeadFns: true,
56
58
  ..Default::default()
57
59
  };
58
60
  let bytes = plum_wasm_codegen::compile(&source, &opts)
compiler/wasm-codegen/tests/wasm_codegen/optimize_test.rs CHANGED
@@ -47,11 +47,11 @@ import std/Str
47
47
 
48
48
  struct Point(x: Int, y: Int, label: Str)
49
49
 
50
- fun total(p: Point) -> Int =
50
+ fun total(p: Point, n: Int) -> Int =
51
- p.x + p.y
51
+ if n == 0 then p.x + p.y else total(p, n - 1)
52
52
 
53
53
  fun main() -> Int =
54
- total(Point(x: 3, y: 4, label: \"p\"))
54
+ total(Point(x: 3, y: 4, label: \"p\"), 3)
55
55
  ";
56
56
 
57
57
  /// Reading a field of a struct-typed parameter needs no cast: the parameter already has
@@ -88,3 +88,30 @@ fun main() -> Int =
88
88
  assert!(ops.iter().any(|o| o.starts_with("RefCast") || o.starts_with("BrOnCast")), "{ops:?}");
89
89
  assert_eq!(runInt("variantcast", src), 13);
90
90
  }
91
+
92
+ /// A function nothing reaches is not in the module; the ones a closure (the table) or
93
+ /// a call reaches are, renumbered, and still run.
94
+ #[test]
95
+ fn unreachableFunctionsAreDropped() {
96
+ let src = "\
97
+ import std/Int
98
+
99
+ fun neverCalled(n: Int) -> Int =
100
+ n * 1000
101
+
102
+ fun twice(f: fn(Int) -> Int, n: Int) -> Int =
103
+ f(f(n))
104
+
105
+ fun bump(n: Int) -> Int =
106
+ n + 1
107
+
108
+ fun main() -> Int =
109
+ k := 10
110
+ twice(|n| n + k, 1) + twice(bump, 0)
111
+ ";
112
+ let all = bodies(&compile("deadfns", src));
113
+ let names: Vec<&str> = all.iter().map(|b| b.0.as_str()).collect();
114
+ assert!(!names.contains(&"neverCalled"), "{names:?}");
115
+ assert!(names.iter().any(|n| n.starts_with("twice")), "{names:?}");
116
+ assert_eq!(runInt("deadfns", src), 23);
117
+ }