plum

#treesitter#compiler#wasm

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

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


4e1ad62 — Peter John 2026-11-10T11:28:56+05:30
CLI: plum check, plum test --filter and --watch, compile fusion flags, clean crash lines
compiler/cli/src/game.rs CHANGED
@@ -364,7 +364,7 @@ fn respond(mut stream: TcpStream, server: &Server) {
364
364
 
365
365
  /// What the watcher compares between polls: size and mtime of every watched file, `None` for a
366
366
  /// file that is missing (so one that disappears and returns is a change).
367
- type Stamps = Vec<(PathBuf, Option<(SystemTime, u64)>)>;
367
+ pub(crate) type Stamps = Vec<(PathBuf, Option<(SystemTime, u64)>)>;
368
368
 
369
369
  fn stamp(path: &Path) -> Option<(SystemTime, u64)> {
370
370
  let m = fs::metadata(path).ok()?;
@@ -392,7 +392,7 @@ fn sourceFiles(entry: &Path, lib: &Path) -> Vec<PathBuf> {
392
392
  seen
393
393
  }
394
394
 
395
- fn sourceStamps(entry: &Path, lib: &Path) -> Stamps {
395
+ pub(crate) fn sourceStamps(entry: &Path, lib: &Path) -> Stamps {
396
396
  sourceFiles(entry, lib).into_iter().map(|f| { let s = stamp(&f); (f, s) }).collect()
397
397
  }
398
398
 
compiler/cli/src/main.rs CHANGED
@@ -49,10 +49,26 @@ enum Command {
49
49
  /// default: `.` when it holds `std`, else the repository plum was built from)
50
50
  #[arg(long)]
51
51
  lib_path: Option<std::path::PathBuf>,
52
+ /// Print the fusion/uniqueness and struct layout decisions to stderr
53
+ #[arg(long, alias = "explain")]
54
+ explain_fusion: bool,
55
+ /// Skip the fusion (supercompiler) stage
56
+ #[arg(long)]
57
+ no_fusion: bool,
52
58
  /// No in-place updates: every spread copies and no cell is reused
53
59
  #[arg(long)]
54
60
  no_fbip: bool,
55
61
  },
62
+ /// Type-check Plum files (and every file under directories) without compiling or running them
63
+ Check {
64
+ /// One or more source files and/or directories (searched recursively for *.plum files)
65
+ #[arg(required = true)]
66
+ paths: Vec<std::path::PathBuf>,
67
+ /// Root directory `import <path>` is resolved against (`import std/x` -> `<lib-path>/std/x.plum`;
68
+ /// default: `.` when it holds `std`, else the repository plum was built from)
69
+ #[arg(long)]
70
+ lib_path: Option<std::path::PathBuf>,
71
+ },
56
72
  /// Run a Plum program: a game is served and opened in the browser, anything else runs under wasmtime
57
73
  Run {
58
74
  /// Source file to compile and run
@@ -134,6 +150,12 @@ enum Command {
134
150
  /// Seconds one test may run before it fails as timed out (default: `PLUM_TEST_TIMEOUT`, else 60; 0 = no limit)
135
151
  #[arg(long)]
136
152
  timeout: Option<f64>,
153
+ /// Run only the tests whose name contains this text
154
+ #[arg(long)]
155
+ filter: Option<String>,
156
+ /// Run the tests again whenever a tested file or anything it imports changes
157
+ #[arg(long)]
158
+ watch: bool,
137
159
  },
138
160
  /// Install Plum syntax highlighting into an editor's configuration
139
161
  Editor {
@@ -169,8 +191,6 @@ fn renderDiag(d: &Diagnostic, entry: &std::path::Path) -> String {
169
191
  let file = if d.file.is_empty() { entry.display().to_string() } else { d.file.clone() };
170
192
  if d.line > 0 {
171
193
  format!("{}:{}:{}: {}{}", file, d.line, d.column, prefix, d.message)
172
- } else if d.kind == DiagKind::Load || (d.file.is_empty() && d.kind == DiagKind::Codegen) {
173
- format!("{}{}", prefix, d.message)
174
194
  } else {
175
195
  format!("{}: {}{}", file, prefix, d.message)
176
196
  }
@@ -184,12 +204,10 @@ fn run() -> Result<()> {
184
204
  let cli = Cli::parse();
185
205
  match cli.command {
186
206
  Command::Format { file, check, stdin } => cmdFormat(file, check, stdin),
187
- Command::Compile {
207
+ Command::Compile { file, output, lib_path, explain_fusion, no_fusion, no_fbip } => {
188
- file,
189
- output,
190
- lib_path,
191
- no_fbip,
192
- } => cmdCompile(file, output, libPathOrDefault(lib_path), no_fbip),
208
+ cmdCompile(file, output, libPathOrDefault(lib_path), fusionFlags(explain_fusion, no_fusion, no_fbip))
209
+ }
210
+ Command::Check { paths, lib_path } => cmdCheck(paths, libPathOrDefault(lib_path)),
193
211
  Command::Run { file, lib_path, explain_fusion, no_fusion, no_fbip, assets, port, no_open, no_watch, replay, args } => {
194
212
  plum_host::setProgramArgs(args);
195
213
  cmdRun(file, lib_path, fusionFlags(explain_fusion, no_fusion, no_fbip), GameOptions { assets, port, noOpen: no_open, noWatch: no_watch, output: None, replay })
@@ -197,8 +215,9 @@ fn run() -> Result<()> {
197
215
  Command::Build { file, output, lib_path, assets, explain_fusion, no_fusion, no_fbip } => {
198
216
  cmdBuild(file, lib_path, fusionFlags(explain_fusion, no_fusion, no_fbip), GameOptions { assets, port: None, noOpen: false, noWatch: false, output, replay: None })
199
217
  }
200
- Command::Test { paths, lib_path, explain_fusion, no_fusion, no_fbip, timeout } => {
218
+ Command::Test { paths, lib_path, explain_fusion, no_fusion, no_fbip, timeout, filter, watch } => {
201
- cmdTest(paths, libPathOrDefault(lib_path), fusionFlags(explain_fusion, no_fusion, no_fbip), testTimeout(timeout)?)
219
+ let options = TestOptions { fusion: fusionFlags(explain_fusion, no_fusion, no_fbip), timeout: testTimeout(timeout)?, filter };
220
+ cmdTest(paths, libPathOrDefault(lib_path), options, watch)
202
221
  }
203
222
  Command::Editor { editor, insiders } => editor::install(editor, insiders),
204
223
  }
@@ -312,9 +331,9 @@ fn cmdCompile(
312
331
  file: std::path::PathBuf,
313
332
  output: Option<std::path::PathBuf>,
314
333
  lib_path: std::path::PathBuf,
315
- no_fbip: bool,
334
+ fusion: plum_driver::PassOptions,
316
335
  ) -> Result<()> {
317
- let wasm_bytes = compileToWasm(&file, &lib_path, plum_driver::PassOptions { fbip: !no_fbip, ..plum_driver::PassOptions::default() })?;
336
+ let wasm_bytes = compileToWasm(&file, &lib_path, fusion)?;
318
337
 
319
338
  let out_path = output.unwrap_or_else(|| file.with_extension("wasm"));
320
339
  fs::write(&out_path, &wasm_bytes)
@@ -324,6 +343,44 @@ fn cmdCompile(
324
343
  Ok(())
325
344
  }
326
345
 
346
+ /// `plum check`: loads and type-checks every file, printing each error; no wasm is made.
347
+ fn cmdCheck(paths: Vec<std::path::PathBuf>, lib_path: std::path::PathBuf) -> Result<()> {
348
+ let mut files = Vec::new();
349
+ for path in &paths {
350
+ files.extend(collectPlumFiles(path)?);
351
+ }
352
+ let opts = plum_driver::PassOptions { closureSpec: false, fusion: false, trmc: false, fbip: false, explain: false };
353
+ let mut bad = 0usize;
354
+ for file in &files {
355
+ let errors = match plum_core::loadAndMergeDiag(file, &lib_path) {
356
+ Ok(ast) => plum_driver::check(&ast, &opts).err(),
357
+ Err(ds) => Some(ds),
358
+ };
359
+ if let Some(ds) = errors {
360
+ eprintln!("{}", renderAll(&ds, file));
361
+ bad += 1;
362
+ }
363
+ }
364
+ if files.len() > 1 || bad > 0 {
365
+ println!("{}/{} files checked without errors", files.len() - bad, files.len());
366
+ }
367
+ if bad > 0 {
368
+ process::exit(1);
369
+ }
370
+ Ok(())
371
+ }
372
+
373
+ /// A trap from a program's `main`, printed once: a `crash` already printed its message
374
+ /// (and a `Result` main's `Err` its variant), so only other traps are reported here.
375
+ fn reportMainTrap(trap: &wasmtime::Error) {
376
+ if plum_host::takeCrash().is_some() {
377
+ return;
378
+ }
379
+ let text = plum_host::trapReport(trap, &|n| plum_core::diag::sourceName(n))
380
+ .unwrap_or_else(|| format!("error: {}", plum_core::diag::sourceName(&format!("{trap:#}"))));
381
+ eprintln!("{text}");
382
+ }
383
+
327
384
  fn cmdRun(
328
385
  file: std::path::PathBuf,
329
386
  lib_path: Option<std::path::PathBuf>,
@@ -354,7 +411,7 @@ fn cmdRun(
354
411
  let resultMain = program.resultMain;
355
412
 
356
413
  // GC + typed function references are required to load modules containing
357
- // Plum's structs/enums/strings/closures (see docs/superpowers/plans/2026-07-25-wasm-gc-migration.md).
414
+ // Plum's structs/enums/strings/closures.
358
415
  let engine = plum_host::engine();
359
416
 
360
417
  let module = wasmtime::Module::new(&engine, &wasm_bytes)
@@ -372,7 +429,7 @@ fn cmdRun(
372
429
  Err(trap) => {
373
430
  // A `Result` main that returned `Err` already printed `crash: <variant>`.
374
431
  if !resultMain {
375
- eprintln!("error: {}", plum_core::diag::sourceName(&trap.to_string()));
432
+ reportMainTrap(&trap);
376
433
  }
377
434
  process::exit(1);
378
435
  }
@@ -387,7 +444,7 @@ fn cmdRun(
387
444
  })?;
388
445
  if let Err(trap) = main.call(&mut store, ()) {
389
446
  if !resultMain {
390
- eprintln!("error: {}", plum_core::diag::sourceName(&trap.to_string()));
447
+ reportMainTrap(&trap);
391
448
  }
392
449
  process::exit(1);
393
450
  }
@@ -396,9 +453,8 @@ fn cmdRun(
396
453
 
397
454
  /// `path` is a file if it points directly at one, otherwise a directory
398
455
  /// walked recursively for every `*.plum` file (sorted for deterministic
399
- /// output) — what lets `plum test` accept a directory (or several) and run
456
+ /// output) — what lets `plum test` and `plum check` accept a directory (or
400
- /// every file under it, replacing `scripts/test-plum.sh`'s own
401
- /// find-and-loop shell logic.
457
+ /// several) and take every file under it.
402
458
  fn collectPlumFiles(path: &std::path::Path) -> Result<Vec<std::path::PathBuf>> {
403
459
  if path.is_file() {
404
460
  return Ok(vec![path.to_path_buf()]);
@@ -441,33 +497,63 @@ fn testTimeout(flag: Option<f64>) -> Result<Option<std::time::Duration>> {
441
497
  /// The epoch tick of `plum test`'s engine: a test's deadline is counted in these.
442
498
  const TEST_TICK: std::time::Duration = std::time::Duration::from_millis(50);
443
499
 
500
+ /// How `plum test` runs each test.
501
+ #[derive(Clone)]
444
- fn cmdTest(
502
+ struct TestOptions {
445
- paths: Vec<std::path::PathBuf>,
446
- lib_path: std::path::PathBuf,
447
503
  fusion: plum_driver::PassOptions,
448
504
  timeout: Option<std::time::Duration>,
505
+ /// Only the tests whose name contains this.
449
- ) -> Result<()> {
506
+ filter: Option<String>,
507
+ }
508
+
509
+ fn cmdTest(paths: Vec<std::path::PathBuf>, lib_path: std::path::PathBuf, options: TestOptions, watch: bool) -> Result<()> {
510
+ if !watch {
511
+ if !testOnce(&paths, &lib_path, &options)? {
512
+ process::exit(1);
513
+ }
514
+ return Ok(());
515
+ }
516
+ // `--watch`: run, then wait for a tested file or anything it imports to change.
517
+ let stamps = || -> Result<Vec<game::Stamps>> {
518
+ let mut files = Vec::new();
519
+ for path in &paths {
520
+ files.extend(collectPlumFiles(path)?);
521
+ }
522
+ Ok(files.iter().map(|f| game::sourceStamps(f, &lib_path)).collect())
523
+ };
524
+ loop {
525
+ let before = stamps()?;
526
+ if let Err(e) = testOnce(&paths, &lib_path, &options) {
527
+ eprintln!("error: {e:#}");
528
+ }
529
+ println!("watching for changes (Ctrl-C to stop)");
530
+ while stamps()? == before {
531
+ std::thread::sleep(std::time::Duration::from_millis(300));
532
+ }
533
+ println!();
534
+ }
535
+ }
536
+
537
+ /// One `plum test` run over `paths`; whether every test passed.
538
+ fn testOnce(paths: &[std::path::PathBuf], lib_path: &std::path::Path, options: &TestOptions) -> Result<bool> {
539
+ let lib_path = lib_path.to_path_buf();
450
- // A single plain file keeps the exact original single-file UX (no
540
+ // A single plain file keeps the single-file output (no `=== path ===`
451
- // `=== path ===` header, no aggregate summary line, no "N/1 files
541
+ // header, no aggregate summary line, no "N/1 files passed" — just that
452
- // passed" — just that one file's own test tree). Anything else (a
542
+ // one file's own test tree). Anything else (a directory, or more than one
453
- // directory, or more than one path) uses the multi-file sweep below,
543
+ // path) uses the multi-file sweep below.
454
- // matching `scripts/test-plum.sh`'s old find-and-loop shell logic.
455
- if let [only] = paths.as_slice() {
544
+ if let [only] = paths {
456
545
  if only.is_file() {
457
- let (passed, failed) = runTestFile(only, &lib_path, fusion, timeout)?;
546
+ let (passed, failed) = runTestFile(only, &lib_path, options)?;
458
547
  // A sweep's worker (see `runSweepParallel`) reads the counts from this line.
459
548
  if std::env::var_os(TEST_CHILD_ENV).is_some() {
460
549
  println!("{COUNTS_MARK}{passed} {failed}");
461
550
  }
462
- if failed > 0 {
463
- process::exit(1);
464
- }
465
- return Ok(());
551
+ return Ok(failed == 0);
466
552
  }
467
553
  }
468
554
 
469
555
  let mut files = Vec::new();
470
- for path in &paths {
556
+ for path in paths {
471
557
  files.extend(collectPlumFiles(path)?);
472
558
  }
473
559
  let mut total_passed = 0usize;
@@ -475,11 +561,11 @@ fn cmdTest(
475
561
  let mut files_failed = 0usize;
476
562
  let jobs = testJobs();
477
563
  if jobs > 1 && files.len() > 1 {
478
- (total_passed, total_failed, files_failed) = runSweepParallel(&files, &lib_path, fusion, timeout, jobs)?;
564
+ (total_passed, total_failed, files_failed) = runSweepParallel(&files, &lib_path, options, jobs)?;
479
565
  } else {
480
566
  for file in &files {
481
567
  println!("=== {} ===", file.display());
482
- match runTestFile(file, &lib_path, fusion, timeout) {
568
+ match runTestFile(file, &lib_path, options) {
483
569
  Ok((passed, failed)) => {
484
570
  total_passed += passed;
485
571
  total_failed += failed;
@@ -524,10 +610,7 @@ fn cmdTest(
524
610
  files.len() - files_failed,
525
611
  files.len()
526
612
  );
527
- if files_failed > 0 {
613
+ Ok(files_failed == 0)
528
- process::exit(1);
529
- }
530
- Ok(())
531
614
  }
532
615
 
533
616
  /// Set on a sweep's child `plum test <file>`: it then prints its counts on a `COUNTS_MARK` line.
@@ -555,10 +638,10 @@ fn testJobs() -> usize {
555
638
  fn runSweepParallel(
556
639
  files: &[std::path::PathBuf],
557
640
  lib_path: &std::path::Path,
558
- fusion: plum_driver::PassOptions,
641
+ options: &TestOptions,
559
- timeout: Option<std::time::Duration>,
560
642
  jobs: usize,
561
643
  ) -> Result<(usize, usize, usize)> {
644
+ let (fusion, timeout) = (options.fusion, options.timeout);
562
645
  use std::io::Write;
563
646
  use std::sync::atomic::{AtomicUsize, Ordering};
564
647
  let exe = std::env::current_exe().context("cannot find the plum executable")?;
@@ -590,6 +673,9 @@ fn runSweepParallel(
590
673
  cmd.arg("--explain-fusion");
591
674
  }
592
675
  cmd.arg("--timeout").arg(timeout.map_or(0.0, |t| t.as_secs_f64()).to_string());
676
+ if let Some(f) = &options.filter {
677
+ cmd.arg("--filter").arg(f);
678
+ }
593
679
  cmd.arg(file).env(TEST_CHILD_ENV, "1").stdin(process::Stdio::null());
594
680
  if color {
595
681
  cmd.env(TEST_COLOR_ENV, "1");
@@ -742,16 +828,18 @@ fn outputWithin(
742
828
  /// Runs every `test` block in one file, printing the Spock-flavored per-test
743
829
  /// tree as it goes, and returns `(passed, failed)` counts — shared by both
744
830
  /// the single-file and directory-recursive paths of `cmdTest`.
745
- fn runTestFile(
746
- file: &std::path::Path,
747
- lib_path: &std::path::Path,
831
+ fn runTestFile(file: &std::path::Path, lib_path: &std::path::Path, options: &TestOptions) -> Result<(usize, usize)> {
748
- fusion: plum_driver::PassOptions,
749
- timeout: Option<std::time::Duration>,
832
+ let timeout = options.timeout;
750
- ) -> Result<(usize, usize)> {
751
- let (wasm_bytes, names) = compileToTestWasm(file, lib_path, fusion)?;
833
+ let (wasm_bytes, mut names) = compileToTestWasm(file, lib_path, options.fusion)?;
752
- if let Ok(path) = std::env::var("PLUM_DUMP_WASM") {
753
- let _ = std::fs::write(path, &wasm_bytes);
834
+ if let Some(f) = &options.filter {
835
+ names.retain(|n| n.contains(f.as_str()));
836
+ if names.is_empty() {
837
+ println!("no tests in {} match `{f}`", file.display());
838
+ return Ok((0, 0));
839
+ }
754
840
  }
841
+ // A `crash` is reported in its test's line, not printed apart.
842
+ plum_host::setQuietCrash(true);
755
843
 
756
844
  let engine = plum_host::engineWithTicker(TEST_TICK);
757
845
  // The deadline, in ticks, set afresh before each test (and before instantiation).
@@ -833,7 +921,9 @@ fn runTestFile(
833
921
  failed += 1;
834
922
  }
835
923
  Err(trap) => {
924
+ let report = plum_host::trapReport(&trap, &|n| plum_core::diag::sourceName(n))
925
+ .unwrap_or_else(|| plum_core::diag::sourceName(&format!("{trap:#}")));
836
- println!("{branch} {name} {} PANIC: {}", red("\u{2718}"), plum_core::diag::sourceName(&format!("{trap:#}")));
926
+ println!("{branch} {name} {} PANIC: {report}", red("\u{2718}"));
837
927
  failed += 1;
838
928
  }
839
929
  }
compiler/cli/tests/cli/crash_test.rs CHANGED
@@ -79,6 +79,24 @@ fn crash_in_a_loop_names_the_function_not_its_lifted_loop() {
79
79
  .expect("failed to run plum");
80
80
  let stderr = String::from_utf8_lossy(&out.stderr);
81
81
  assert!(!out.status.success(), "stderr: {stderr}");
82
- assert!(stderr.contains("!boom"), "stderr was: {stderr}");
82
+ assert!(stderr.contains("crash: division by zero in boom (called from main)"), "stderr was: {stderr}");
83
83
  assert!(!stderr.contains("@loop"), "stderr was: {stderr}");
84
84
  }
85
+
86
+ /// A trap is one clean line naming the function, not a wasmtime backtrace; a `crash`
87
+ /// prints its message once, with no trap report after it.
88
+ #[test]
89
+ fn aTrapIsOneCleanLine() {
90
+ let dir = crate::common::Scratch::new("trap_line");
91
+ std::fs::write(dir.join("div.plum"), "import std/Int\n\nfun main() -> Int =\n z := 0\n 1 / z\n").unwrap();
92
+ std::fs::write(dir.join("boom.plum"), "import std/Str\n\nfun main() =\n crash \"boom\"\n").unwrap();
93
+ let run = |f: &str| {
94
+ let out = Command::new(plumBin()).current_dir(crate::common::root()).arg("run").arg(dir.join(f)).output().unwrap();
95
+ assert!(!out.status.success());
96
+ String::from_utf8_lossy(&out.stderr).into_owned()
97
+ };
98
+ assert_eq!(run("div.plum").trim(), "crash: division by zero in main");
99
+ let boom = run("boom.plum");
100
+ assert_eq!(boom.lines().count(), 1, "{boom}");
101
+ assert!(boom.starts_with("crash: boom at "), "{boom}");
102
+ }
compiler/cli/tests/cli/test_scope_test.rs CHANGED
@@ -80,3 +80,81 @@ fn libPathDefaultsToTheBuiltRepositoryOutsideACheckout() {
80
80
  assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
81
81
  assert!(dir.join("a.wasm").is_file());
82
82
  }
83
+
84
+ /// `--filter` runs only the tests whose name contains the text, in a file and in a sweep.
85
+ #[test]
86
+ fn filterRunsOnlyMatchingTests() {
87
+ let dir = scratch("filter");
88
+ std::fs::write(dir.join("a.plum"), TWO).unwrap();
89
+ std::fs::write(dir.join("b.plum"), "import std/Int\n\ntest \"other\"\n assert 1 == 2\n").unwrap();
90
+ let (out, ok) = runPlum(&["--filter", "tw", dir.join("a.plum").to_str().unwrap()]);
91
+ assert!(ok && out.contains("two") && !out.contains("one") && out.contains("1 passed, 0 failed"), "{out}");
92
+ let (out, ok) = runPlum(&["--filter", "on", dir.to_str().unwrap()]);
93
+ assert!(ok, "{out}");
94
+ assert!(out.contains("1 passed, 0 failed") && out.contains("no tests in"), "{out}");
95
+ }
96
+
97
+ /// `plum check` reports a type error with its file and fails; clean files pass.
98
+ #[test]
99
+ fn checkReportsTypeErrorsWithoutRunning() {
100
+ let dir = scratch("check");
101
+ std::fs::write(dir.join("good.plum"), TWO).unwrap();
102
+ std::fs::write(dir.join("bad.plum"), "import std/Int\n\nfun main() -> Int =\n nope\n").unwrap();
103
+ let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).ancestors().nth(2).unwrap();
104
+ let out = Command::new(plumBin()).current_dir(root).arg("check").arg(dir.path()).output().unwrap();
105
+ let err = String::from_utf8_lossy(&out.stderr);
106
+ assert!(!out.status.success());
107
+ assert!(err.contains("bad.plum:4:3: type error") && err.contains("nope"), "{err}");
108
+ assert!(String::from_utf8_lossy(&out.stdout).contains("1/2 files checked without errors"));
109
+ let out = Command::new(plumBin()).current_dir(root).arg("check").arg(dir.join("good.plum")).output().unwrap();
110
+ assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
111
+ }
112
+
113
+ /// A load error names the file it came from.
114
+ #[test]
115
+ fn aLoadErrorNamesItsFile() {
116
+ let dir = scratch("loaderr");
117
+ std::fs::write(dir.join("m.plum"), "import std/NoSuchThing\n").unwrap();
118
+ let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).ancestors().nth(2).unwrap();
119
+ let out = Command::new(plumBin()).current_dir(root).arg("compile").arg(dir.join("m.plum")).output().unwrap();
120
+ let err = String::from_utf8_lossy(&out.stderr);
121
+ assert!(err.contains("m.plum: ") && err.contains("NoSuchThing"), "{err}");
122
+ }
123
+
124
+ /// `--watch` runs the tests again when the file changes.
125
+ #[test]
126
+ fn watchRerunsOnAChange() {
127
+ use std::io::BufRead;
128
+ let dir = scratch("watch");
129
+ let file = dir.join("w.plum");
130
+ std::fs::write(&file, TWO).unwrap();
131
+ let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).ancestors().nth(2).unwrap();
132
+ let mut child = crate::common::KillOnDrop(
133
+ Command::new(plumBin())
134
+ .current_dir(root)
135
+ .args(["test", "--watch"])
136
+ .arg(&file)
137
+ .stdout(std::process::Stdio::piped())
138
+ .stderr(std::process::Stdio::null())
139
+ .spawn()
140
+ .unwrap(),
141
+ );
142
+ let (tx, rx) = std::sync::mpsc::channel();
143
+ let out = child.0.stdout.take().unwrap();
144
+ std::thread::spawn(move || {
145
+ for line in std::io::BufReader::new(out).lines() {
146
+ if tx.send(line.unwrap_or_default()).is_err() {
147
+ break;
148
+ }
149
+ }
150
+ });
151
+ let waitFor = |needle: &str| loop {
152
+ let line = rx.recv_timeout(std::time::Duration::from_secs(60)).unwrap_or_else(|_| panic!("no `{needle}`"));
153
+ if line.contains(needle) {
154
+ break;
155
+ }
156
+ };
157
+ waitFor("watching for changes");
158
+ std::fs::write(&file, TWO.replace("assert 2 == 2", "assert 2 == 3 ")).unwrap();
159
+ waitFor("1 passed, 1 failed");
160
+ }
compiler/host/src/lib.rs CHANGED
@@ -58,6 +58,81 @@ pub fn engineConfig() -> wasmtime::Config {
58
58
  config
59
59
  }
60
60
 
61
+ /// The message of the last `crash` (the `plum::crash` import), until `takeCrash` reads it.
62
+ static LAST_CRASH: std::sync::Mutex<Option<String>> = std::sync::Mutex::new(None);
63
+ /// When set, `crash` only records its message (for `trapReport`) and prints nothing.
64
+ static QUIET_CRASH: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
65
+
66
+ /// `quiet`: a `crash` records its message without printing it (`plum test` shows it in
67
+ /// the failed test's line instead).
68
+ pub fn setQuietCrash(quiet: bool) {
69
+ QUIET_CRASH.store(quiet, std::sync::atomic::Ordering::Relaxed);
70
+ }
71
+
72
+ /// The message of the `crash` since the last call (`crash: <text> at <file:line:col>`).
73
+ pub fn takeCrash() -> Option<String> {
74
+ LAST_CRASH.lock().unwrap_or_else(|e| e.into_inner()).take()
75
+ }
76
+
77
+ /// What a trap means, in words.
78
+ fn trapWords(trap: wasmtime::Trap) -> String {
79
+ use wasmtime::Trap;
80
+ match trap {
81
+ Trap::IntegerDivisionByZero => "division by zero".into(),
82
+ Trap::IntegerOverflow => "integer overflow".into(),
83
+ Trap::BadConversionToInteger => "float out of the Int range".into(),
84
+ Trap::StackOverflow => "stack overflow (too deep a recursion)".into(),
85
+ Trap::MemoryOutOfBounds | Trap::HeapMisaligned => "memory access out of bounds".into(),
86
+ Trap::TableOutOfBounds | Trap::ArrayOutOfBounds => "index out of bounds".into(),
87
+ Trap::NullReference | Trap::IndirectCallToNull => "null reference".into(),
88
+ Trap::CastFailure => "a value of the wrong type".into(),
89
+ Trap::AllocationTooLarge => "allocation too large".into(),
90
+ Trap::UnreachableCodeReached => "unreachable code reached".into(),
91
+ Trap::Interrupt => "interrupted (timed out)".into(),
92
+ Trap::OutOfFuel => "out of fuel".into(),
93
+ other => other.to_string(),
94
+ }
95
+ }
96
+
97
+ /// The Plum function a backtrace frame's name (the module's `name` section) stands
98
+ /// for; `None` for the compiler's own wrappers and for a test's generated function.
99
+ fn frameName(name: &str, rename: &dyn Fn(&str) -> String) -> Option<String> {
100
+ if ["export.", "unbox.", "rebox.", "__test_"].iter().any(|p| name.starts_with(p)) || name == "start" {
101
+ return None;
102
+ }
103
+ let name = name.strip_prefix("fn.").unwrap_or(name);
104
+ Some(match name.strip_suffix(".closure") {
105
+ Some(owner) => format!("a closure in {}", rename(owner)),
106
+ None => rename(name),
107
+ })
108
+ }
109
+
110
+ /// A failed call into a Plum module, for a person: `crash: division by zero in div
111
+ /// (called from main)`. A `crash` with a message reports that message (it already says
112
+ /// where); else the trap in words and the Plum functions on the stack, innermost first,
113
+ /// each through `rename` (the compiler's internal names to source names). `None` when
114
+ /// the error is not a trap or crash at all.
115
+ pub fn trapReport(err: &wasmtime::Error, rename: &dyn Fn(&str) -> String) -> Option<String> {
116
+ if let Some(message) = takeCrash() {
117
+ return Some(message);
118
+ }
119
+ let what = trapWords(*err.downcast_ref::<wasmtime::Trap>()?);
120
+ let mut names: Vec<String> = err
121
+ .downcast_ref::<wasmtime::WasmBacktrace>()
122
+ .map(|bt| bt.frames().iter().filter_map(|f| f.func_name()).filter_map(|n| frameName(n, rename)).collect())
123
+ .unwrap_or_default();
124
+ names.dedup();
125
+ Some(match names.split_first() {
126
+ None => format!("crash: {what}"),
127
+ Some((inner, [])) => format!("crash: {what} in {inner}"),
128
+ Some((inner, outer)) => {
129
+ let shown: Vec<&str> = outer.iter().take(8).map(String::as_str).collect();
130
+ let more = if outer.len() > 8 { ", ..." } else { "" };
131
+ format!("crash: {what} in {inner} (called from {}{more})", shown.join(", "))
132
+ }
133
+ })
134
+ }
135
+
61
136
  /// Builds the `Extern`s that satisfy a compiled Plum module's host imports (today,
62
137
  /// only `plum::printLn`) in declaration order, matching each one's exact `FuncType`
63
138
  /// (its `Str` param is a concrete wasm-gc array type, so the host function must be
@@ -103,7 +178,11 @@ pub fn hostImports(
103
178
  return Err(wasmtime::Error::msg("crash expects a Str argument"));
104
179
  };
105
180
  let buf = strBytes(&mut caller, s)?;
106
- eprintln!("crash: {}", String::from_utf8_lossy(&buf));
181
+ let message = format!("crash: {}", String::from_utf8_lossy(&buf));
182
+ if !QUIET_CRASH.load(std::sync::atomic::Ordering::Relaxed) {
183
+ eprintln!("{message}");
184
+ }
185
+ *LAST_CRASH.lock().unwrap_or_else(|e| e.into_inner()) = Some(message);
107
186
  Ok(())
108
187
  },
109
188
  )))
docs/tools.md CHANGED
@@ -2,14 +2,15 @@
2
2
 
3
3
  ## Commands
4
4
 
5
- Run these from a checkout of this repository, or pass `--lib-path`, so `import std/...` can find the standard library.
5
+ `import std/...` resolves against `--lib-path`. Without it, every command (and the language server) uses `.` when it holds a `std` folder, as a checkout of this repository does, else the repository `plum` was built from.
6
6
 
7
7
  | Command | What it does |
8
8
  |---|---|
9
9
  | `plum run file.plum` | Compile and run. A program whose `main` returns a [game](game.md), a type with `update` and `draw`, opens in the browser |
10
10
  | `plum run file.plum -- a b` | Run with arguments: the words after `--` are the program's `io.args()` (here `a` and `b`). A `plum build` executable gets its own arguments the same way; `plum test` and a game in the browser get none |
11
11
  | `plum test file.plum dir/` | Run the `test` blocks in files and folders |
12
+ | `plum check file.plum dir/` | Type-check files and folders without compiling or running them |
12
- | `plum compile file.plum` | Write `file.wasm` |
13
+ | `plum compile file.plum` | Write `file.wasm` (`-o` names the file) |
13
14
  | `plum build file.plum` | Make a native executable, or for a game, a static site |
14
15
  | `plum format file.plum` | Format the file in place (`--check` only checks, `--stdin` reads standard input) |
15
16
  | `plum editor helix` | Set up Helix |
@@ -32,13 +33,35 @@ Run these from a checkout of this repository, or pass `--lib-path`, so `import s
32
33
  | `-o DIR` | Write the site to `DIR` (default `dist`) |
33
34
  | `--assets DIR` | Load assets from `DIR` |
34
35
 
36
+ **Options for `plum test`:**
37
+
38
+ | Option | What it does |
39
+ |---|---|
40
+ | `--filter TEXT` | Run only the tests whose name contains `TEXT` |
41
+ | `--watch` | Run the tests again whenever a tested file, or a file it imports, changes |
42
+ | `--timeout SECONDS` | Fail a test that runs longer, as `TIMEOUT` (default 60, or `PLUM_TEST_TIMEOUT`; 0 means no limit). The other tests in the file still run |
43
+
44
+ Folders are tested one file per process, as many at once as there are cores (`PLUM_TEST_JOBS` sets the number), slowest first: how long each file took is kept in `$TMPDIR/plum-test-durations.txt`.
45
+
35
- **Options for looking at the compiler's work:**
46
+ **Options for looking at the compiler's work** (`run`, `build`, `test`, `compile`):
36
47
 
37
48
  | Option | What it does |
38
49
  |---|---|
39
50
  | `--no-fusion` | Turn off the optimisations described in [Performance](performance.md) |
51
+ | `--no-fbip` | Turn off in-place updates: every spread copies and no cell is reused |
40
52
  | `--explain-fusion` | Print each optimisation decision and how each struct is stored |
41
53
 
54
+ **Environment variables:**
55
+
56
+ | Variable | What it does |
57
+ |---|---|
58
+ | `PLUM_TEST_JOBS=N` | How many files `plum test` tests at once |
59
+ | `PLUM_TEST_TIMEOUT=SECONDS` | The default of `plum test --timeout` |
60
+ | `PLUM_DUMP_WASM=out.wasm` | `plum test`: also write the compiled test module to `out.wasm` |
61
+ | `PLUM_TIMINGS=1` | Print how long each compiler pass takes |
62
+
63
+ A program that crashes prints one line, such as `crash: division by zero in div (called from main)`, or the message and place of a `crash`.
64
+
42
65
  ## Editors
43
66
 
44
67
  `plum editor helix` and `plum editor vscode` install syntax highlighting and the language server, which gives you errors as you type and completion. Everything is built into the `plum` binary, so they work from any folder. Reload your editor afterwards.
@@ -51,7 +74,9 @@ You need a recent stable Rust toolchain and a C compiler.
51
74
  cargo install --path compiler/cli
52
75
  ```
53
76
 
54
- This installs `plum` to `~/.cargo/bin`. Run it again after pulling changes. While working on the compiler, use `cargo run -p plum-cli --` instead.
77
+ This installs `plum` to `~/.cargo/bin`. Run it again after pulling changes. While working on the compiler, use `cargo run -p plum-cli --` instead, and run `compiler/scripts/test-all.sh` before a commit: it builds, runs every Rust test and then `plum test std examples tests` in the default, `--no-fbip` and `--no-fusion` modes, and ends with `ALL PASSED` or `FAILED: <n>`.
78
+
79
+ `plum build` of a program that is not a game compiles the `compiler/runtime` crate with cargo, so it needs this source tree and cargo on `PATH`.
55
80
 
56
81
  To rebuild the VSCode extension, you also need `node` and `npm`: run `npm install && npm run build` in `compiler/tooling/vscode-plum`.
57
82