plum

#treesitter#compiler#wasm

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

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


ab2a43a — Peter John 2026-11-10T21:23:21+05:30
Codegen: the wasm passes can be turned off, and a fallback is loud
compiler/wasm-codegen/src/module.rs CHANGED
@@ -22,6 +22,17 @@ pub(crate) enum DataSegmentEntry {
22
22
  Passive(Vec<u8>),
23
23
  }
24
24
 
25
+ /// Set in the environment, `finishOptimized` runs none of the passes in `optimize`.
26
+ pub const NO_WASM_OPT_ENV: &str = "PLUM_NO_WASM_OPT";
27
+
28
+ static OPTIMIZER_FALLBACKS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
29
+
30
+ /// How many modules this process wrote unoptimised because the passes broke them (see
31
+ /// `WasmModule::finishOptimized`): always 0 unless the optimiser has a bug.
32
+ pub fn optimizerFallbacks() -> usize {
33
+ OPTIMIZER_FALLBACKS.load(std::sync::atomic::Ordering::Relaxed)
34
+ }
35
+
25
36
  pub struct WasmModule {
26
37
  pub(crate) types: Vec<TypeEntry>,
27
38
  /// Running count of type-section INDICES assigned so far — NOT the same as
@@ -179,12 +190,14 @@ impl WasmModule {
179
190
  }
180
191
 
181
192
  /// The module's bytes after the passes in `optimize` (with `keepDeadFns`, functions
182
- /// nothing reaches stay, for tests that read a fn the passes inlined everywhere). When the module as built does not
193
+ /// nothing reaches stay, for tests that read a fn the passes inlined everywhere). With
194
+ /// `PLUM_NO_WASM_OPT` set in the environment no pass runs (to compare a program's
195
+ /// behaviour with and without them). When the module as built does not validate, it is
183
- /// validate, it is returned as it is, so the engine reports the error; a pass that
196
+ /// returned as it is, so the engine reports the error. A pass that breaks a valid
184
- /// breaks a valid module is a compiler bug (a panic in debug builds, otherwise the
197
+ /// module is a compiler bug: a panic in debug builds; otherwise a warning on stderr,
185
- /// unoptimised module is used).
198
+ /// a count in `optimizerFallbacks`, and the unoptimised module.
186
199
  pub fn finishOptimized(&mut self, keepDeadFns: bool) -> Vec<u8> {
187
- if crate::optimize::validates(self).is_err() {
200
+ if std::env::var_os(NO_WASM_OPT_ENV).is_some() || crate::optimize::validates(self).is_err() {
188
201
  return self.encode();
189
202
  }
190
203
  let saved = (self.functions.clone(), self.exports.clone(), self.start_function, self.table_elements.clone(), self.func_names.clone());
@@ -194,7 +207,9 @@ impl WasmModule {
194
207
  .and_then(|_| if keepDeadFns { Ok(0) } else { crate::optimize::removeDeadFunctions(self) })
195
208
  .and_then(|_| crate::optimize::validates(self));
196
209
  if let Err(e) = r {
210
+ OPTIMIZER_FALLBACKS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
197
211
  debug_assert!(false, "wasm optimisation produced an invalid module: {e}");
212
+ eprintln!("warning: compiler bug: the wasm passes produced an invalid module ({e}); writing the unoptimised module instead");
198
213
  (self.functions, self.exports, self.start_function, self.table_elements, self.func_names) = saved;
199
214
  self.func_count = self.functions.len() as u32;
200
215
  }
compiler/wasm-codegen/tests/wasm_codegen/optimize_test.rs CHANGED
@@ -183,3 +183,80 @@ fun main() -> Int =
183
183
  assert_eq!(uniq.len(), closures.len(), "{closures:?}");
184
184
  assert_eq!(runInt("closurenames", src), 8);
185
185
  }
186
+
187
+ /// Every `.plum` file under `dir`, recursively, in path order.
188
+ fn plumFiles(dir: &std::path::Path, out: &mut Vec<std::path::PathBuf>) {
189
+ let mut entries: Vec<_> = std::fs::read_dir(dir).unwrap().map(|e| e.unwrap().path()).collect();
190
+ entries.sort();
191
+ for p in entries {
192
+ if p.is_dir() {
193
+ plumFiles(&p, out);
194
+ } else if p.extension().is_some_and(|e| e == "plum") {
195
+ out.push(p);
196
+ }
197
+ }
198
+ }
199
+
200
+ /// The passes never break a module of std, the examples or the tests, in test mode or
201
+ /// as a program: a broken one is a panic in this debug build, and in a release build a
202
+ /// warning, an unoptimised module and a count in `optimizerFallbacks`.
203
+ #[test]
204
+ fn optimizerNeverFallsBackOnTheRepo() {
205
+ let root = plum_test_support::repoRoot();
206
+ let mut files = Vec::new();
207
+ for d in ["std", "examples", "tests"] {
208
+ plumFiles(&root.join(d), &mut files);
209
+ }
210
+ assert!(files.len() > 100, "{} files", files.len());
211
+ let files = std::sync::Arc::new(std::sync::Mutex::new(files));
212
+ let compiled = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
213
+ let workers: Vec<_> = (0..8)
214
+ .map(|_| {
215
+ let (files, compiled, root) = (files.clone(), compiled.clone(), root.clone());
216
+ std::thread::Builder::new()
217
+ .stack_size(256 << 20)
218
+ .spawn(move || loop {
219
+ let Some(f) = files.lock().unwrap().pop() else { break };
220
+ // Files that don't load or check (fixtures of errors) have no module.
221
+ let Ok(src) = plum_core::loadAndMergeDiag(&f, &root) else { continue };
222
+ for tests in [true, false] {
223
+ let opts = plum_wasm_codegen::CompileOptions { tests, ..Default::default() };
224
+ if plum_wasm_codegen::compile(&src, &opts).is_ok() {
225
+ compiled.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
226
+ }
227
+ }
228
+ })
229
+ .unwrap()
230
+ })
231
+ .collect();
232
+ for w in workers {
233
+ w.join().expect("a worker panicked: an optimised module failed to validate");
234
+ }
235
+ assert!(compiled.load(std::sync::atomic::Ordering::Relaxed) > 100);
236
+ assert_eq!(plum_wasm_codegen::optimizerFallbacks(), 0);
237
+ }
238
+
239
+ /// `PLUM_NO_WASM_OPT` turns the passes off: the casts the first pass drops are back.
240
+ #[test]
241
+ fn noWasmOptEnvKeepsTheModuleAsBuilt() {
242
+ let opt = compile("noopt_on", POINT);
243
+ let out = std::process::Command::new(std::env::current_exe().unwrap())
244
+ .args(["--exact", "optimize_test::noWasmOptChild", "--nocapture", "--include-ignored"])
245
+ .env(plum_wasm_codegen::NO_WASM_OPT_ENV, "1")
246
+ .output()
247
+ .unwrap();
248
+ assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stdout));
249
+ let all = bodies(&opt);
250
+ assert!(!body(&all, "total").iter().any(|o| o.starts_with("RefCast")));
251
+ assert!(String::from_utf8_lossy(&out.stdout).contains("unoptimised total has a cast"), "{}", String::from_utf8_lossy(&out.stdout));
252
+ }
253
+
254
+ /// Run by `noWasmOptEnvKeepsTheModuleAsBuilt` in a child process with the env set.
255
+ #[test]
256
+ #[ignore]
257
+ fn noWasmOptChild() {
258
+ assert!(std::env::var_os(plum_wasm_codegen::NO_WASM_OPT_ENV).is_some(), "run by noWasmOptEnvKeepsTheModuleAsBuilt");
259
+ let all = bodies(&compile("noopt_off", POINT));
260
+ assert!(body(&all, "total").iter().any(|o| o.starts_with("RefCast")), "{:?}", body(&all, "total"));
261
+ println!("unoptimised total has a cast");
262
+ }