plum

#treesitter#compiler#wasm

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

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


d3dabfb — Peter John 2026-11-10T11:38:52+05:30
plum build executables: precompiled module, one build at a time, one crash line
compiler/cli/src/main.rs CHANGED
@@ -984,31 +984,50 @@ fn cmdBuild(
984
984
  let stem = file
985
985
  .file_stem()
986
986
  .ok_or_else(|| anyhow::anyhow!("invalid source file path {}", file.display()))?;
987
+ let runtime_dir = runtimeCrateDir();
988
+ if !runtime_dir.join("Cargo.toml").is_file() {
989
+ anyhow::bail!(
990
+ "plum build makes an executable by compiling the plum-runtime crate, which is not at {} (this plum was built from a source tree that moved or is gone)",
991
+ runtime_dir.display()
992
+ );
993
+ }
987
994
 
995
+ // The module, and the same module compiled ahead of time for this machine (the
996
+ // runtime falls back to compiling the wasm if it cannot use that copy).
997
+ let scratch = std::env::temp_dir().join(format!("plum-build-{}-{}", stem.to_string_lossy(), process::id()));
998
+ fs::create_dir_all(&scratch).with_context(|| format!("failed to create {}", scratch.display()))?;
999
+ let removeScratch = ScratchGuard(scratch.clone());
988
- let wasm_path = std::env::temp_dir().join(format!(
1000
+ let wasm_path = scratch.join("program.wasm");
989
- "plum-build-{}-{}.wasm",
990
- stem.to_string_lossy(),
991
- process::id()
992
- ));
993
- fs::write(&wasm_path, &wasm_bytes)
1001
+ let cwasm_path = scratch.join("program.cwasm");
994
- .with_context(|| format!("failed to write {}", wasm_path.display()))?;
1002
+ fs::write(&wasm_path, &wasm_bytes).with_context(|| format!("failed to write {}", wasm_path.display()))?;
1003
+ let precompiled = wasmtime::Engine::new(&plum_host::engineConfig())
1004
+ .and_then(|e| e.precompile_module(&wasm_bytes))
1005
+ .unwrap_or_default();
1006
+ fs::write(&cwasm_path, &precompiled).with_context(|| format!("failed to write {}", cwasm_path.display()))?;
995
- let wasm_abs_path = fs::canonicalize(&wasm_path)
1007
+ let wasm_abs_path = fs::canonicalize(&wasm_path)?;
1008
+ let cwasm_abs_path = fs::canonicalize(&cwasm_path)?;
1009
+
1010
+ // Builds share the runtime's target folder (so wasmtime compiles once): one at a
1011
+ // time, from the cargo build to the copy, so none copies another's program.
1012
+ let target = runtime_dir.join("target");
996
- .with_context(|| format!("failed to resolve {}", wasm_path.display()))?;
1013
+ fs::create_dir_all(&target).with_context(|| format!("failed to create {}", target.display()))?;
1014
+ let lock = fs::File::create(target.join("plum-build.lock")).context("failed to create the build lock")?;
1015
+ lock.lock().context("failed to take the build lock")?;
997
1016
 
998
- let runtime_dir = runtimeCrateDir();
999
1017
  eprintln!("building executable (embedding wasm via wasmtime)...");
1000
1018
  let status = process::Command::new("cargo")
1001
1019
  .args(["build", "--release", "--manifest-path"])
1002
1020
  .arg(runtime_dir.join("Cargo.toml"))
1003
1021
  .env("PLUM_WASM_PATH", &wasm_abs_path)
1022
+ .env("PLUM_CWASM_PATH", &cwasm_abs_path)
1023
+ .env("PLUM_RESULT_MAIN", if program.resultMain { "1" } else { "0" })
1004
1024
  .status()
1005
- .context("failed to run cargo — is it installed and on PATH?")?;
1025
+ .context("failed to run cargo: plum build needs cargo on PATH to make an executable")?;
1006
- let _ = fs::remove_file(&wasm_path);
1007
1026
  if !status.success() {
1008
1027
  anyhow::bail!("cargo build failed");
1009
1028
  }
1010
1029
 
1011
- let built_bin = runtime_dir.join("target/release/plum-runtime");
1030
+ let built_bin = target.join("release/plum-runtime");
1012
1031
  let out_path = output.unwrap_or_else(|| std::path::PathBuf::from(stem));
1013
1032
  fs::copy(&built_bin, &out_path).with_context(|| {
1014
1033
  format!(
@@ -1017,11 +1036,22 @@ fn cmdBuild(
1017
1036
  out_path.display()
1018
1037
  )
1019
1038
  })?;
1039
+ drop(lock);
1040
+ drop(removeScratch);
1020
1041
 
1021
1042
  eprintln!("built {} → {}", file.display(), out_path.display());
1022
1043
  Ok(())
1023
1044
  }
1024
1045
 
1046
+ /// A folder deleted when dropped.
1047
+ struct ScratchGuard(std::path::PathBuf);
1048
+
1049
+ impl Drop for ScratchGuard {
1050
+ fn drop(&mut self) {
1051
+ let _ = fs::remove_dir_all(&self.0);
1052
+ }
1053
+ }
1054
+
1025
1055
  #[cfg(test)]
1026
1056
  mod runtime_path_tests {
1027
1057
  /// `plum build` hands this manifest to cargo, so a moved crate must fail here.
compiler/cli/tests/cli/main_result_test.rs CHANGED
@@ -123,3 +123,23 @@ fn lowersOnTheAstNotTheText() {
123
123
  let mut plain = plum_test_support::parse("fun main() -> Int = 1\n");
124
124
  assert!(!plum_core::main_result::lowerResultMain(&mut plain));
125
125
  }
126
+
127
+ /// A built executable reports a `Result` main's `Err` once (no trap report after the
128
+ /// `crash:` line), and a trap as one clean line.
129
+ #[test]
130
+ fn builtExecutablesReportACrashOnce() {
131
+ let dir = crate::common::Scratch::new("built_crash");
132
+ let err = dir.join("err.plum");
133
+ std::fs::write(&err, "module app\nimport std/Result\nimport std/Int\nimport std/Io\n\nenum AppError =\n | Bad\n\nfun main(io: Io) -> Result[Int, AppError] =\n Err(error: Bad)\n").unwrap();
134
+ let div = dir.join("div.plum");
135
+ std::fs::write(&div, "import std/Int\n\nfun main() -> Int =\n z := 0\n 1 / z\n").unwrap();
136
+ for (src, want) in [(&err, "crash: Bad"), (&div, "crash: division by zero in main")] {
137
+ let exe = src.with_extension("");
138
+ let out = Command::new(plumBin()).current_dir(crate::common::root()).arg("build").arg(src).arg("-o").arg(&exe).output().unwrap();
139
+ assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
140
+ let run = Command::new(&exe).output().unwrap();
141
+ let stderr = String::from_utf8_lossy(&run.stderr);
142
+ assert_eq!(run.status.code(), Some(1), "{stderr}");
143
+ assert_eq!(stderr.trim(), want, "{stderr}");
144
+ }
145
+ }
compiler/runtime/src/main.rs CHANGED
@@ -2,20 +2,40 @@
2
2
  // mirrors this file's host-import logic), not Rust's idiomatic snake_case.
3
3
  #![allow(non_snake_case)]
4
4
 
5
- // Embeds a Plum-compiled wasm module (path supplied via the PLUM_WASM_PATH
5
+ // Embeds a Plum-compiled wasm module and runs its `main` export under wasmtime, so
6
- // env var at build time by `plum build`) and runs its `main` export under
7
- // wasmtime, so the result is a single native executable with no runtime
6
+ // the result is a single native executable with no runtime dependency on a
8
- // dependency on a `wasmtime` install or a separate .wasm file.
7
+ // `wasmtime` install or a separate .wasm file. `plum build` sets, at build time:
8
+ // PLUM_WASM_PATH (the module), PLUM_CWASM_PATH (the same module compiled ahead of
9
+ // time for this machine, or an empty file) and PLUM_RESULT_MAIN (`1` when `main`
10
+ // returns a `Result`, whose `Err` already prints `crash: <variant>`).
9
11
  const WASM_BYTES: &[u8] = include_bytes!(env!("PLUM_WASM_PATH"));
12
+ const CWASM_BYTES: &[u8] = include_bytes!(env!("PLUM_CWASM_PATH"));
13
+ const RESULT_MAIN: Option<&str> = option_env!("PLUM_RESULT_MAIN");
14
+
15
+ /// A trap from `main`, printed once (a `crash` or a `Result` main's `Err` already said it).
16
+ fn reportTrap(trap: &wasmtime::Error) {
17
+ if RESULT_MAIN == Some("1") || plum_host::takeCrash().is_some() {
18
+ return;
19
+ }
20
+ let plain = |n: &str| n.split('@').next().unwrap_or(n).to_string();
21
+ match plum_host::trapReport(trap, &plain) {
22
+ Some(report) => eprintln!("{report}"),
23
+ None => eprintln!("error: {trap:#}"),
24
+ }
25
+ }
10
26
 
11
27
  fn main() {
12
- // GC + typed function references are required to load modules containing
13
- // Plum's structs/enums/strings/closures (see docs/superpowers/plans/2026-07-25-wasm-gc-migration.md).
14
28
  let engine = plum_host::engine();
15
29
  // `io.args()`: the executable's own arguments, without the program name.
16
30
  plum_host::setProgramArgs(std::env::args().skip(1).collect());
17
31
 
32
+ // The ahead-of-time copy skips compiling at every launch; wasmtime refuses it (and
33
+ // the wasm is compiled instead) if it was made by another wasmtime or configuration.
34
+ // SAFETY: `plum build` made these bytes with `Engine::precompile_module` from
35
+ // WASM_BYTES, under plum_host's engine configuration, and they are embedded in
36
+ // this executable, so they cannot be swapped or changed after the build.
37
+ let precompiled = (!CWASM_BYTES.is_empty()).then(|| unsafe { wasmtime::Module::deserialize(&engine, CWASM_BYTES) }.ok()).flatten();
18
- let module = wasmtime::Module::new(&engine, WASM_BYTES).expect("embedded wasm should be valid");
38
+ let module = precompiled.unwrap_or_else(|| wasmtime::Module::new(&engine, WASM_BYTES).expect("embedded wasm should be valid"));
19
39
  let mut store = wasmtime::Store::new(&engine, ());
20
40
  let imports = plum_host::hostImports(&mut store, &module, plum_host::Caps::all())
21
41
  .expect("host imports should resolve");
@@ -27,7 +47,7 @@ fn main() {
27
47
  match main.call(&mut store, ()) {
28
48
  Ok(result) => println!("{result}"),
29
49
  Err(trap) => {
30
- eprintln!("error: {trap}");
50
+ reportTrap(&trap);
31
51
  std::process::exit(1);
32
52
  }
33
53
  }
@@ -38,7 +58,7 @@ fn main() {
38
58
  .get_typed_func::<(), ()>(&mut store, "main")
39
59
  .expect("module has no `main` export with signature () -> i64 or () -> ()");
40
60
  if let Err(trap) = main.call(&mut store, ()) {
41
- eprintln!("error: {trap}");
61
+ reportTrap(&trap);
42
62
  std::process::exit(1);
43
63
  }
44
64
  }