plum

#treesitter#compiler#wasm

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

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


f41a2d9 — Peter John 2026-11-13T16:30:43+05:30
web/plum_bridge and web-test, from master (86085924, d8df3f79, 9a43a992); plum run <folder>: after GPU_WAIT_MS (5 s) with no WebGPU adapter or device the page says "WebGPU did not answer within 5 s. Still waiting; .." and logs a console.error, goes on waiting, and an answer that comes late takes the message away, logs "WebGPU answered after N s" and starts the game; web-test --stall-adapter checks both halves (chromium_says_when_webgpu_does_not_answer_and_starts_when_it_does), the checks and the record and replay pages forgive that error on a page that then answered; record_and_replay closes the recording page once its recording is taken and fails a replay page that never set plumRenderer; web_check's browser tests take turns, one browser at a time (this branch has no play_check); plum run and plum build take a folder and run its one .plum file with a `fun main` (none or two is an error), with CLI tests; README, game.md, tools.md, the backlog
compiler/cli/src/main.rs CHANGED
@@ -71,7 +71,7 @@ enum Command {
71
71
  },
72
72
  /// Run a Plum program: a game is served and opened in the browser, anything else runs under wasmtime
73
73
  Run {
74
- /// Source file to compile and run
74
+ /// Source file to compile and run, or a folder holding one file with a `main` (a game's)
75
75
  file: std::path::PathBuf,
76
76
  /// Print the fusion/uniqueness and struct layout decisions to stderr
77
77
  #[arg(long, alias = "explain")]
@@ -107,7 +107,7 @@ enum Command {
107
107
  },
108
108
  /// Build a Plum program: a game becomes a static web build (a folder), anything else a native executable
109
109
  Build {
110
- /// Source file to compile
110
+ /// Source file to compile, or a folder holding one file with a `main`
111
111
  file: std::path::PathBuf,
112
112
  /// Print the fusion/uniqueness and struct layout decisions to stderr
113
113
  #[arg(long, alias = "explain")]
@@ -210,10 +210,10 @@ fn run() -> Result<()> {
210
210
  Command::Check { paths, lib_path } => cmdCheck(paths, libPathOrDefault(lib_path)),
211
211
  Command::Run { file, lib_path, explain_fusion, no_fusion, no_fbip, assets, port, no_open, no_watch, replay, args } => {
212
212
  plum_host::setProgramArgs(args);
213
- cmdRun(file, lib_path, fusionFlags(explain_fusion, no_fusion, no_fbip), GameOptions { assets, port, noOpen: no_open, noWatch: no_watch, output: None, replay })
213
+ cmdRun(program::entryFile(&file)?, lib_path, fusionFlags(explain_fusion, no_fusion, no_fbip), GameOptions { assets, port, noOpen: no_open, noWatch: no_watch, output: None, replay })
214
214
  }
215
215
  Command::Build { file, output, lib_path, assets, explain_fusion, no_fusion, no_fbip } => {
216
- cmdBuild(file, lib_path, fusionFlags(explain_fusion, no_fusion, no_fbip), GameOptions { assets, port: None, noOpen: false, noWatch: false, output, replay: None })
216
+ cmdBuild(program::entryFile(&file)?, lib_path, fusionFlags(explain_fusion, no_fusion, no_fbip), GameOptions { assets, port: None, noOpen: false, noWatch: false, output, replay: None })
217
217
  }
218
218
  Command::Test { paths, lib_path, explain_fusion, no_fusion, no_fbip, timeout, filter, watch } => {
219
219
  let options = TestOptions { fusion: fusionFlags(explain_fusion, no_fusion, no_fbip), timeout: testTimeout(timeout)?, filter };
compiler/cli/src/program.rs CHANGED
@@ -36,6 +36,32 @@ pub struct Failure {
36
36
  pub text: String,
37
37
  }
38
38
 
39
+ /// The file `plum run` / `plum build` runs for `path`: the file itself, or for a folder (a
40
+ /// game's, with its `assets`) the one `.plum` file directly in it with a `fun main`.
41
+ pub fn entryFile(path: &Path) -> Result<std::path::PathBuf> {
42
+ if !path.is_dir() {
43
+ return Ok(path.to_path_buf());
44
+ }
45
+ let mut files: Vec<std::path::PathBuf> = std::fs::read_dir(path)?
46
+ .flatten()
47
+ .map(|e| e.path())
48
+ .filter(|p| p.is_file() && p.extension().is_some_and(|x| x == "plum"))
49
+ .collect();
50
+ files.sort();
51
+ let hasMain = |f: &std::path::PathBuf| {
52
+ std::fs::read_to_string(f).is_ok_and(|t| t.lines().any(|l| l.starts_with("fun main(")))
53
+ };
54
+ let mains: Vec<&std::path::PathBuf> = files.iter().filter(|f| hasMain(f)).collect();
55
+ match mains.as_slice() {
56
+ [one] => Ok(one.to_path_buf()),
57
+ [] => anyhow::bail!("{} has no .plum file with a `fun main`", path.display()),
58
+ _ => {
59
+ let names: Vec<String> = mains.iter().map(|f| f.display().to_string()).collect();
60
+ anyhow::bail!("{} has more than one .plum file with a `fun main`: {}; name the file to run", path.display(), names.join(", "))
61
+ }
62
+ }
63
+ }
64
+
39
65
  /// Loads, compiles and classifies `file`. Compile errors are printed and exit the process.
40
66
  pub fn compileProgram(
41
67
  file: &Path,
compiler/cli/tests/cli/main.rs CHANGED
@@ -18,6 +18,7 @@ mod main_result_test;
18
18
  mod no_fbip_test;
19
19
  mod old_forms_test;
20
20
  mod replay_test;
21
+ mod run_folder_test;
21
22
  mod std_bounds_test;
22
23
  mod test_exes_script_test;
23
24
  mod test_scope_test;
compiler/cli/tests/cli/run_folder_test.rs ADDED
@@ -0,0 +1,51 @@
1
+ #![allow(non_snake_case)]
2
+ //! `plum run <folder>`: the folder's one `.plum` file with a `fun main` is run (a game's folder
3
+ //! with its `assets`, or any folder); none or two of them is an error naming the folder.
4
+ use std::process::Command;
5
+
6
+ use crate::common::{plumBin, root, Scratch};
7
+
8
+ fn run(args: &[&str]) -> (bool, String, String) {
9
+ let out = Command::new(plumBin()).current_dir(root()).args(args).output().unwrap();
10
+ (out.status.success(), String::from_utf8_lossy(&out.stdout).into_owned(), String::from_utf8_lossy(&out.stderr).into_owned())
11
+ }
12
+
13
+ const APP: &str = "import std/Str\nimport std/Io\n\nfun main(io: Io) =\n io.printLn(\"hi from the folder\")\n";
14
+
15
+ #[test]
16
+ fn runFolderRunsItsOneMain() {
17
+ let dir = Scratch::new("run_folder_one");
18
+ std::fs::write(dir.join("App.plum"), APP).unwrap();
19
+ std::fs::write(dir.join("Helper.plum"), "fun helper() -> Int = 1\n").unwrap();
20
+ std::fs::create_dir(dir.join("sub")).unwrap();
21
+ std::fs::write(dir.join("sub/Other.plum"), APP).unwrap();
22
+ let (ok, stdout, stderr) = run(&["run", dir.path().to_str().unwrap()]);
23
+ assert!(ok, "{stderr}");
24
+ assert_eq!(stdout.trim(), "hi from the folder");
25
+ }
26
+
27
+ #[test]
28
+ fn runFolderWithNoMainOrTwoFails() {
29
+ let dir = Scratch::new("run_folder_none");
30
+ std::fs::write(dir.join("Helper.plum"), "fun helper() -> Int = 1\n").unwrap();
31
+ let (ok, _, stderr) = run(&["run", dir.path().to_str().unwrap()]);
32
+ assert!(!ok && stderr.contains("has no .plum file with a `fun main`"), "{stderr}");
33
+ std::fs::write(dir.join("A.plum"), APP).unwrap();
34
+ std::fs::write(dir.join("B.plum"), APP).unwrap();
35
+ let (ok, _, stderr) = run(&["run", dir.path().to_str().unwrap()]);
36
+ assert!(!ok && stderr.contains("has more than one .plum file with a `fun main`") && stderr.contains("name the file to run"), "{stderr}");
37
+ }
38
+
39
+ /// A game's folder runs the game: its headless replay matches the one of its main file.
40
+ #[test]
41
+ fn runGameFolderIsItsMainFile() {
42
+ let dir = Scratch::new("run_folder_game");
43
+ let replay = dir.join("replay.txt");
44
+ std::fs::write(&replay, format!("plum-replay 1 7 9 800 600\n{}", "- 0 0 0 0\n".repeat(30))).unwrap();
45
+ let byFile = run(&["run", "examples/games/orbitrunner/OrbitRunner.plum", "--replay", replay.to_str().unwrap()]);
46
+ let byFolder = run(&["run", "examples/games/orbitrunner", "--replay", replay.to_str().unwrap()]);
47
+ assert!(byFile.0, "{}", byFile.2);
48
+ assert!(byFolder.0, "{}", byFolder.2);
49
+ assert!(!byFile.1.is_empty());
50
+ assert_eq!(byFolder.1, byFile.1);
51
+ }
compiler/game/web-test/README.md CHANGED
@@ -21,8 +21,8 @@ Downloads the Chromium and WebKit builds matching the bundled Playwright driver
21
21
 
22
22
  cargo run --manifest-path compiler/game/web-test/Cargo.toml -- examples/games/orbitrunner/OrbitRunner.plum --screenshot /tmp/orb-run.png
23
23
 
24
- Options: `--browser chromium|webkit` (default chromium; WebKit is Playwright's Safari-engine build and has WebGPU, so the same render assertions apply; a WebKit build without `navigator.gpu` is checked for the "WebGPU is not supported in this browser" message and a loadable plum.wasm instead), `--expect-unsupported-webgpu` (hides `navigator.gpu` in any browser and checks that path), `--no-module-introspection` (makes `WebAssembly.Module.imports/exports/customSections` throw the TypeError Safari gives for typed GC references), `--frames-wait SECS` (default 8), `--screenshot OUT.png`, `--assets DIR` (default: the nearest `assets` folder beside the source or in a parent, e.g. `examples/games/orbitrunner/assets`), `--require-audio`, `--json` (adds a one-line JSON object with the backend and frame stats), `--headed` (a real GPU window instead of headless software WebGPU), `--measure SECS` (records requestAnimationFrame intervals in the page and prints avg / p50 / p95 / p99 ms, fps and the mean per-frame update/draw/render split; `--json` adds `update_ms`, `draw_ms`, `render_ms`) and `--uncapped` (lifts vsync so the frame time is the work per frame), `--dpr N` (Playwright `deviceScaleFactor`; also checks the backing store is CSS size x ratio), `--lose-device` (destroys the GPU device from the page after a few frames and requires the `GPU device lost (...); restored` log and resumed rendering; the page exposes the device only when the harness asks) and `--expect-pixel x,y,r,g,b[,tol]` (repeatable; the screenshot pixel at CSS (x, y), default tolerance 2). `--json` also reports `draws`, the GPU draw calls per frame. `fixtures/interleave.plum`, `text_sizes.plum` and `rendertarget.plum` exercise multi-texture batching, SDF text and render targets/blend modes. `fixtures/stress.plum` and `fixtures/stress_state_view.plum` (drawn by a screen's view) are scenes behind [BENCHMARK.md](BENCHMARK.md).
24
+ Options: `--browser chromium|webkit` (default chromium; WebKit is Playwright's Safari-engine build and has WebGPU, so the same render assertions apply; a WebKit build without `navigator.gpu` is checked for the "WebGPU is not supported in this browser" message and a loadable plum.wasm instead), `--expect-unsupported-webgpu` (hides `navigator.gpu` in any browser and checks that path), `--no-module-introspection` (makes `WebAssembly.Module.imports/exports/customSections` throw the TypeError Safari gives for typed GC references), `--frames-wait SECS` (default 8), `--screenshot OUT.png`, `--assets DIR` (default: the nearest `assets` folder beside the source or in a parent, e.g. `examples/games/orbitrunner/assets`), `--require-audio`, `--json` (adds a one-line JSON object with the backend and frame stats), `--headed` (a real GPU window instead of headless software WebGPU), `--measure SECS` (records requestAnimationFrame intervals in the page and prints avg / p50 / p95 / p99 ms, fps and the mean per-frame update/draw/render split; `--json` adds `update_ms`, `draw_ms`, `render_ms`) and `--uncapped` (lifts vsync so the frame time is the work per frame), `--dpr N` (Playwright `deviceScaleFactor`; also checks the backing store is CSS size x ratio), `--lose-device` (destroys the GPU device from the page after a few frames and requires the `GPU device lost (...); restored` log and resumed rendering; the page exposes the device only when the harness asks), `--stall-adapter` (holds every `navigator.gpu.requestAdapter()` unanswered: the page must show and log "WebGPU did not answer within 5 s" (the bridge's wait, `GPU_WAIT_MS`) and not start; the harness then lets the adapter through, and the game must start, the message go and the usual check pass. A page whose WebGPU answered late, here or under load, has that one `console.error` forgiven, as it logs `WebGPU answered after N s`) and `--expect-pixel x,y,r,g,b[,tol]` (repeatable; the screenshot pixel at CSS (x, y), default tolerance 2). `--json` also reports `draws`, the GPU draw calls per frame. `fixtures/interleave.plum`, `text_sizes.plum` and `rendertarget.plum` exercise multi-texture batching, SDF text and render targets/blend modes. `fixtures/stress.plum` and `fixtures/stress_state_view.plum` (drawn by a screen's view) are scenes behind [BENCHMARK.md](BENCHMARK.md).
25
25
  Exit code is non-zero with a message on failure.
26
26
 
27
27
  `cargo test --manifest-path compiler/game/web-test/Cargo.toml` runs the same check on
28
- `examples/games/orbitrunner/OrbitRunner.plum`, `examples/games/balloonpop/BalloonPop.plum` and `fixtures/stress_state_view.plum`, plus WebKit runs and a record-and-replay run (Orbit Runner recorded at `?record` with keys and clicks, then replayed at `?replay=` in two pages, one pressing other keys: both must end on the same frame and stay there); each skips with a note if its browser is not installed.
28
+ `examples/games/orbitrunner/OrbitRunner.plum`, `examples/games/balloonpop/BalloonPop.plum` and `fixtures/stress_state_view.plum`, plus WebKit runs, Orbit Runner with `--stall-adapter`, and a record-and-replay run (Orbit Runner recorded at `?record` with keys and clicks, then replayed at `?replay=` in two pages, one pressing other keys: both must end on the same frame and stay there); each skips with a note if its browser is not installed. The checks take turns, one browser at a time: several software-WebGPU browsers at once starve each other of frames.
compiler/game/web-test/src/lib.rs CHANGED
@@ -62,6 +62,11 @@ pub struct Options {
62
62
  pub expect_pixels: Vec<ExpectPixel>,
63
63
  /// Destroy the GPU device from the page after a few frames and require rendering to resume.
64
64
  pub lose_device: bool,
65
+ /// Hold every `navigator.gpu.requestAdapter()` unanswered until the harness lets it go:
66
+ /// the page must say that WebGPU did not answer (the bridge's message and
67
+ /// `console.error`) and stay unstarted; then the adapter is let through, and the game
68
+ /// must start, the message go, and the rest of the check pass.
69
+ pub stall_adapter: bool,
65
70
  /// Pass `--no-fbip` to `plum build`.
66
71
  pub no_fbip: bool,
67
72
  /// Pass `--no-fusion` to `plum build`.
@@ -84,6 +89,7 @@ impl Default for Options {
84
89
  uncapped: false,
85
90
  dpr: None,
86
91
  lose_device: false,
92
+ stall_adapter: false,
87
93
  no_fbip: false,
88
94
  no_fusion: false,
89
95
  expect_pixels: Vec::new(),
@@ -437,6 +443,74 @@ async fn check(port: u16, opts: &Options) -> Result<String, String> {
437
443
 
438
444
  const UNSUPPORTED_MESSAGE: &str = "WebGPU is not supported in this browser";
439
445
 
446
+ /// The start of what the bridge shows and logs when WebGPU's adapter or device has not
447
+ /// answered within its wait, and the line it logs when it then does.
448
+ const STALL_MESSAGE: &str = "WebGPU did not answer within";
449
+ const STALL_ERROR: &str = "console.error: WebGPU did not answer within";
450
+ const STALL_ANSWERED: &str = "WebGPU answered after";
451
+
452
+ /// `--stall-adapter`: every `requestAdapter()` waits until `__plumReleaseAdapter()`.
453
+ const STALL_ADAPTER: &str = r#"
454
+ (() => {
455
+ if (typeof GPU === "undefined") return;
456
+ const ask = GPU.prototype.requestAdapter;
457
+ let release;
458
+ const gate = new Promise((r) => { release = r; });
459
+ window.__plumReleaseAdapter = () => { release(); return true; };
460
+ GPU.prototype.requestAdapter = function (...a) { return gate.then(() => ask.apply(this, a)); };
461
+ })();
462
+ "#;
463
+
464
+ /// The page's errors, less the bridge's "did not answer" error when WebGPU then answered
465
+ /// (a slow adapter under load, or `--stall-adapter`): the page recovered from it.
466
+ pub(crate) fn real_errors(errors: &[String], logs: &[String]) -> Vec<String> {
467
+ let answered = logs.iter().any(|l| l.contains(STALL_ANSWERED));
468
+ errors.iter().filter(|e| !(answered && e.starts_with(STALL_ERROR))).cloned().collect()
469
+ }
470
+
471
+ /// `--stall-adapter`: with the adapter held, the page must show and log that WebGPU did not
472
+ /// answer and not start; once it is let through, the game must start and the message go.
473
+ async fn check_stalled(page: &playwright_rs::protocol::Page, logs: &Arc<Mutex<Vec<String>>>) -> Result<(), String> {
474
+ let text = || async { page.evaluate::<(), String>("() => document.body.innerText", None).await.unwrap_or_default() };
475
+ let mut shown = false;
476
+ for _ in 0..60 {
477
+ if text().await.contains(STALL_MESSAGE) {
478
+ shown = true;
479
+ break;
480
+ }
481
+ tokio::time::sleep(Duration::from_millis(250)).await;
482
+ }
483
+ let console = || logs.lock().unwrap().join("\n");
484
+ if !shown {
485
+ return Err(format!("--stall-adapter: the page never showed '{STALL_MESSAGE} ..'\n--- console ---\n{}", console()));
486
+ }
487
+ if !logs.lock().unwrap().iter().any(|l| l.starts_with(STALL_ERROR)) {
488
+ return Err(format!("--stall-adapter: no '{STALL_ERROR} ..' log\n--- console ---\n{}", console()));
489
+ }
490
+ let early: Option<String> = page.evaluate("() => window.plumRenderer || null", None::<&()>).await.unwrap_or(None);
491
+ if early.is_some() {
492
+ return Err("--stall-adapter: the page set plumRenderer with the adapter held".to_string());
493
+ }
494
+ let released: bool = page.evaluate("() => window.__plumReleaseAdapter ? window.__plumReleaseAdapter() : false", None::<&()>).await.unwrap_or(false);
495
+ if !released {
496
+ return Err("--stall-adapter: the page had no held adapter to let go (no GPU?)".to_string());
497
+ }
498
+ for _ in 0..60 {
499
+ let renderer: Option<String> = page.evaluate("() => window.plumRenderer || null", None::<&()>).await.unwrap_or(None);
500
+ if renderer.is_some() {
501
+ if text().await.contains(STALL_MESSAGE) {
502
+ return Err("--stall-adapter: the game started but the message stayed".to_string());
503
+ }
504
+ if !logs.lock().unwrap().iter().any(|l| l.contains(STALL_ANSWERED)) {
505
+ return Err(format!("--stall-adapter: no '{STALL_ANSWERED} ..' log\n--- console ---\n{}", console()));
506
+ }
507
+ return Ok(());
508
+ }
509
+ tokio::time::sleep(Duration::from_millis(250)).await;
510
+ }
511
+ Err(format!("--stall-adapter: the game did not start once the adapter was let through\n--- console ---\n{}", console()))
512
+ }
513
+
440
514
  /// The page has no `navigator.gpu`: it must say so, plum.wasm must still load and
441
515
  /// initialise (`plumWasmProbe` is "ok"), and nothing else may have gone wrong.
442
516
  async fn check_unsupported(
@@ -528,6 +602,9 @@ async fn check_page(browser: &playwright_rs::protocol::Browser, port: u16, opts:
528
602
  if opts.expect_unsupported_webgpu {
529
603
  page.add_init_script("delete Navigator.prototype.gpu;").await.map_err(pe("init script"))?;
530
604
  }
605
+ if opts.stall_adapter {
606
+ page.add_init_script(STALL_ADAPTER).await.map_err(pe("init script"))?;
607
+ }
531
608
  if opts.no_module_introspection {
532
609
  page.add_init_script(NO_MODULE_INTROSPECTION).await.map_err(pe("init script"))?;
533
610
  }
@@ -536,6 +613,9 @@ async fn check_page(browser: &playwright_rs::protocol::Browser, port: u16, opts:
536
613
  // instantiate and initialise plum.wasm and report the outcome in `plumWasmProbe`.
537
614
  page.add_init_script("window.__plumWasmProbe = true;").await.map_err(pe("init script"))?;
538
615
  page.goto(&format!("http://127.0.0.1:{port}/"), None).await.map_err(pe("goto"))?;
616
+ if opts.stall_adapter {
617
+ check_stalled(&page, &logs).await?;
618
+ }
539
619
 
540
620
  // Give the wasm time to load, then provide a user gesture on the canvas.
541
621
  tokio::time::sleep(Duration::from_secs_f64((opts.frames_wait / 2.0).min(3.0))).await;
@@ -607,7 +687,7 @@ async fn check_page(browser: &playwright_rs::protocol::Browser, port: u16, opts:
607
687
  let (a, b) = (decode(&png1)?, decode(&png2)?);
608
688
  let colours = distinct_colours(&b, 1000);
609
689
  let diff = differing_pixels(&a, &b);
610
- let errs = errors.lock().unwrap().clone();
690
+ let errs = real_errors(&errors.lock().unwrap(), &logs.lock().unwrap());
611
691
  let mut failures_pre: Vec<String> = vec![];
612
692
 
613
693
  let mut report = format!(
@@ -657,6 +737,9 @@ async fn check_page(browser: &playwright_rs::protocol::Browser, port: u16, opts:
657
737
  }
658
738
  }
659
739
  }
740
+ if opts.stall_adapter {
741
+ report.push_str("\nstalled adapter: the page said WebGPU did not answer, then started once it did");
742
+ }
660
743
  if opts.lose_device {
661
744
  report.push_str(if loss_failure.is_none() { "\ndevice loss: destroyed, restored, rendering resumed" } else { "\ndevice loss: FAILED" });
662
745
  }
@@ -730,18 +813,22 @@ async fn record_and_replay_at(port: u16, dir: &Path) -> Result<String, String> {
730
813
  out
731
814
  }
732
815
 
816
+ type Lines = Arc<Mutex<Vec<String>>>;
817
+
733
- /// A page at `query` that collects its errors.
818
+ /// A page at `query` that collects its errors and its console lines.
734
- async fn open_page(browser: &playwright_rs::protocol::Browser, port: u16, query: &str) -> Result<(playwright_rs::protocol::Page, Arc<Mutex<Vec<String>>>), String> {
819
+ async fn open_page(browser: &playwright_rs::protocol::Browser, port: u16, query: &str) -> Result<(playwright_rs::protocol::Page, Lines, Lines), String> {
735
820
  let page = browser.new_page().await.map_err(pe("new page"))?;
736
- let errors: Arc<Mutex<Vec<String>>> = Arc::default();
821
+ let errors: Lines = Arc::default();
822
+ let logs: Lines = Arc::default();
737
823
  {
738
- let errors = errors.clone();
824
+ let (errors, logs) = (errors.clone(), logs.clone());
739
825
  page.on_console(move |m| {
740
- let errors = errors.clone();
826
+ let (errors, logs) = (errors.clone(), logs.clone());
741
827
  async move {
742
828
  if m.type_() == "error" {
743
829
  errors.lock().unwrap().push(format!("console.error: {}", m.text()));
744
830
  }
831
+ logs.lock().unwrap().push(format!("console.{}: {}", m.type_(), m.text()));
745
832
  Ok(())
746
833
  }
747
834
  })
@@ -762,7 +849,7 @@ async fn open_page(browser: &playwright_rs::protocol::Browser, port: u16, query:
762
849
  }
763
850
  page.goto(&format!("http://127.0.0.1:{port}/{query}"), None).await.map_err(pe("goto"))?;
764
851
  tokio::time::sleep(Duration::from_secs(2)).await;
765
- Ok((page, errors))
852
+ Ok((page, errors, logs))
766
853
  }
767
854
 
768
855
  /// Holds `key` for `secs` and clicks at (x, y).
@@ -775,12 +862,12 @@ async fn play_some(page: &playwright_rs::protocol::Page, key: &str, secs: f64, x
775
862
  }
776
863
 
777
864
  async fn record_then_replay(browser: &playwright_rs::protocol::Browser, port: u16, dir: &Path) -> Result<String, String> {
778
- let (rec, rec_errors) = open_page(browser, port, "?record").await?;
865
+ let (rec, rec_errors, rec_logs) = open_page(browser, port, "?record").await?;
779
866
  play_some(&rec, "ArrowRight", 1.0, 300.0, 200.0).await?;
780
867
  play_some(&rec, "ArrowDown", 0.7, 500.0, 300.0).await?;
781
868
  play_some(&rec, "Space", 0.3, 200.0, 400.0).await?;
782
869
  let text: String = rec.evaluate("() => globalThis.plumReplay ? globalThis.plumReplay() : ''", None::<&()>).await.map_err(pe("plumReplay"))?;
783
- let errs = rec_errors.lock().unwrap().clone();
870
+ let errs = real_errors(&rec_errors.lock().unwrap(), &rec_logs.lock().unwrap());
784
871
  if !errs.is_empty() {
785
872
  return Err(format!("recording page: {errs:?}"));
786
873
  }
@@ -792,10 +879,14 @@ async fn record_then_replay(browser: &playwright_rs::protocol::Browser, port: u1
792
879
  return Err(format!("the recording lacks the held arrow or the click ({ticks} ticks)"));
793
880
  }
794
881
  std::fs::write(dir.join("replay.txt"), &text).map_err(|e| e.to_string())?;
882
+ // The recording page is done with: closed, not left running beside the replays. Under
883
+ // load, the third software-WebGPU page in one Chromium could wait for ever on
884
+ // navigator.gpu.requestAdapter(), so the noisy replay never started and stayed black.
885
+ rec.close().await.map_err(pe("close recording page"))?;
795
886
 
796
887
  let wait = Duration::from_secs_f64(ticks as f64 / 60.0 * 2.0 + 3.0);
797
- let (quiet, quiet_errors) = open_page(browser, port, "?replay=replay.txt").await?;
888
+ let (quiet, quiet_errors, quiet_logs) = open_page(browser, port, "?replay=replay.txt").await?;
798
- let (noisy, noisy_errors) = open_page(browser, port, "?replay=replay.txt").await?;
889
+ let (noisy, noisy_errors, noisy_logs) = open_page(browser, port, "?replay=replay.txt").await?;
799
890
  play_some(&noisy, "ArrowLeft", 0.5, 100.0, 100.0).await?;
800
891
  play_some(&noisy, "Enter", 0.3, 400.0, 250.0).await?;
801
892
  tokio::time::sleep(wait).await;
@@ -804,8 +895,14 @@ async fn record_then_replay(browser: &playwright_rs::protocol::Browser, port: u1
804
895
  tokio::time::sleep(Duration::from_millis(500)).await;
805
896
  let a2 = decode(&quiet.screenshot(None).await.map_err(pe("screenshot"))?)?;
806
897
  let mut failures = Vec::new();
807
- for (name, errs) in [("quiet replay", &quiet_errors), ("noisy replay", &noisy_errors)] {
898
+ for (name, page) in [("quiet replay", &quiet), ("noisy replay", &noisy)] {
899
+ let renderer: Option<String> = page.evaluate("() => globalThis.plumRenderer || null", None::<&()>).await.unwrap_or(None);
900
+ if renderer.is_none() {
901
+ failures.push(format!("{name}: the page never started (no plumRenderer: WebGPU did not answer?)"));
902
+ }
903
+ }
904
+ for (name, errs, logs) in [("quiet replay", &quiet_errors, &quiet_logs), ("noisy replay", &noisy_errors, &noisy_logs)] {
808
- let errs = errs.lock().unwrap().clone();
905
+ let errs = real_errors(&errs.lock().unwrap(), &logs.lock().unwrap());
809
906
  if !errs.is_empty() {
810
907
  failures.push(format!("{name}: {errs:?}"));
811
908
  }
compiler/game/web-test/src/main.rs CHANGED
@@ -3,7 +3,7 @@ use std::path::PathBuf;
3
3
 
4
4
  const USAGE: &str = "usage: plum-web-test <file.plum> [--frames-wait SECS] [--screenshot OUT.png] [--require-audio]\n [--assets DIR] [--headed] [--measure SECS] [--uncapped] [--json] [--no-fbip] [--no-fusion]
5
5
  [--browser chromium|webkit] [--expect-unsupported-webgpu] [--no-module-introspection]
6
- [--dpr N] [--lose-device] [--expect-pixel x,y,r,g,b[,tol]]...";
6
+ [--dpr N] [--lose-device] [--stall-adapter] [--expect-pixel x,y,r,g,b[,tol]]...";
7
7
 
8
8
  #[tokio::main]
9
9
  async fn main() {
@@ -30,6 +30,7 @@ async fn main() {
30
30
  opts.expect_pixels.push(ExpectPixel::parse(&v).unwrap_or_else(|e| fail(&e)));
31
31
  }
32
32
  "--lose-device" => opts.lose_device = true,
33
+ "--stall-adapter" => opts.stall_adapter = true,
33
34
  "--dpr" => opts.dpr = Some(args.next().and_then(|v| v.parse().ok()).unwrap_or_else(|| fail("--dpr needs a number"))),
34
35
  "--measure" => opts.measure = Some(args.next().and_then(|v| v.parse().ok()).unwrap_or_else(|| fail("--measure needs a number of seconds"))),
35
36
  "--assets" => opts.assets = Some(args.next().map(PathBuf::from).unwrap_or_else(|| fail("--assets needs a directory"))),
compiler/game/web-test/tests/web_check.rs CHANGED
@@ -1,5 +1,12 @@
1
1
  use plum_web_test::{chromium_installed, repo_root, run, webkit_installed, Browser, Options};
2
2
 
3
+ /// One browser at a time: several software-WebGPU browsers at once starve each other of
4
+ /// frames, and the checks that count frames or wait for the page to start then fail at random.
5
+ fn one_browser() -> std::sync::MutexGuard<'static, ()> {
6
+ static ONE: std::sync::Mutex<()> = std::sync::Mutex::new(());
7
+ ONE.lock().unwrap_or_else(|e| e.into_inner())
8
+ }
9
+
3
10
  #[test]
4
11
  fn orb_run_renders_and_animates() {
5
12
  orb_run("examples/games/orbitrunner/OrbitRunner.plum");
@@ -44,6 +51,7 @@ fn chromium_runs_without_module_introspection() {
44
51
  return;
45
52
  }
46
53
  let opts = Options { no_module_introspection: true, ..Options::default() };
54
+ let _one = one_browser();
47
55
  let rt = tokio::runtime::Runtime::new().unwrap();
48
56
  let report = rt.block_on(run(&repo_root().join("examples/games/orbitrunner/OrbitRunner.plum"), &opts)).unwrap_or_else(|e| panic!("{e}"));
49
57
  println!("{report}");
@@ -56,6 +64,7 @@ fn webkit_runs_without_module_introspection() {
56
64
  return;
57
65
  }
58
66
  let opts = Options { browser: Browser::Webkit, no_module_introspection: true, ..Options::default() };
67
+ let _one = one_browser();
59
68
  let rt = tokio::runtime::Runtime::new().unwrap();
60
69
  let report = rt.block_on(run(&repo_root().join("examples/games/orbitrunner/OrbitRunner.plum"), &opts)).unwrap_or_else(|e| {
61
70
  assert!(!e.contains("unable to produce import descriptors"), "{e}");
@@ -64,6 +73,21 @@ fn webkit_runs_without_module_introspection() {
64
73
  println!("{report}");
65
74
  }
66
75
 
76
+ /// WebGPU's adapter request held unanswered: the page says WebGPU did not answer and logs
77
+ /// it, then, once the adapter comes, starts the game and takes the message away.
78
+ #[test]
79
+ fn chromium_says_when_webgpu_does_not_answer_and_starts_when_it_does() {
80
+ if !chromium_installed() {
81
+ eprintln!("SKIP: Playwright Chromium not installed (see compiler/game/web-test/README.md)");
82
+ return;
83
+ }
84
+ let opts = Options { stall_adapter: true, ..Options::default() };
85
+ let _one = one_browser();
86
+ let rt = tokio::runtime::Runtime::new().unwrap();
87
+ let report = rt.block_on(run(&repo_root().join("examples/games/orbitrunner/OrbitRunner.plum"), &opts)).unwrap_or_else(|e| panic!("{e}"));
88
+ assert!(report.contains("stalled adapter: the page said WebGPU did not answer, then started once it did"), "{report}");
89
+ }
90
+
67
91
  #[test]
68
92
  fn webkit_without_webgpu_loads_the_wasm_and_says_so() {
69
93
  if !webkit_installed() {
@@ -71,6 +95,7 @@ fn webkit_without_webgpu_loads_the_wasm_and_says_so() {
71
95
  return;
72
96
  }
73
97
  let opts = Options { browser: Browser::Webkit, expect_unsupported_webgpu: true, no_module_introspection: true, ..Options::default() };
98
+ let _one = one_browser();
74
99
  let rt = tokio::runtime::Runtime::new().unwrap();
75
100
  let report = rt.block_on(run(&repo_root().join("examples/games/orbitrunner/OrbitRunner.plum"), &opts)).unwrap_or_else(|e| panic!("{e}"));
76
101
  assert!(report.contains("plum.wasm load probe: ok"), "{report}");
@@ -81,6 +106,7 @@ fn orb_run(example: &str) {
81
106
  eprintln!("SKIP: Playwright Chromium not installed (see compiler/game/web-test/README.md)");
82
107
  return;
83
108
  }
109
+ let _one = one_browser();
84
110
  let rt = tokio::runtime::Runtime::new().unwrap();
85
111
  let file = repo_root().join(example);
86
112
  let report = rt.block_on(run(&file, &Options::default())).unwrap_or_else(|e| panic!("{e}"));
@@ -153,6 +179,7 @@ fn render_target_pixels() {
153
179
  }
154
180
  let pixels = ["130,130,255,0,0", "196,196,0,255,0", "130,196,51,51,51", "450,150,102,153,204", "600,150,26,51,26", "750,150,153,153,153", "900,150,153,26,26", "408,308,0,0,255", "408,408,153,26,26", "650,490,255,255,255", "690,450,51,51,51"];
155
181
  let opts = Options { expect_pixels: pixels.iter().map(|p| plum_web_test::ExpectPixel::parse(p).unwrap()).collect(), ..Options::default() };
182
+ let _one = one_browser();
156
183
  let rt = tokio::runtime::Runtime::new().unwrap();
157
184
  let file = repo_root().join("compiler/game/web-test/fixtures/rendertarget.plum");
158
185
  let report = rt.block_on(run(&file, &opts)).unwrap_or_else(|e| panic!("{e}"));
@@ -165,6 +192,7 @@ fn a_recorded_run_replays_in_the_browser() {
165
192
  eprintln!("SKIP: Playwright Chromium not installed (see compiler/game/web-test/README.md)");
166
193
  return;
167
194
  }
195
+ let _one = one_browser();
168
196
  let rt = tokio::runtime::Runtime::new().unwrap();
169
197
  let report = rt.block_on(plum_web_test::record_and_replay(&repo_root().join("examples/games/orbitrunner/OrbitRunner.plum"))).unwrap_or_else(|e| panic!("{e}"));
170
198
  println!("{report}");
compiler/game/web/plum_bridge.js CHANGED
@@ -17,6 +17,11 @@
17
17
  const IMAGE_EXT = /\.(png|jpe?g|gif|webp|bmp)$/i;
18
18
  const MAX_TEXTURE = 8192; // WebGPU's default maxTextureDimension2D
19
19
  const SOUND_EXT = /\.(wav|ogg)$/i;
20
+ // How long the page waits for WebGPU's adapter and device before it says they have not
21
+ // answered. A healthy request answers in well under a second, a software adapter in a
22
+ // cold browser included; 5 s leaves room for a slow first driver start without leaving a
23
+ // player in front of a black page for long. The page goes on waiting after it.
24
+ const GPU_WAIT_MS = 5000;
20
25
  // --- paths --------------------------------------------------------------------
21
26
 
22
27
  // The asset-root-relative form of `p`, or null if it is empty, absolute or escapes the root.
@@ -1231,12 +1236,26 @@ fn shade(i: VOut) -> vec4f {
1231
1236
  if (canvas.height !== h) canvas.height = h;
1232
1237
  };
1233
1238
  size();
1234
- const message = (text, color) =>
1239
+ const message = (text, color) => {
1235
- document.body.append(Object.assign(document.createElement("pre"), { textContent: text, style: "position:fixed;top:0;left:0;color:" + color + ";margin:8px;font-size:18px" }));
1240
+ const el = Object.assign(document.createElement("pre"), { textContent: text, style: "position:fixed;top:0;left:0;color:" + color + ";margin:8px;font-size:18px" });
1241
+ document.body.append(el);
1242
+ return el;
1243
+ };
1236
1244
 
1237
1245
  let backend = null;
1238
1246
  const env = { glyph: () => null, atlas: null };
1239
1247
  const b = makeBatcher({ glyph: (cp) => env.glyph(cp), get atlas() { return env.atlas; } });
1248
+ // A request for the adapter or the device that never answers (seen with several
1249
+ // software-WebGPU pages under load) would leave the page black and silent: after
1250
+ // GPU_WAIT_MS the page says so and logs an error, and goes on waiting, so an adapter
1251
+ // that comes late still starts the game and takes the message away.
1252
+ const asked = performance.now();
1253
+ let waiting = null;
1254
+ const timer = setTimeout(() => {
1255
+ const msg = "WebGPU did not answer within " + GPU_WAIT_MS / 1000 + " s";
1256
+ console.error(msg + "; still waiting");
1257
+ waiting = message(msg + ". Still waiting; if the page stays black, close other pages that use the GPU and reload.", "#f55");
1258
+ }, GPU_WAIT_MS);
1240
1259
  try {
1241
1260
  backend = await makeWebGPU(canvas, b, (reason, restored) => {
1242
1261
  if (restored) {
@@ -1248,6 +1267,12 @@ fn shade(i: VOut) -> vec4f {
1248
1267
  });
1249
1268
  } catch (e) {
1250
1269
  console.error("WebGPU failed to start:", e);
1270
+ } finally {
1271
+ clearTimeout(timer);
1272
+ }
1273
+ if (waiting) {
1274
+ waiting.remove();
1275
+ if (backend) console.log("WebGPU answered after " + ((performance.now() - asked) / 1000).toFixed(1) + " s");
1251
1276
  }
1252
1277
  if (!backend) {
1253
1278
  const msg = "WebGPU is not supported in this browser";
docs/backlog.md CHANGED
@@ -10,7 +10,6 @@ The retained scene tree was replaced by master's screen view in functional form:
10
10
  - **Pass re-check failures met on the way** (fixed in std, not in the compiler): fusion devirtualising `s.frames().onDemand()` on a `Screen` with one implementer mistypes the fused call (std matches on `frames()` instead); trmc on `List.map` with a coercion (`xs.map(|m| m)` into a `List<View>`) fails its re-check (`view.all(xs)` lifts through a typed helper); dead-code removal is reverted when it removes every type a downcast to a trait could match (it met `Container as c`, which master has since folded into `view` too).
11
11
  - **Frames on demand in the hosts**: `Game.idle()` works, but no host is told (master's `frameIdle` extern, and the browser skipping the draw and waiting for input).
12
12
  - **Development keys** (`plum run --dev`, master's `remakeGame` host call): a game offers undo only through its own effects.
13
- - **`plum run <folder>`** (master runs a game's folder; here the main file is named).
14
13
  - **Master's other games** (`clockwork`, `menu`) are not ported.
15
14
  - **The view's cost**: each frame makes the view's list and items. `benchmarks/screen_views` (`orbit.plum`, `scale.plum`, master's drivers) times it; not yet run against master. Master's stepping walk makes the view once more a tick and each actor's view; this branch's `stepped` makes neither, so the two `update` timings are not the same work (`scale.plum`'s header says so).
16
15
  - **Stepping without the screen naming its actors**: the game cannot step an actor found in a view, as the screen holding it is a value; each screen maps its own fields in `stepped`. A lens per field, or a view walk that rebuilds the screen, would let std do it; not designed.
docs/game.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # The game engine
2
2
 
3
- Write a game in Plum and run it in the browser on Plum's own WebGPU renderer. It needs a browser with WebGPU: Chrome, Edge, Firefox or Safari 26+.
3
+ Write a game in Plum and run it in the browser on Plum's own WebGPU renderer. It needs a browser with WebGPU: Chrome, Edge, Firefox or Safari 26+. Without it the page says "WebGPU is not supported in this browser"; if WebGPU is there but does not answer within 5 s (seen with several software-WebGPU pages under load), the page says so and goes on waiting, and an answer that comes late still starts the game.
4
4
 
5
5
  ![the example game](game.png)
6
6
 
@@ -10,7 +10,7 @@ Write a game in Plum and run it in the browser on Plum's own WebGPU renderer. It
10
10
  plum run examples/games/orbitrunner/OrbitRunner.plum
11
11
  ```
12
12
 
13
- This builds the game, starts a local server and opens your browser. Steer with the arrow keys or WASD, collect the orbs and dodge the mines; when the game is over, Enter or R plays again. Press a key first, because browsers only start sound after you interact with the page. `examples/games/balloonpop/BalloonPop.plum` is the other example game: press the balloons, and Z or Backspace takes the last press back.
13
+ This builds the game, starts a local server and opens your browser. `plum run examples/games/orbitrunner` does the same: given a folder, `plum run` and `plum build` take the one `.plum` file in it with a `fun main` (none, or more than one, is an error that says so). Steer with the arrow keys or WASD, collect the orbs and dodge the mines; when the game is over, Enter or R plays again. Press a key first, because browsers only start sound after you interact with the page. `examples/games/balloonpop/BalloonPop.plum` is the other example game: press the balloons, and Z or Backspace takes the last press back.
14
14
 
15
15
  ## A game's files
16
16
 
@@ -469,7 +469,7 @@ The engine has master's shape at e91c40ce (`View` and `Actor`, `Screen` with its
469
469
 
470
470
  The same on both: `View` (`place`, `view`, `visible`, `paintSelf`, the shared empty default), the walks (`paintView`, `paintCulled`, `drawnIn`, `hitIn`, `worldIn`), `Screen` (`name`, `view`, `hud(window)`, `steps`, `camera(base)`, `size`, `viewport`, `culls`, `busy`, `background`, `transition`, `frames`; no `enter`, `leave`, `resize`, `draw` or `fresh`), `Control` (`goTo`, `exit`, `undo`, `redo`, `rewindTo`; no `restart`), pointer events dropped during a transition, each screen on its own background in one, the ready-made views (Circle by its centre, `Label(align:)`, `Overlay` with a required size hit inside its box, `Sprite.frameAt`), `gfx.drawRectEx` and `drawTextEx` in std, the browser, the native host and the recorder, the input (`ButtonDown`, `ButtonUp`, `Held.buttons`, the extra `Key`s, `Input.axis`, `isMouseDown(b)`, `isMousePressed(b)`, `isMouseReleased(b)`, the replay's button mask and `B`/`b` events), `math.near`, `Game.pixels`, `frameDrawn()`, `drawList()`, `camera(i)`, `toWorld`, `toScreen`, `visible(i)`, `travelAsked`, and Orbit Runner's state checksum (925878360).
471
471
 
472
- Not ported: master's frames-on-demand host call (`frameIdle`), its development keys (`plum run --dev`, `remakeGame`, `TravelKeys`), `plum run` taking a game's folder, and its `clockwork` and `menu` games; see the [backlog](backlog.md). This branch keeps `examples/games/clicks.plum` and `two_screens.plum`, which master doesn't have.
472
+ Not ported: master's frames-on-demand host call (`frameIdle`), its development keys (`plum run --dev`, `remakeGame`, `TravelKeys`), and its `clockwork` and `menu` games; see the [backlog](backlog.md). This branch keeps `examples/games/clicks.plum` and `two_screens.plum`, which master doesn't have.
473
473
 
474
474
  ## Publishing
475
475
 
docs/tools.md CHANGED
@@ -6,7 +6,7 @@
6
6
 
7
7
  | Command | What it does |
8
8
  |---|---|
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 |
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. Given a folder (`plum run examples/games/orbitrunner`), it runs the one `.plum` file in the folder with a `fun main`; `plum build` does the same |
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
12
  | `plum check file.plum dir/` | Type-check files and folders without compiling or running them |