plum

#treesitter#compiler#wasm

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

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


de47c34 — Peter John 2026-11-10T10:31:23+05:30
plum test: a test that never ends fails as timed out, by name
compiler/cli/src/main.rs CHANGED
@@ -129,6 +129,9 @@ enum Command {
129
129
  /// Root directory `import <path>` is resolved against (`import std/x` -> `<lib-path>/std/x.plum`)
130
130
  #[arg(long, default_value = ".")]
131
131
  lib_path: std::path::PathBuf,
132
+ /// Seconds one test may run before it fails as timed out (default: `PLUM_TEST_TIMEOUT`, else 60; 0 = no limit)
133
+ #[arg(long)]
134
+ timeout: Option<f64>,
132
135
  },
133
136
  /// Install Plum syntax highlighting into an editor's configuration
134
137
  Editor {
@@ -192,8 +195,8 @@ fn run() -> Result<()> {
192
195
  Command::Build { file, output, lib_path, assets, explain_fusion, no_fusion, no_fbip } => {
193
196
  cmdBuild(file, lib_path, fusionFlags(explain_fusion, no_fusion, no_fbip), GameOptions { assets, port: None, noOpen: false, noWatch: false, output, replay: None })
194
197
  }
195
- Command::Test { paths, lib_path, explain_fusion, no_fusion, no_fbip } => {
198
+ Command::Test { paths, lib_path, explain_fusion, no_fusion, no_fbip, timeout } => {
196
- cmdTest(paths, lib_path, fusionFlags(explain_fusion, no_fusion, no_fbip))
199
+ cmdTest(paths, lib_path, fusionFlags(explain_fusion, no_fusion, no_fbip), testTimeout(timeout)?)
197
200
  }
198
201
  Command::Editor { editor, insiders } => editor::install(editor, insiders),
199
202
  }
@@ -418,10 +421,30 @@ fn collectPlumFiles(path: &std::path::Path) -> Result<Vec<std::path::PathBuf>> {
418
421
  Ok(files)
419
422
  }
420
423
 
424
+ /// How long one test may run: `--timeout`, else `PLUM_TEST_TIMEOUT`, else 60 seconds.
425
+ /// `None` (a limit of 0) means no limit.
426
+ fn testTimeout(flag: Option<f64>) -> Result<Option<std::time::Duration>> {
427
+ let secs = match flag {
428
+ Some(s) => s,
429
+ None => match std::env::var("PLUM_TEST_TIMEOUT") {
430
+ Ok(v) => v.trim().parse::<f64>().map_err(|_| anyhow::anyhow!("PLUM_TEST_TIMEOUT={v} is not a number of seconds"))?,
431
+ Err(_) => 60.0,
432
+ },
433
+ };
434
+ if !(secs >= 0.0 && secs.is_finite()) {
435
+ anyhow::bail!("the test timeout must be a number of seconds, 0 or more (got {secs})");
436
+ }
437
+ Ok((secs > 0.0).then(|| std::time::Duration::from_secs_f64(secs)))
438
+ }
439
+
440
+ /// The epoch tick of `plum test`'s engine: a test's deadline is counted in these.
441
+ const TEST_TICK: std::time::Duration = std::time::Duration::from_millis(50);
442
+
421
443
  fn cmdTest(
422
444
  paths: Vec<std::path::PathBuf>,
423
445
  lib_path: std::path::PathBuf,
424
446
  fusion: plum_driver::PassOptions,
447
+ timeout: Option<std::time::Duration>,
425
448
  ) -> Result<()> {
426
449
  // A single plain file keeps the exact original single-file UX (no
427
450
  // `=== path ===` header, no aggregate summary line, no "N/1 files
@@ -430,7 +453,7 @@ fn cmdTest(
430
453
  // matching `scripts/test-plum.sh`'s old find-and-loop shell logic.
431
454
  if let [only] = paths.as_slice() {
432
455
  if only.is_file() {
433
- let (passed, failed) = runTestFile(only, &lib_path, fusion)?;
456
+ let (passed, failed) = runTestFile(only, &lib_path, fusion, timeout)?;
434
457
  // A sweep's worker (see `runSweepParallel`) reads the counts from this line.
435
458
  if std::env::var_os(TEST_CHILD_ENV).is_some() {
436
459
  println!("{COUNTS_MARK}{passed} {failed}");
@@ -451,11 +474,11 @@ fn cmdTest(
451
474
  let mut files_failed = 0usize;
452
475
  let jobs = testJobs();
453
476
  if jobs > 1 && files.len() > 1 {
454
- (total_passed, total_failed, files_failed) = runSweepParallel(&files, &lib_path, fusion, jobs)?;
477
+ (total_passed, total_failed, files_failed) = runSweepParallel(&files, &lib_path, fusion, timeout, jobs)?;
455
478
  } else {
456
479
  for file in &files {
457
480
  println!("=== {} ===", file.display());
458
- match runTestFile(file, &lib_path, fusion) {
481
+ match runTestFile(file, &lib_path, fusion, timeout) {
459
482
  Ok((passed, failed)) => {
460
483
  total_passed += passed;
461
484
  total_failed += failed;
@@ -532,6 +555,7 @@ fn runSweepParallel(
532
555
  files: &[std::path::PathBuf],
533
556
  lib_path: &std::path::Path,
534
557
  fusion: plum_driver::PassOptions,
558
+ timeout: Option<std::time::Duration>,
535
559
  jobs: usize,
536
560
  ) -> Result<(usize, usize, usize)> {
537
561
  use std::io::Write;
@@ -539,7 +563,7 @@ fn runSweepParallel(
539
563
  let exe = std::env::current_exe().context("cannot find the plum executable")?;
540
564
  let color = useColor();
541
565
  let next = AtomicUsize::new(0);
542
- let (tx, rx) = std::sync::mpsc::channel::<(usize, std::io::Result<process::Output>)>();
566
+ let (tx, rx) = std::sync::mpsc::channel::<(usize, std::io::Result<(process::Output, Option<std::time::Duration>)>)>();
543
567
  let (mut passed, mut failed, mut filesFailed) = (0usize, 0usize, 0usize);
544
568
  std::thread::scope(|scope| {
545
569
  for _ in 0..jobs.min(files.len()) {
@@ -559,17 +583,21 @@ fn runSweepParallel(
559
583
  if fusion.explain {
560
584
  cmd.arg("--explain-fusion");
561
585
  }
586
+ cmd.arg("--timeout").arg(timeout.map_or(0.0, |t| t.as_secs_f64()).to_string());
562
587
  cmd.arg(file).env(TEST_CHILD_ENV, "1").stdin(process::Stdio::null());
563
588
  if color {
564
589
  cmd.env(TEST_COLOR_ENV, "1");
565
590
  }
591
+ // Each test has its own deadline inside the child; this one catches a file
592
+ // that hangs outside its tests (in the compiler, say).
593
+ let fileLimit = timeout.map(|t| (t * 5).max(std::time::Duration::from_secs(300)));
566
- if tx.send((i, cmd.output())).is_err() {
594
+ if tx.send((i, outputWithin(cmd, fileLimit))).is_err() {
567
595
  break;
568
596
  }
569
597
  });
570
598
  }
571
599
  drop(tx);
572
- let mut done: Vec<Option<std::io::Result<process::Output>>> = (0..files.len()).map(|_| None).collect();
600
+ let mut done: Vec<Option<std::io::Result<(process::Output, Option<std::time::Duration>)>>> = (0..files.len()).map(|_| None).collect();
573
601
  let mut shown = 0;
574
602
  let (out, err) = (io::stdout(), io::stderr());
575
603
  for (i, r) in rx {
@@ -578,7 +606,10 @@ fn runSweepParallel(
578
606
  let (mut out, mut err) = (out.lock(), err.lock());
579
607
  let _ = writeln!(out, "=== {} ===", files[shown].display());
580
608
  match r {
581
- Ok(o) => {
609
+ Ok((o, timedOut)) => {
610
+ if let Some(limit) = timedOut {
611
+ let _ = writeln!(err, "error: {} timed out: still running after {} s, killed", files[shown].display(), limit.as_secs());
612
+ }
582
613
  let text = String::from_utf8_lossy(&o.stdout);
583
614
  let mut counts = None;
584
615
  for line in text.lines() {
@@ -618,6 +649,43 @@ fn runSweepParallel(
618
649
  Ok((passed, failed, filesFailed))
619
650
  }
620
651
 
652
+ /// Runs `cmd` to the end like `Command::output`, but kills it once it runs past `limit`;
653
+ /// the second value is then `Some(limit)`.
654
+ fn outputWithin(
655
+ mut cmd: process::Command,
656
+ limit: Option<std::time::Duration>,
657
+ ) -> std::io::Result<(process::Output, Option<std::time::Duration>)> {
658
+ let Some(limit) = limit else { return cmd.output().map(|o| (o, None)) };
659
+ let mut child = cmd.stdout(process::Stdio::piped()).stderr(process::Stdio::piped()).spawn()?;
660
+ let readAll = |r: Option<Box<dyn Read + Send>>| {
661
+ std::thread::spawn(move || {
662
+ let mut buf = Vec::new();
663
+ if let Some(mut r) = r {
664
+ let _ = r.read_to_end(&mut buf);
665
+ }
666
+ buf
667
+ })
668
+ };
669
+ let out = readAll(child.stdout.take().map(|s| Box::new(s) as Box<dyn Read + Send>));
670
+ let err = readAll(child.stderr.take().map(|s| Box::new(s) as Box<dyn Read + Send>));
671
+ let deadline = std::time::Instant::now() + limit;
672
+ let mut timedOut = None;
673
+ let status = loop {
674
+ if let Some(status) = child.try_wait()? {
675
+ break status;
676
+ }
677
+ if std::time::Instant::now() >= deadline {
678
+ let _ = child.kill();
679
+ timedOut = Some(limit);
680
+ break child.wait()?;
681
+ }
682
+ std::thread::sleep(std::time::Duration::from_millis(20));
683
+ };
684
+ let stdout = out.join().unwrap_or_default();
685
+ let stderr = err.join().unwrap_or_default();
686
+ Ok((process::Output { status, stdout, stderr }, timedOut))
687
+ }
688
+
621
689
  /// Runs every `test` block in one file, printing the Spock-flavored per-test
622
690
  /// tree as it goes, and returns `(passed, failed)` counts — shared by both
623
691
  /// the single-file and directory-recursive paths of `cmdTest`.
@@ -625,17 +693,21 @@ fn runTestFile(
625
693
  file: &std::path::Path,
626
694
  lib_path: &std::path::Path,
627
695
  fusion: plum_driver::PassOptions,
696
+ timeout: Option<std::time::Duration>,
628
697
  ) -> Result<(usize, usize)> {
629
698
  let (wasm_bytes, names) = compileToTestWasm(file, lib_path, fusion)?;
630
699
  if let Ok(path) = std::env::var("PLUM_DUMP_WASM") {
631
700
  let _ = std::fs::write(path, &wasm_bytes);
632
701
  }
633
702
 
634
- let engine = plum_host::engine();
703
+ let engine = plum_host::engineWithTicker(TEST_TICK);
704
+ // The deadline, in ticks, set afresh before each test (and before instantiation).
705
+ let ticks = timeout.map_or(u64::MAX, |t| (t.as_millis() / TEST_TICK.as_millis()).max(1) as u64);
635
706
 
636
707
  let module = wasmtime::Module::new(&engine, &wasm_bytes)
637
708
  .map_err(|e| anyhow::anyhow!("compiled wasm failed to load: {e:#}"))?;
638
709
  let mut store = wasmtime::Store::new(&engine, ());
710
+ store.set_epoch_deadline(ticks);
639
711
  let imports = plum_host::hostImports(&mut store, &module, plum_host::Caps::all())?;
640
712
  let instance = wasmtime::Instance::new(&mut store, &module, &imports)
641
713
  .map_err(|e| anyhow::anyhow!("module failed to instantiate: {e}"))?;
@@ -687,6 +759,7 @@ fn runTestFile(
687
759
  .get_func(&mut store, &export_name)
688
760
  .ok_or_else(|| anyhow::anyhow!("internal error: missing export '{export_name}'"))?;
689
761
  let mut results = [wasmtime::Val::I32(0)];
762
+ store.set_epoch_deadline(ticks);
690
763
  match test_fn.call(&mut store, &[], &mut results) {
691
764
  Ok(()) => {
692
765
  let report = readStrResult(&mut store, &results[0])?;
@@ -701,6 +774,11 @@ fn runTestFile(
701
774
  failed += 1;
702
775
  }
703
776
  }
777
+ Err(trap) if trap.downcast_ref::<wasmtime::Trap>() == Some(&wasmtime::Trap::Interrupt) => {
778
+ let secs = timeout.map_or(0.0, |t| t.as_secs_f64());
779
+ println!("{branch} {name} {} TIMEOUT: still running after {secs} s (raise it with --timeout or PLUM_TEST_TIMEOUT)", red("\u{2718}"));
780
+ failed += 1;
781
+ }
704
782
  Err(trap) => {
705
783
  println!("{branch} {name} {} PANIC: {}", red("\u{2718}"), plum_core::diag::sourceName(&format!("{trap:#}")));
706
784
  failed += 1;
compiler/cli/tests/cli/common.rs ADDED
@@ -0,0 +1,61 @@
1
+ //! Helpers shared by the CLI tests.
2
+ #![allow(dead_code)]
3
+
4
+ use std::path::{Path, PathBuf};
5
+
6
+ /// The `plum` binary cargo built beside this test executable.
7
+ pub fn plumBin() -> PathBuf {
8
+ let mut path = std::env::current_exe().unwrap();
9
+ path.pop();
10
+ if path.ends_with("deps") {
11
+ path.pop();
12
+ }
13
+ path.push("plum");
14
+ path
15
+ }
16
+
17
+ /// The repository root (imports such as `std/Int` resolve against it).
18
+ pub fn root() -> PathBuf {
19
+ Path::new(env!("CARGO_MANIFEST_DIR")).ancestors().nth(2).unwrap().to_path_buf()
20
+ }
21
+
22
+ /// A fresh scratch folder, deleted when dropped (also when the test panics).
23
+ pub struct Scratch(PathBuf);
24
+
25
+ impl Scratch {
26
+ /// A folder under the system temp folder, named after `name` and this process.
27
+ pub fn new(name: &str) -> Scratch {
28
+ Scratch::at(std::env::temp_dir().join(format!("plum_{name}_{}", std::process::id())))
29
+ }
30
+
31
+ /// The folder `dir`, emptied first.
32
+ pub fn at(dir: PathBuf) -> Scratch {
33
+ let _ = std::fs::remove_dir_all(&dir);
34
+ std::fs::create_dir_all(&dir).unwrap();
35
+ Scratch(dir)
36
+ }
37
+
38
+ pub fn path(&self) -> &Path {
39
+ &self.0
40
+ }
41
+
42
+ pub fn join(&self, p: impl AsRef<Path>) -> PathBuf {
43
+ self.0.join(p)
44
+ }
45
+ }
46
+
47
+ impl Drop for Scratch {
48
+ fn drop(&mut self) {
49
+ let _ = std::fs::remove_dir_all(&self.0);
50
+ }
51
+ }
52
+
53
+ /// A child process killed (and reaped) when dropped, on every path.
54
+ pub struct KillOnDrop(pub std::process::Child);
55
+
56
+ impl Drop for KillOnDrop {
57
+ fn drop(&mut self) {
58
+ let _ = self.0.kill();
59
+ let _ = self.0.wait();
60
+ }
61
+ }
compiler/cli/tests/cli/main.rs CHANGED
@@ -1,5 +1,6 @@
1
1
  #![allow(non_snake_case)]
2
2
  //! Single integration-test binary for plum-cli (one link instead of one per file).
3
+ mod common;
3
4
  mod args_clock_test;
4
5
  mod assert_once_test;
5
6
  mod compile_tests;
@@ -14,3 +15,4 @@ mod no_fbip_test;
14
15
  mod old_forms_test;
15
16
  mod replay_test;
16
17
  mod test_scope_test;
18
+ mod timeout_test;
compiler/cli/tests/cli/timeout_test.rs ADDED
@@ -0,0 +1,34 @@
1
+ use crate::common::{plumBin, root, Scratch};
2
+ use std::process::Command;
3
+
4
+ const HANG: &str = "import std/Int\nimport std/Bool\n\nfun spin(n: Int) -> Int =\n if n < 0 then 0 else spin(n + 1)\n\ntest \"fast\"\n assert 1 == 1\n\ntest \"forever\"\n assert spin(1) == 0\n\ntest \"after\"\n assert 2 == 2\n";
5
+
6
+ /// A test that never ends fails as timed out, by name, and the tests after it still run.
7
+ #[test]
8
+ fn aTestThatNeverEndsTimesOut() {
9
+ let dir = Scratch::new("timeout");
10
+ std::fs::write(dir.join("hang.plum"), HANG).unwrap();
11
+ std::fs::write(dir.join("ok.plum"), "import std/Int\n\ntest \"ok\"\n assert 1 == 1\n").unwrap();
12
+ // One file in-process (`--timeout`), and a sweep of the folder (`PLUM_TEST_TIMEOUT`).
13
+ for (args, env) in [(vec!["--timeout", "0.5", "hang.plum"], None), (vec!["."], Some("0.5"))] {
14
+ let mut cmd = Command::new(plumBin());
15
+ cmd.current_dir(dir.path()).arg("test").arg("--lib-path").arg(root()).args(&args);
16
+ if let Some(t) = env {
17
+ cmd.env("PLUM_TEST_TIMEOUT", t);
18
+ }
19
+ let start = std::time::Instant::now();
20
+ let out = cmd.output().unwrap();
21
+ let text = String::from_utf8_lossy(&out.stdout);
22
+ assert!(!out.status.success(), "{args:?}: {text}");
23
+ assert!(text.contains("forever \u{2718} TIMEOUT"), "{args:?}: {text}");
24
+ assert!(text.contains("after \u{2714}"), "{args:?}: {text}");
25
+ assert!(start.elapsed() < std::time::Duration::from_secs(60), "{args:?}");
26
+ }
27
+ }
28
+
29
+ #[test]
30
+ fn aBadTimeoutIsRejected() {
31
+ let out = Command::new(plumBin()).current_dir(root()).args(["test", "--timeout=-1", "tests/tail_calls.plum"]).output().unwrap();
32
+ assert!(!out.status.success());
33
+ assert!(String::from_utf8_lossy(&out.stderr).contains("timeout"));
34
+ }
compiler/host/src/lib.rs CHANGED
@@ -23,6 +23,29 @@ impl Caps {
23
23
 
24
24
  /// The engine every Plum host uses: GC, typed function refs, tail calls, 64 MiB initial GC heap.
25
25
  pub fn engine() -> wasmtime::Engine {
26
+ wasmtime::Engine::new(&engineConfig()).expect("failed to construct wasmtime engine")
27
+ }
28
+
29
+ /// `engine()` with epoch interruption on: a store traps with `Trap::Interrupt` once the
30
+ /// engine's epoch passes its deadline (`Store::set_epoch_deadline`). `plum test` uses it
31
+ /// to stop a test that never ends; a separate thread ticks the epoch every `tick`.
32
+ pub fn engineWithTicker(tick: std::time::Duration) -> wasmtime::Engine {
33
+ let mut config = engineConfig();
34
+ config.epoch_interruption(true);
35
+ let engine = wasmtime::Engine::new(&config).expect("failed to construct wasmtime engine");
36
+ let ticked = engine.weak();
37
+ std::thread::spawn(move || loop {
38
+ std::thread::sleep(tick);
39
+ match ticked.upgrade() {
40
+ Some(e) => e.increment_epoch(),
41
+ None => break,
42
+ }
43
+ });
44
+ engine
45
+ }
46
+
47
+ /// The configuration behind `engine()`.
48
+ pub fn engineConfig() -> wasmtime::Config {
26
49
  let mut config = wasmtime::Config::new();
27
50
  config.wasm_gc(true);
28
51
  config.wasm_function_references(true);
@@ -32,7 +55,7 @@ pub fn engine() -> wasmtime::Engine {
32
55
  // skip the early full-heap copies of each doubling growth (docs/plans/2026-11-03-gc-report.md).
33
56
  config.gc_heap_initial_size(64 << 20);
34
57
  config.async_stack_size(8 << 20);
35
- wasmtime::Engine::new(&config).expect("failed to construct wasmtime engine")
58
+ config
36
59
  }
37
60
 
38
61
  /// Builds the `Extern`s that satisfy a compiled Plum module's host imports (today,