Runtime abstraction + browser REPL
Decouple ForthVM from wasmtime via a Runtime trait so the same outer interpreter, compiler, and 200+ word definitions work on both native (wasmtime) and browser (js-sys WebAssembly API) backends. Runtime trait (runtime.rs): - HostAccess trait for memory/global ops inside host function closures - HostFn type: Box<dyn Fn(&mut dyn HostAccess) -> Result<()>> - Runtime trait: memory, globals, table, instantiate, call, register NativeRuntime (runtime_native.rs): - Wraps wasmtime Engine/Store/Memory/Table/Global/Func - CallerHostAccess bridges HostAccess to wasmtime Caller API - Feature-gated behind "native" (default) outer.rs refactor: - ForthVM<R: Runtime> — generic over execution backend - All 87 host functions converted from Func::new closures to HostFn - All memory access via rt.mem_read/write_*, global access via rt.get/set_* - Zero logic changes — pure API conversion wafer-core feature gates: - default = ["native"] includes wasmtime + all native modules - Without "native": pure Rust only (outer, codegen, optimizer, dictionary) Browser REPL (crates/web): - WebRuntime: js-sys WebAssembly.Memory/Table/Global/Module/Instance - WaferRepl: wasm-bindgen entry point (evaluate, data_stack, reset) - WebAssembly.Function with Safari fallback (wrapper module) - Frontend: dark terminal UI, word panel, init code editor, history - Build: wasm-pack build --target web All 452 tests pass (431 unit + 1 benchmark + 9 comparison + 11 compliance).
This commit is contained in:
@@ -2,27 +2,48 @@
|
||||
|
||||
## What is WAFER?
|
||||
|
||||
WAFER (WebAssembly Forth Engine in Rust) is an optimizing Forth 2012 compiler targeting WebAssembly. Currently a working Forth system with 200+ words, JIT compilation, 12 word sets at 100% compliance, and a full optimization pipeline (peephole, constant folding, inlining, strength reduction, DCE, tail calls, stack-to-local promotion with loop/IF support, self-recursive direct calls, consolidation). Beats gforth on all benchmarks in release mode.
|
||||
WAFER (WebAssembly Forth Engine in Rust) is an optimizing Forth 2012 compiler targeting WebAssembly. Currently a working Forth system with 200+ words, JIT compilation, 12 word sets at 100% compliance, and a full optimization pipeline (peephole, constant folding, inlining, strength reduction, DCE, tail calls, stack-to-local promotion with loop/IF support, self-recursive direct calls, consolidation). Beats gforth on all benchmarks in release mode. Includes a browser-based REPL via wasm-pack.
|
||||
|
||||
## Architecture
|
||||
|
||||
- Each Forth word compiles to its own WASM module via `wasm-encoder`
|
||||
- Modules share memory, globals (dsp/rsp), and a function table via wasmtime imports
|
||||
- IR-based compilation: Forth -> `Vec<IrOp>` -> WASM codegen -> wasmtime instantiation
|
||||
- Modules share memory, globals (dsp/rsp/fsp), and a function table via runtime imports
|
||||
- IR-based compilation: Forth -> `Vec<IrOp>` -> WASM codegen -> runtime instantiation
|
||||
- Dictionary: linked-list in a `Vec<u8>` buffer simulating WASM linear memory
|
||||
- Primitives: either IR-based (compiled to WASM) or host functions (Rust closures in wasmtime)
|
||||
- Primitives: either IR-based (compiled to WASM) or host functions (closures via `HostFn`)
|
||||
- **Runtime trait**: `ForthVM<R: Runtime>` is generic over the execution backend
|
||||
- `NativeRuntime` (wasmtime) -- CLI, tests, AOT compilation
|
||||
- `WebRuntime` (js-sys) -- browser REPL via wasm-pack
|
||||
|
||||
## Crate Structure
|
||||
|
||||
- `crates/core` -- compiler, optimizer, codegen, dictionary, runtime traits, outer interpreter
|
||||
- `crates/cli` -- CLI REPL with rustyline, `wafer build`/`wafer run` commands
|
||||
- `crates/web` -- browser REPL (wasm-bindgen entry point, WebRuntime, HTML/CSS/JS frontend)
|
||||
|
||||
## Key Files
|
||||
|
||||
- `crates/core/src/outer.rs` -- ForthVM: the main runtime, outer interpreter, compiler, all primitives
|
||||
- `crates/core/src/codegen.rs` -- IR-to-WASM translation, module generation, wasmtime execution tests
|
||||
- `crates/core/src/outer.rs` -- `ForthVM<R: Runtime>`: outer interpreter, compiler, all primitives
|
||||
- `crates/core/src/runtime.rs` -- `Runtime` + `HostAccess` traits (execution backend abstraction)
|
||||
- `crates/core/src/runtime_native.rs` -- `NativeRuntime`: wasmtime implementation (behind `native` feature)
|
||||
- `crates/core/src/codegen.rs` -- IR-to-WASM translation, module generation
|
||||
- `crates/core/src/dictionary.rs` -- Dictionary data structure with create/find/reveal
|
||||
- `crates/core/src/ir.rs` -- IrOp enum (the intermediate representation)
|
||||
- `crates/core/src/memory.rs` -- Memory layout constants (stack regions, dictionary base, etc.)
|
||||
- `crates/core/src/optimizer.rs` -- IR optimization passes (peephole, fold, inline, DCE, etc.)
|
||||
- `crates/core/src/config.rs` -- WaferConfig: unified optimization configuration
|
||||
- `crates/core/src/consolidate.rs` -- Consolidation recompiler (single-module direct calls)
|
||||
- `crates/core/boot.fth` -- Bootstrap Forth definitions loaded at startup
|
||||
- `crates/cli/src/main.rs` -- CLI REPL with rustyline
|
||||
- `crates/web/src/lib.rs` -- `WaferRepl` wasm-bindgen entry point
|
||||
- `crates/web/src/runtime_web.rs` -- `WebRuntime`: browser WebAssembly API via js-sys
|
||||
- `crates/web/www/` -- Frontend (index.html, style.css, app.js)
|
||||
|
||||
## Feature Flags (wafer-core)
|
||||
|
||||
- `default = ["native"]` -- includes wasmtime, NativeRuntime, runner, export, etc.
|
||||
- `native` -- enables `dep:wasmtime` and all native-only modules
|
||||
- No features -- pure Rust only (dictionary, IR, optimizer, codegen, outer interpreter). Used by `wafer-web`.
|
||||
|
||||
## Adding a New Word
|
||||
|
||||
@@ -35,8 +56,12 @@ self.register_primitive("WORD_NAME", false, vec![IrOp::Dup, IrOp::Mul])?;
|
||||
**Host function** (needs Rust logic -- I/O, dictionary manipulation, complex stack access):
|
||||
|
||||
```rust
|
||||
let func = Func::new(&mut self.store, func_type.clone(), move |mut caller, _params, _results| {
|
||||
// manipulate memory/globals directly
|
||||
let shared_state = Arc::clone(&self.some_field);
|
||||
let func: HostFn = Box::new(move |ctx: &mut dyn HostAccess| {
|
||||
let sp = ctx.get_dsp();
|
||||
let val = ctx.mem_read_i32(sp);
|
||||
// ... logic using ctx for memory/global access ...
|
||||
ctx.set_dsp(sp + CELL_SIZE);
|
||||
Ok(())
|
||||
});
|
||||
self.register_host_primitive("WORD_NAME", false, func)?;
|
||||
@@ -54,13 +79,20 @@ Handle in `interpret_token_immediate()` or `compile_token()` as a special case.
|
||||
|
||||
## Testing
|
||||
|
||||
- Run `cargo test --workspace` before committing (currently 427 unit + 1 benchmark + 11 compliance + 11 comparison)
|
||||
- Run `cargo test --workspace` before committing (currently 431 unit + 1 benchmark + 11 compliance + 9 comparison)
|
||||
- Forth 2012 compliance: `cargo test -p wafer-core --test compliance`
|
||||
- Cross-engine comparison (vs gforth): `cargo test -p wafer-core --test comparison`
|
||||
- Performance benchmarks (release mode): `cargo test -p wafer-core --test comparison -- --nocapture --ignored`
|
||||
- Test helper in outer.rs: `eval_output("forth code")` returns printed output as String
|
||||
- Test helper: `eval_stack("forth code")` returns data stack as Vec<i32>
|
||||
|
||||
## Web REPL
|
||||
|
||||
- Build: `cd crates/web && wasm-pack build --target web --out-dir www/pkg`
|
||||
- Serve: `python3 -m http.server -d crates/web/www 8080`
|
||||
- Open: `http://localhost:8080/`
|
||||
- Dev build (faster, unoptimized): `wasm-pack build --target web --dev --out-dir www/pkg`
|
||||
|
||||
## Key Principles
|
||||
|
||||
1. Correctness first, performance second
|
||||
|
||||
Generated
+124
-11
@@ -150,6 +150,12 @@ dependencies = [
|
||||
"allocator-api2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cast"
|
||||
version = "0.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "37b2a672a2cb129a2e41c10b1224bb368f9f37a2b16b612598138befd7b37eb5"
|
||||
|
||||
[[package]]
|
||||
name = "cc"
|
||||
version = "1.2.58"
|
||||
@@ -858,10 +864,12 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "js-sys"
|
||||
version = "0.3.92"
|
||||
version = "0.3.95"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cc4c90f45aa2e6eacbe8645f77fdea542ac97a494bcd117a67df9ff4d611f995"
|
||||
checksum = "2964e92d1d9dc3364cae4d718d93f227e3abb088e747d92e0395bfdedf1c12ca"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"futures-util",
|
||||
"once_cell",
|
||||
"wasm-bindgen",
|
||||
]
|
||||
@@ -929,6 +937,16 @@ dependencies = [
|
||||
"rustix",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "minicov"
|
||||
version = "0.3.8"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4869b6a491569605d66d3952bcdf03df789e5b536e5f0cf7758a7f08a55ae24d"
|
||||
dependencies = [
|
||||
"cc",
|
||||
"walkdir",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "nibble_vec"
|
||||
version = "0.1.0"
|
||||
@@ -950,6 +968,15 @@ dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "nu-ansi-term"
|
||||
version = "0.50.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5"
|
||||
dependencies = [
|
||||
"windows-sys",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "num-traits"
|
||||
version = "0.2.19"
|
||||
@@ -957,6 +984,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"
|
||||
dependencies = [
|
||||
"autocfg",
|
||||
"libm",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -983,6 +1011,12 @@ version = "1.70.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe"
|
||||
|
||||
[[package]]
|
||||
name = "oorandom"
|
||||
version = "11.1.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d6790f58c7ff633d8771f42965289203411a5e5c68388703c06e14f24770b41e"
|
||||
|
||||
[[package]]
|
||||
name = "petgraph"
|
||||
version = "0.6.5"
|
||||
@@ -1298,6 +1332,15 @@ version = "1.0.23"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f"
|
||||
|
||||
[[package]]
|
||||
name = "same-file"
|
||||
version = "1.0.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502"
|
||||
dependencies = [
|
||||
"winapi-util",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "semver"
|
||||
version = "1.0.27"
|
||||
@@ -1639,6 +1682,17 @@ dependencies = [
|
||||
"wasmtime",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wafer-web"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"js-sys",
|
||||
"wafer-core",
|
||||
"wasm-bindgen",
|
||||
"wasm-bindgen-test",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wait-timeout"
|
||||
version = "0.2.1"
|
||||
@@ -1648,6 +1702,16 @@ dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "walkdir"
|
||||
version = "2.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b"
|
||||
dependencies = [
|
||||
"same-file",
|
||||
"winapi-util",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wasi"
|
||||
version = "0.11.1+wasi-snapshot-preview1"
|
||||
@@ -1674,9 +1738,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "wasm-bindgen"
|
||||
version = "0.2.115"
|
||||
version = "0.2.118"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6523d69017b7633e396a89c5efab138161ed5aafcbc8d3e5c5a42ae38f50495a"
|
||||
checksum = "0bf938a0bacb0469e83c1e148908bd7d5a6010354cf4fb73279b7447422e3a89"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"once_cell",
|
||||
@@ -1686,10 +1750,20 @@ dependencies = [
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wasm-bindgen-macro"
|
||||
version = "0.2.115"
|
||||
name = "wasm-bindgen-futures"
|
||||
version = "0.4.68"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4e3a6c758eb2f701ed3d052ff5737f5bfe6614326ea7f3bbac7156192dc32e67"
|
||||
checksum = "f371d383f2fb139252e0bfac3b81b265689bf45b6874af544ffa4c975ac1ebf8"
|
||||
dependencies = [
|
||||
"js-sys",
|
||||
"wasm-bindgen",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wasm-bindgen-macro"
|
||||
version = "0.2.118"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "eeff24f84126c0ec2db7a449f0c2ec963c6a49efe0698c4242929da037ca28ed"
|
||||
dependencies = [
|
||||
"quote",
|
||||
"wasm-bindgen-macro-support",
|
||||
@@ -1697,9 +1771,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "wasm-bindgen-macro-support"
|
||||
version = "0.2.115"
|
||||
version = "0.2.118"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "921de2737904886b52bcbb237301552d05969a6f9c40d261eb0533c8b055fedf"
|
||||
checksum = "9d08065faf983b2b80a79fd87d8254c409281cf7de75fc4b773019824196c904"
|
||||
dependencies = [
|
||||
"bumpalo",
|
||||
"proc-macro2",
|
||||
@@ -1710,13 +1784,52 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "wasm-bindgen-shared"
|
||||
version = "0.2.115"
|
||||
version = "0.2.118"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a93e946af942b58934c604527337bad9ae33ba1d5c6900bbb41c2c07c2364a93"
|
||||
checksum = "5fd04d9e306f1907bd13c6361b5c6bfc7b3b3c095ed3f8a9246390f8dbdee129"
|
||||
dependencies = [
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wasm-bindgen-test"
|
||||
version = "0.3.68"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6bb55e2540ad1c56eec35fd63e2aea15f83b11ce487fd2de9ad11578dfc047ea"
|
||||
dependencies = [
|
||||
"async-trait",
|
||||
"cast",
|
||||
"js-sys",
|
||||
"libm",
|
||||
"minicov",
|
||||
"nu-ansi-term",
|
||||
"num-traits",
|
||||
"oorandom",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"wasm-bindgen",
|
||||
"wasm-bindgen-futures",
|
||||
"wasm-bindgen-test-macro",
|
||||
"wasm-bindgen-test-shared",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wasm-bindgen-test-macro"
|
||||
version = "0.3.68"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "caf0ca1bd612b988616bac1ab34c4e4290ef18f7148a1d8b7f31c150080e9295"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wasm-bindgen-test-shared"
|
||||
version = "0.2.118"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "23cda5ecc67248c48d3e705d3e03e00af905769b78b9d2a1678b663b8b9d4472"
|
||||
|
||||
[[package]]
|
||||
name = "wasm-compose"
|
||||
version = "0.245.1"
|
||||
|
||||
@@ -7,6 +7,7 @@ use clap::{Parser, Subcommand};
|
||||
use wafer_core::export::{ExportConfig, export_module, serialize_metadata};
|
||||
use wafer_core::outer::ForthVM;
|
||||
use wafer_core::runner::{run_precompiled_bytes, run_wasm_file};
|
||||
use wafer_core::runtime_native::NativeRuntime;
|
||||
|
||||
/// 8-byte magic trailer identifying a native WAFER executable.
|
||||
const NATIVE_MAGIC: &[u8; 8] = b"WAFEREXE";
|
||||
@@ -136,7 +137,7 @@ fn cmd_build(
|
||||
) -> anyhow::Result<()> {
|
||||
let source = std::fs::read_to_string(file)?;
|
||||
|
||||
let mut vm = ForthVM::new()?;
|
||||
let mut vm = ForthVM::<NativeRuntime>::new()?;
|
||||
vm.set_recording(true);
|
||||
vm.evaluate(&source)?;
|
||||
|
||||
@@ -261,7 +262,7 @@ fn cmd_run(file: &str) -> anyhow::Result<()> {
|
||||
|
||||
/// `wafer` (REPL) or `wafer program.fth` (evaluate and exit)
|
||||
fn cmd_eval_or_repl(file: Option<&str>) -> anyhow::Result<()> {
|
||||
let mut vm = ForthVM::new()?;
|
||||
let mut vm = ForthVM::<NativeRuntime>::new()?;
|
||||
|
||||
match file {
|
||||
Some(file) => {
|
||||
|
||||
@@ -8,10 +8,14 @@ license.workspace = true
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[features]
|
||||
default = ["native"]
|
||||
native = ["dep:wasmtime"]
|
||||
|
||||
[dependencies]
|
||||
wasm-encoder = { workspace = true }
|
||||
wasmparser = { workspace = true }
|
||||
wasmtime = { workspace = true }
|
||||
wasmtime = { workspace = true, optional = true }
|
||||
anyhow = { workspace = true }
|
||||
thiserror = { workspace = true }
|
||||
|
||||
|
||||
@@ -3059,7 +3059,7 @@ fn compile_multi_word_module(
|
||||
// Tests
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
#[cfg(test)]
|
||||
#[cfg(all(test, feature = "native"))]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::dictionary::WordId;
|
||||
|
||||
@@ -10,6 +10,7 @@ use crate::codegen::{ExportSections, compile_exportable_module};
|
||||
use crate::dictionary::WordId;
|
||||
use crate::ir::IrOp;
|
||||
use crate::outer::ForthVM;
|
||||
use crate::runtime::Runtime;
|
||||
|
||||
/// Configuration for `wafer build`.
|
||||
pub struct ExportConfig {
|
||||
@@ -39,14 +40,14 @@ pub struct ExportMetadata {
|
||||
///
|
||||
/// Returns the raw `.wasm` bytes ready to write to a file, plus the metadata.
|
||||
pub fn export_module(
|
||||
vm: &mut ForthVM,
|
||||
vm: &mut ForthVM<impl Runtime>,
|
||||
config: &ExportConfig,
|
||||
) -> anyhow::Result<(Vec<u8>, ExportMetadata)> {
|
||||
let mut words = vm.ir_words();
|
||||
|
||||
// Determine the entry point.
|
||||
// Priority: --entry flag > MAIN word > recorded top-level execution.
|
||||
let toplevel = vm.toplevel_ir();
|
||||
let toplevel = vm.toplevel_ir().to_vec();
|
||||
let entry_word_id = if let Some(ref name) = config.entry_word {
|
||||
Some(
|
||||
vm.resolve_word(name)
|
||||
@@ -58,7 +59,7 @@ pub fn export_module(
|
||||
// Synthesize a _start word from recorded top-level execution.
|
||||
// Pick a WordId that won't collide (one past the current table size).
|
||||
let start_id = WordId(vm.current_table_size());
|
||||
words.push((start_id, toplevel.to_vec()));
|
||||
words.push((start_id, toplevel.clone()));
|
||||
Some(start_id)
|
||||
} else {
|
||||
None
|
||||
@@ -361,8 +362,9 @@ mod tests {
|
||||
fn roundtrip(source: &str) -> String {
|
||||
use crate::outer::ForthVM;
|
||||
use crate::runner::run_wasm_bytes;
|
||||
use crate::runtime_native::NativeRuntime;
|
||||
|
||||
let mut vm = ForthVM::new().unwrap();
|
||||
let mut vm = ForthVM::<NativeRuntime>::new().unwrap();
|
||||
vm.set_recording(true);
|
||||
vm.evaluate(source).unwrap();
|
||||
|
||||
|
||||
+15
-3
@@ -16,13 +16,25 @@
|
||||
|
||||
pub mod codegen;
|
||||
pub mod config;
|
||||
pub mod consolidate;
|
||||
pub mod dictionary;
|
||||
pub mod error;
|
||||
pub mod export;
|
||||
pub mod ir;
|
||||
pub mod js_loader;
|
||||
pub mod memory;
|
||||
pub mod optimizer;
|
||||
pub mod runtime;
|
||||
|
||||
// Outer interpreter: runtime-agnostic, works with any Runtime impl
|
||||
#[allow(trivial_numeric_casts, clippy::unnecessary_cast)]
|
||||
pub mod outer;
|
||||
|
||||
// Modules requiring the native wasmtime runtime
|
||||
#[cfg(feature = "native")]
|
||||
pub mod consolidate;
|
||||
#[cfg(feature = "native")]
|
||||
pub mod export;
|
||||
#[cfg(feature = "native")]
|
||||
pub mod js_loader;
|
||||
#[cfg(feature = "native")]
|
||||
pub mod runner;
|
||||
#[cfg(feature = "native")]
|
||||
pub mod runtime_native;
|
||||
|
||||
+1531
-2646
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,152 @@
|
||||
//! Runtime abstraction for WASM execution.
|
||||
//!
|
||||
//! The [`Runtime`] trait decouples the Forth VM from any specific WASM engine.
|
||||
//! Two implementations exist:
|
||||
//! - `NativeRuntime` (wasmtime) — for CLI and native tests
|
||||
//! - `WebRuntime` (`js_sys`) — for browser REPL
|
||||
//!
|
||||
//! The [`HostAccess`] trait provides memory and global access to host function
|
||||
//! callbacks, abstracting over wasmtime's `Caller` and browser's `js_sys` APIs.
|
||||
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
/// Access to WASM memory and globals from within a host function callback.
|
||||
///
|
||||
/// Both wasmtime (via `Caller`) and browser (via `js_sys`) implement this trait,
|
||||
/// allowing host function logic to be shared across runtimes.
|
||||
pub trait HostAccess {
|
||||
/// Read a 32-bit integer from linear memory at `addr` (little-endian).
|
||||
fn mem_read_i32(&mut self, addr: u32) -> i32;
|
||||
|
||||
/// Write a 32-bit integer to linear memory at `addr` (little-endian).
|
||||
fn mem_write_i32(&mut self, addr: u32, val: i32);
|
||||
|
||||
/// Read a single byte from linear memory.
|
||||
fn mem_read_u8(&mut self, addr: u32) -> u8;
|
||||
|
||||
/// Write a single byte to linear memory.
|
||||
fn mem_write_u8(&mut self, addr: u32, val: u8);
|
||||
|
||||
/// Read a slice of bytes from linear memory.
|
||||
fn mem_read_slice(&mut self, addr: u32, len: usize) -> Vec<u8>;
|
||||
|
||||
/// Write a slice of bytes to linear memory.
|
||||
fn mem_write_slice(&mut self, addr: u32, data: &[u8]);
|
||||
|
||||
/// Total size of linear memory in bytes.
|
||||
fn mem_len(&mut self) -> usize;
|
||||
|
||||
/// Read the data stack pointer global.
|
||||
fn get_dsp(&mut self) -> u32;
|
||||
|
||||
/// Write the data stack pointer global.
|
||||
fn set_dsp(&mut self, val: u32);
|
||||
|
||||
/// Read the return stack pointer global.
|
||||
fn get_rsp(&mut self) -> u32;
|
||||
|
||||
/// Write the return stack pointer global.
|
||||
fn set_rsp(&mut self, val: u32);
|
||||
|
||||
/// Read the float stack pointer global.
|
||||
fn get_fsp(&mut self) -> u32;
|
||||
|
||||
/// Write the float stack pointer global.
|
||||
fn set_fsp(&mut self, val: u32);
|
||||
|
||||
/// Call a function in the shared table by index.
|
||||
/// Needed by CATCH to invoke the xt it receives.
|
||||
fn call_func(&mut self, fn_index: u32) -> anyhow::Result<()>;
|
||||
}
|
||||
|
||||
/// Host function callback type.
|
||||
///
|
||||
/// A boxed closure that receives mutable [`HostAccess`] for memory/global ops.
|
||||
/// Captures shared state (e.g. output buffer) via `Arc<Mutex<...>>`.
|
||||
pub type HostFn = Box<dyn Fn(&mut dyn HostAccess) -> anyhow::Result<()> + Send + Sync>;
|
||||
|
||||
/// Abstraction over a WASM execution runtime.
|
||||
///
|
||||
/// Provides memory access, global management, module instantiation,
|
||||
/// function execution, and host function registration.
|
||||
pub trait Runtime: Sized {
|
||||
/// Create a new runtime with shared linear memory, function table,
|
||||
/// stack pointer globals, and an `emit` host function wired to `output`.
|
||||
fn new(
|
||||
memory_pages: u32,
|
||||
table_size: u32,
|
||||
dsp_init: u32,
|
||||
rsp_init: u32,
|
||||
fsp_init: u32,
|
||||
output: Arc<Mutex<String>>,
|
||||
) -> anyhow::Result<Self>;
|
||||
|
||||
// -- Linear memory access --
|
||||
|
||||
/// Read a 32-bit integer from linear memory at `addr` (little-endian).
|
||||
fn mem_read_i32(&mut self, addr: u32) -> i32;
|
||||
|
||||
/// Write a 32-bit integer to linear memory at `addr` (little-endian).
|
||||
fn mem_write_i32(&mut self, addr: u32, val: i32);
|
||||
|
||||
/// Read a single byte from linear memory.
|
||||
fn mem_read_u8(&mut self, addr: u32) -> u8;
|
||||
|
||||
/// Write a single byte to linear memory.
|
||||
fn mem_write_u8(&mut self, addr: u32, val: u8);
|
||||
|
||||
/// Read a slice of bytes from linear memory.
|
||||
fn mem_read_slice(&mut self, addr: u32, len: usize) -> Vec<u8>;
|
||||
|
||||
/// Write a slice of bytes to linear memory.
|
||||
fn mem_write_slice(&mut self, addr: u32, data: &[u8]);
|
||||
|
||||
/// Total size of linear memory in bytes.
|
||||
fn mem_len(&mut self) -> usize;
|
||||
|
||||
// -- Globals --
|
||||
|
||||
/// Read the data stack pointer global.
|
||||
fn get_dsp(&mut self) -> u32;
|
||||
|
||||
/// Write the data stack pointer global.
|
||||
fn set_dsp(&mut self, val: u32);
|
||||
|
||||
/// Read the return stack pointer global.
|
||||
fn get_rsp(&mut self) -> u32;
|
||||
|
||||
/// Write the return stack pointer global.
|
||||
fn set_rsp(&mut self, val: u32);
|
||||
|
||||
/// Read the float stack pointer global.
|
||||
fn get_fsp(&mut self) -> u32;
|
||||
|
||||
/// Write the float stack pointer global.
|
||||
fn set_fsp(&mut self, val: u32);
|
||||
|
||||
// -- Function table --
|
||||
|
||||
/// Current number of entries in the function table.
|
||||
fn table_size(&mut self) -> u32;
|
||||
|
||||
/// Grow the table if needed so that index `needed` is valid.
|
||||
fn ensure_table_size(&mut self, needed: u32) -> anyhow::Result<()>;
|
||||
|
||||
// -- Compilation and execution --
|
||||
|
||||
/// Compile WASM bytes into a module, instantiate it with shared imports
|
||||
/// (memory, table, globals, emit), and install the exported function
|
||||
/// at `fn_index` in the shared table.
|
||||
fn instantiate_and_install(&mut self, wasm_bytes: &[u8], fn_index: u32) -> anyhow::Result<()>;
|
||||
|
||||
/// Call the function at `fn_index` in the shared table.
|
||||
fn call_func(&mut self, fn_index: u32) -> anyhow::Result<()>;
|
||||
|
||||
// -- Host functions --
|
||||
|
||||
/// Register a void→void host function at `fn_index` in the shared table.
|
||||
///
|
||||
/// The callback receives a [`HostAccess`] for memory and global operations.
|
||||
/// It may also capture shared state via `Arc<Mutex<...>>`.
|
||||
fn register_host_func(&mut self, fn_index: u32, f: HostFn) -> anyhow::Result<()>;
|
||||
}
|
||||
@@ -0,0 +1,328 @@
|
||||
//! Native runtime implementation using wasmtime.
|
||||
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use wasmtime::{
|
||||
Engine, Func, FuncType, Global, Instance, Memory, Module, Mutability, Ref, RefType, Store,
|
||||
Table, Val, ValType,
|
||||
};
|
||||
|
||||
use crate::runtime::{HostAccess, HostFn, Runtime};
|
||||
|
||||
/// Host-side state accessible from WASM callbacks.
|
||||
struct NativeVmHost {
|
||||
#[allow(dead_code)]
|
||||
output: Arc<Mutex<String>>,
|
||||
}
|
||||
|
||||
/// [`HostAccess`] implementation for wasmtime, wrapping a `Caller`.
|
||||
struct CallerHostAccess<'a, 'b> {
|
||||
caller: &'a mut wasmtime::Caller<'b, NativeVmHost>,
|
||||
memory: Memory,
|
||||
table: Table,
|
||||
dsp: Global,
|
||||
rsp: Global,
|
||||
fsp: Global,
|
||||
}
|
||||
|
||||
impl HostAccess for CallerHostAccess<'_, '_> {
|
||||
fn mem_read_i32(&mut self, addr: u32) -> i32 {
|
||||
let data = self.memory.data(&self.caller);
|
||||
let a = addr as usize;
|
||||
i32::from_le_bytes(data[a..a + 4].try_into().unwrap())
|
||||
}
|
||||
|
||||
fn mem_write_i32(&mut self, addr: u32, val: i32) {
|
||||
let a = addr as usize;
|
||||
let bytes = val.to_le_bytes();
|
||||
self.memory.data_mut(&mut *self.caller)[a..a + 4].copy_from_slice(&bytes);
|
||||
}
|
||||
|
||||
fn mem_read_u8(&mut self, addr: u32) -> u8 {
|
||||
self.memory.data(&self.caller)[addr as usize]
|
||||
}
|
||||
|
||||
fn mem_write_u8(&mut self, addr: u32, val: u8) {
|
||||
self.memory.data_mut(&mut *self.caller)[addr as usize] = val;
|
||||
}
|
||||
|
||||
fn mem_read_slice(&mut self, addr: u32, len: usize) -> Vec<u8> {
|
||||
let a = addr as usize;
|
||||
self.memory.data(&self.caller)[a..a + len].to_vec()
|
||||
}
|
||||
|
||||
fn mem_write_slice(&mut self, addr: u32, data: &[u8]) {
|
||||
let a = addr as usize;
|
||||
self.memory.data_mut(&mut *self.caller)[a..a + data.len()].copy_from_slice(data);
|
||||
}
|
||||
|
||||
fn mem_len(&mut self) -> usize {
|
||||
self.memory.data(&self.caller).len()
|
||||
}
|
||||
|
||||
fn get_dsp(&mut self) -> u32 {
|
||||
self.dsp.get(&mut *self.caller).unwrap_i32() as u32
|
||||
}
|
||||
|
||||
fn set_dsp(&mut self, val: u32) {
|
||||
self.dsp
|
||||
.set(&mut *self.caller, Val::I32(val as i32))
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
fn get_rsp(&mut self) -> u32 {
|
||||
self.rsp.get(&mut *self.caller).unwrap_i32() as u32
|
||||
}
|
||||
|
||||
fn set_rsp(&mut self, val: u32) {
|
||||
self.rsp
|
||||
.set(&mut *self.caller, Val::I32(val as i32))
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
fn get_fsp(&mut self) -> u32 {
|
||||
self.fsp.get(&mut *self.caller).unwrap_i32() as u32
|
||||
}
|
||||
|
||||
fn set_fsp(&mut self, val: u32) {
|
||||
self.fsp
|
||||
.set(&mut *self.caller, Val::I32(val as i32))
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
fn call_func(&mut self, fn_index: u32) -> anyhow::Result<()> {
|
||||
let func_ref = self
|
||||
.table
|
||||
.get(&mut *self.caller, fn_index as u64)
|
||||
.ok_or_else(|| anyhow::anyhow!("call_func: invalid index {fn_index}"))?;
|
||||
let func = *func_ref
|
||||
.unwrap_func()
|
||||
.ok_or_else(|| anyhow::anyhow!("call_func: null funcref {fn_index}"))?;
|
||||
func.call(&mut *self.caller, &[], &mut [])?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Wasmtime-based native runtime.
|
||||
pub struct NativeRuntime {
|
||||
engine: Engine,
|
||||
store: Store<NativeVmHost>,
|
||||
memory: Memory,
|
||||
table: Table,
|
||||
dsp: Global,
|
||||
rsp: Global,
|
||||
fsp: Global,
|
||||
emit_func: Func,
|
||||
}
|
||||
|
||||
impl Runtime for NativeRuntime {
|
||||
fn new(
|
||||
memory_pages: u32,
|
||||
table_size: u32,
|
||||
dsp_init: u32,
|
||||
rsp_init: u32,
|
||||
fsp_init: u32,
|
||||
output: Arc<Mutex<String>>,
|
||||
) -> anyhow::Result<Self> {
|
||||
let mut config = wasmtime::Config::new();
|
||||
config.cranelift_nan_canonicalization(false);
|
||||
let engine = Engine::new(&config)?;
|
||||
|
||||
let host = NativeVmHost {
|
||||
output: Arc::clone(&output),
|
||||
};
|
||||
let mut store = Store::new(&engine, host);
|
||||
|
||||
let memory = Memory::new(&mut store, wasmtime::MemoryType::new(memory_pages, None))?;
|
||||
|
||||
let dsp = Global::new(
|
||||
&mut store,
|
||||
wasmtime::GlobalType::new(ValType::I32, Mutability::Var),
|
||||
Val::I32(dsp_init as i32),
|
||||
)?;
|
||||
let rsp = Global::new(
|
||||
&mut store,
|
||||
wasmtime::GlobalType::new(ValType::I32, Mutability::Var),
|
||||
Val::I32(rsp_init as i32),
|
||||
)?;
|
||||
let fsp = Global::new(
|
||||
&mut store,
|
||||
wasmtime::GlobalType::new(ValType::I32, Mutability::Var),
|
||||
Val::I32(fsp_init as i32),
|
||||
)?;
|
||||
|
||||
let table = Table::new(
|
||||
&mut store,
|
||||
wasmtime::TableType::new(RefType::FUNCREF, table_size, None),
|
||||
Ref::Func(None),
|
||||
)?;
|
||||
|
||||
let out_ref = Arc::clone(&output);
|
||||
let emit_func = Func::new(
|
||||
&mut store,
|
||||
FuncType::new(&engine, [ValType::I32], []),
|
||||
move |_caller, params, _results| {
|
||||
let ch = params[0].unwrap_i32() as u8 as char;
|
||||
out_ref.lock().unwrap().push(ch);
|
||||
Ok(())
|
||||
},
|
||||
);
|
||||
|
||||
Ok(NativeRuntime {
|
||||
engine,
|
||||
store,
|
||||
memory,
|
||||
table,
|
||||
dsp,
|
||||
rsp,
|
||||
fsp,
|
||||
emit_func,
|
||||
})
|
||||
}
|
||||
|
||||
// -- Memory --
|
||||
|
||||
fn mem_read_i32(&mut self, addr: u32) -> i32 {
|
||||
let a = addr as usize;
|
||||
let data = self.memory.data(&self.store);
|
||||
i32::from_le_bytes(data[a..a + 4].try_into().unwrap())
|
||||
}
|
||||
|
||||
fn mem_write_i32(&mut self, addr: u32, val: i32) {
|
||||
let a = addr as usize;
|
||||
let bytes = val.to_le_bytes();
|
||||
self.memory.data_mut(&mut self.store)[a..a + 4].copy_from_slice(&bytes);
|
||||
}
|
||||
|
||||
fn mem_read_u8(&mut self, addr: u32) -> u8 {
|
||||
self.memory.data(&self.store)[addr as usize]
|
||||
}
|
||||
|
||||
fn mem_write_u8(&mut self, addr: u32, val: u8) {
|
||||
self.memory.data_mut(&mut self.store)[addr as usize] = val;
|
||||
}
|
||||
|
||||
fn mem_read_slice(&mut self, addr: u32, len: usize) -> Vec<u8> {
|
||||
let a = addr as usize;
|
||||
self.memory.data(&self.store)[a..a + len].to_vec()
|
||||
}
|
||||
|
||||
fn mem_write_slice(&mut self, addr: u32, data: &[u8]) {
|
||||
let a = addr as usize;
|
||||
self.memory.data_mut(&mut self.store)[a..a + data.len()].copy_from_slice(data);
|
||||
}
|
||||
|
||||
fn mem_len(&mut self) -> usize {
|
||||
self.memory.data(&self.store).len()
|
||||
}
|
||||
|
||||
// -- Globals --
|
||||
|
||||
fn get_dsp(&mut self) -> u32 {
|
||||
self.dsp.get(&mut self.store).unwrap_i32() as u32
|
||||
}
|
||||
|
||||
fn set_dsp(&mut self, val: u32) {
|
||||
self.dsp.set(&mut self.store, Val::I32(val as i32)).unwrap();
|
||||
}
|
||||
|
||||
fn get_rsp(&mut self) -> u32 {
|
||||
self.rsp.get(&mut self.store).unwrap_i32() as u32
|
||||
}
|
||||
|
||||
fn set_rsp(&mut self, val: u32) {
|
||||
self.rsp.set(&mut self.store, Val::I32(val as i32)).unwrap();
|
||||
}
|
||||
|
||||
fn get_fsp(&mut self) -> u32 {
|
||||
self.fsp.get(&mut self.store).unwrap_i32() as u32
|
||||
}
|
||||
|
||||
fn set_fsp(&mut self, val: u32) {
|
||||
self.fsp.set(&mut self.store, Val::I32(val as i32)).unwrap();
|
||||
}
|
||||
|
||||
// -- Table --
|
||||
|
||||
fn table_size(&mut self) -> u32 {
|
||||
self.table.size(&self.store) as u32
|
||||
}
|
||||
|
||||
fn ensure_table_size(&mut self, needed: u32) -> anyhow::Result<()> {
|
||||
let current = self.table.size(&self.store) as u32;
|
||||
if needed >= current {
|
||||
let grow = (needed - current + 64) as u64;
|
||||
self.table.grow(&mut self.store, grow, Ref::Func(None))?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// -- Compilation and execution --
|
||||
|
||||
fn instantiate_and_install(&mut self, wasm_bytes: &[u8], fn_index: u32) -> anyhow::Result<()> {
|
||||
self.ensure_table_size(fn_index)?;
|
||||
let module = Module::new(&self.engine, wasm_bytes)?;
|
||||
let instance = Instance::new(
|
||||
&mut self.store,
|
||||
&module,
|
||||
&[
|
||||
self.emit_func.into(),
|
||||
self.memory.into(),
|
||||
self.dsp.into(),
|
||||
self.rsp.into(),
|
||||
self.fsp.into(),
|
||||
self.table.into(),
|
||||
],
|
||||
)?;
|
||||
|
||||
// Single-word modules export "fn"; multi-word (consolidated/batch)
|
||||
// modules use the element section to place functions in the table.
|
||||
if let Some(func) = instance.get_func(&mut self.store, "fn") {
|
||||
self.table
|
||||
.set(&mut self.store, fn_index as u64, Ref::Func(Some(func)))?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn call_func(&mut self, fn_index: u32) -> anyhow::Result<()> {
|
||||
let r = self
|
||||
.table
|
||||
.get(&mut self.store, fn_index as u64)
|
||||
.ok_or_else(|| anyhow::anyhow!("word {fn_index} not in function table"))?;
|
||||
let func = *r
|
||||
.unwrap_func()
|
||||
.ok_or_else(|| anyhow::anyhow!("word {fn_index} is null funcref"))?;
|
||||
func.call(&mut self.store, &[], &mut [])?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// -- Host functions --
|
||||
|
||||
fn register_host_func(&mut self, fn_index: u32, f: HostFn) -> anyhow::Result<()> {
|
||||
let mem = self.memory;
|
||||
let tbl = self.table;
|
||||
let dsp = self.dsp;
|
||||
let rsp = self.rsp;
|
||||
let fsp = self.fsp;
|
||||
let func = Func::new(
|
||||
&mut self.store,
|
||||
FuncType::new(&self.engine, [], []),
|
||||
move |mut caller, _params, _results| {
|
||||
let mut ctx = CallerHostAccess {
|
||||
caller: &mut caller,
|
||||
memory: mem,
|
||||
table: tbl,
|
||||
dsp,
|
||||
rsp,
|
||||
fsp,
|
||||
};
|
||||
f(&mut ctx).map_err(|e| wasmtime::Error::msg(e.to_string()))
|
||||
},
|
||||
);
|
||||
self.ensure_table_size(fn_index)?;
|
||||
self.table
|
||||
.set(&mut self.store, fn_index as u64, Ref::Func(Some(func)))?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,7 @@
|
||||
use std::time::Instant;
|
||||
use wafer_core::config::WaferConfig;
|
||||
use wafer_core::outer::ForthVM;
|
||||
use wafer_core::runtime_native::NativeRuntime;
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
// Benchmark definitions
|
||||
@@ -203,7 +204,8 @@ struct BenchResult {
|
||||
fn run_benchmark(config: &WaferConfig, bench: &Benchmark) -> BenchResult {
|
||||
// Compile
|
||||
let compile_start = Instant::now();
|
||||
let mut vm = ForthVM::new_with_config(config.clone()).expect("VM creation failed");
|
||||
let mut vm =
|
||||
ForthVM::<NativeRuntime>::new_with_config(config.clone()).expect("VM creation failed");
|
||||
for line in bench.define.lines() {
|
||||
let trimmed = line.trim();
|
||||
if !trimmed.is_empty() {
|
||||
@@ -246,7 +248,8 @@ fn correctness_all_configs() {
|
||||
|
||||
for (cfg_name, config) in &configs {
|
||||
for bench in &benches {
|
||||
let mut vm = ForthVM::new_with_config(config.clone()).expect("VM creation failed");
|
||||
let mut vm = ForthVM::<NativeRuntime>::new_with_config(config.clone())
|
||||
.expect("VM creation failed");
|
||||
let mut define_ok = true;
|
||||
for line in bench.define.lines() {
|
||||
let trimmed = line.trim();
|
||||
@@ -427,8 +430,8 @@ fn optimization_report() {
|
||||
let result_all = run_benchmark(&all_config, bench);
|
||||
|
||||
// With CONSOLIDATE
|
||||
let mut vm_consol =
|
||||
ForthVM::new_with_config(all_config.clone()).expect("VM creation failed");
|
||||
let mut vm_consol = ForthVM::<NativeRuntime>::new_with_config(all_config.clone())
|
||||
.expect("VM creation failed");
|
||||
for line in bench.define.lines() {
|
||||
let trimmed = line.trim();
|
||||
if !trimmed.is_empty() {
|
||||
|
||||
@@ -12,6 +12,7 @@ use std::sync::OnceLock;
|
||||
|
||||
use wafer_core::config::WaferConfig;
|
||||
use wafer_core::outer::ForthVM;
|
||||
use wafer_core::runtime_native::NativeRuntime;
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
// Gforth discovery (cached)
|
||||
@@ -74,7 +75,7 @@ struct EngineResult {
|
||||
|
||||
/// Run Forth code through WAFER (in-process via `ForthVM`).
|
||||
fn run_wafer(code: &str) -> EngineResult {
|
||||
let mut vm = ForthVM::new().expect("Failed to create ForthVM");
|
||||
let mut vm = ForthVM::<NativeRuntime>::new().expect("Failed to create ForthVM");
|
||||
let mut output = String::new();
|
||||
for line in code.lines() {
|
||||
let trimmed = line.trim();
|
||||
@@ -99,7 +100,8 @@ fn run_wafer(code: &str) -> EngineResult {
|
||||
|
||||
/// Run Forth code through WAFER with all optimizations enabled.
|
||||
fn run_wafer_optimized(code: &str) -> EngineResult {
|
||||
let mut vm = ForthVM::new_with_config(WaferConfig::all()).expect("Failed to create ForthVM");
|
||||
let mut vm = ForthVM::<NativeRuntime>::new_with_config(WaferConfig::all())
|
||||
.expect("Failed to create ForthVM");
|
||||
let mut output = String::new();
|
||||
for line in code.lines() {
|
||||
let trimmed = line.trim();
|
||||
@@ -809,7 +811,7 @@ fn performance_report() {
|
||||
|
||||
// Verify correctness first
|
||||
for bench in &benchmarks {
|
||||
let mut vm = ForthVM::new().expect("VM creation failed");
|
||||
let mut vm = ForthVM::<NativeRuntime>::new().expect("VM creation failed");
|
||||
for line in bench.define.lines() {
|
||||
let trimmed = line.trim();
|
||||
if !trimmed.is_empty() {
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
//! asserting 0 test failures.
|
||||
|
||||
use wafer_core::outer::ForthVM;
|
||||
use wafer_core::runtime_native::NativeRuntime;
|
||||
|
||||
/// Path to the test suite source directory.
|
||||
const SUITE_DIR: &str = concat!(
|
||||
@@ -13,7 +14,7 @@ const SUITE_DIR: &str = concat!(
|
||||
);
|
||||
|
||||
/// Load a file and evaluate it line by line, ignoring errors on individual lines.
|
||||
fn load_file(vm: &mut ForthVM, path: &str) {
|
||||
fn load_file(vm: &mut ForthVM<NativeRuntime>, path: &str) {
|
||||
let source = std::fs::read_to_string(path).unwrap_or_else(|_| panic!("Failed to read {path}"));
|
||||
for line in source.lines() {
|
||||
let _ = vm.evaluate(line);
|
||||
@@ -22,8 +23,8 @@ fn load_file(vm: &mut ForthVM, path: &str) {
|
||||
}
|
||||
|
||||
/// Boot a WAFER VM with full prerequisites loaded.
|
||||
fn boot_with_prerequisites() -> ForthVM {
|
||||
let mut vm = ForthVM::new().expect("Failed to create ForthVM");
|
||||
fn boot_with_prerequisites() -> ForthVM<NativeRuntime> {
|
||||
let mut vm = ForthVM::<NativeRuntime>::new().expect("Failed to create ForthVM");
|
||||
|
||||
// Load test framework
|
||||
load_file(&mut vm, &format!("{SUITE_DIR}/tester.fr"));
|
||||
@@ -40,7 +41,7 @@ fn boot_with_prerequisites() -> ForthVM {
|
||||
}
|
||||
|
||||
/// Run a test suite file and return the #ERRORS count.
|
||||
fn run_suite(vm: &mut ForthVM, test_file: &str) -> u32 {
|
||||
fn run_suite(vm: &mut ForthVM<NativeRuntime>, test_file: &str) -> u32 {
|
||||
// Reset error counter
|
||||
let _ = vm.evaluate("DECIMAL 0 #ERRORS !");
|
||||
vm.take_output();
|
||||
@@ -74,7 +75,7 @@ fn run_suite(vm: &mut ForthVM, test_file: &str) -> u32 {
|
||||
|
||||
#[test]
|
||||
fn compliance_core() {
|
||||
let mut vm = ForthVM::new().expect("Failed to create ForthVM");
|
||||
let mut vm = ForthVM::<NativeRuntime>::new().expect("Failed to create ForthVM");
|
||||
load_file(&mut vm, &format!("{SUITE_DIR}/tester.fr"));
|
||||
load_file(&mut vm, &format!("{SUITE_DIR}/core.fr"));
|
||||
|
||||
@@ -94,7 +95,7 @@ fn compliance_core_plus() {
|
||||
fn compliance_core_ext() {
|
||||
// Core Extensions are loaded as part of prerequisites.
|
||||
// Run from scratch to get a clean error count.
|
||||
let mut vm = ForthVM::new().expect("Failed to create ForthVM");
|
||||
let mut vm = ForthVM::<NativeRuntime>::new().expect("Failed to create ForthVM");
|
||||
load_file(&mut vm, &format!("{SUITE_DIR}/tester.fr"));
|
||||
load_file(&mut vm, &format!("{SUITE_DIR}/core.fr"));
|
||||
let _ = vm.evaluate("DECIMAL");
|
||||
@@ -162,7 +163,7 @@ fn compliance_search_order() {
|
||||
fn compliance_string() {
|
||||
// Run from scratch -- the stringtest includes CoreExt tests that
|
||||
// cascade failures when run on top of an already-loaded CoreExt suite.
|
||||
let mut vm = ForthVM::new().expect("Failed to create ForthVM");
|
||||
let mut vm = ForthVM::<NativeRuntime>::new().expect("Failed to create ForthVM");
|
||||
load_file(&mut vm, &format!("{SUITE_DIR}/tester.fr"));
|
||||
load_file(&mut vm, &format!("{SUITE_DIR}/core.fr"));
|
||||
let _ = vm.evaluate("DECIMAL");
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
[package]
|
||||
name = "wafer-web"
|
||||
description = "WAFER browser REPL — WebAssembly Forth in the browser"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[lib]
|
||||
crate-type = ["cdylib", "rlib"]
|
||||
|
||||
[dependencies]
|
||||
wafer-core = { path = "../core", version = "0.1.0", default-features = false }
|
||||
wasm-bindgen = "0.2"
|
||||
js-sys = "0.3"
|
||||
anyhow = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
wasm-bindgen-test = "0.3"
|
||||
@@ -0,0 +1,56 @@
|
||||
//! WAFER Web REPL — browser-based Forth REPL using WebAssembly.
|
||||
|
||||
mod runtime_web;
|
||||
|
||||
use wasm_bindgen::prelude::*;
|
||||
|
||||
use wafer_core::outer::ForthVM;
|
||||
|
||||
use crate::runtime_web::WebRuntime;
|
||||
|
||||
/// Browser REPL for WAFER Forth.
|
||||
#[wasm_bindgen]
|
||||
pub struct WaferRepl {
|
||||
vm: ForthVM<WebRuntime>,
|
||||
}
|
||||
|
||||
#[wasm_bindgen]
|
||||
impl WaferRepl {
|
||||
/// Create a new WAFER REPL instance with all built-in words.
|
||||
#[wasm_bindgen(constructor)]
|
||||
pub fn new() -> Result<WaferRepl, JsError> {
|
||||
let vm = ForthVM::<WebRuntime>::new().map_err(|e| JsError::new(&e.to_string()))?;
|
||||
Ok(WaferRepl { vm })
|
||||
}
|
||||
|
||||
/// Evaluate a line of Forth input. Returns output text.
|
||||
pub fn evaluate(&mut self, input: &str) -> Result<String, JsError> {
|
||||
self.vm
|
||||
.evaluate(input)
|
||||
.map_err(|e| JsError::new(&e.to_string()))?;
|
||||
Ok(self.vm.take_output())
|
||||
}
|
||||
|
||||
/// Get the current data stack as an array (top-first).
|
||||
pub fn data_stack(&mut self) -> Vec<i32> {
|
||||
self.vm.data_stack()
|
||||
}
|
||||
|
||||
/// Check if the VM is currently in compile mode.
|
||||
pub fn is_compiling(&self) -> bool {
|
||||
self.vm.is_compiling()
|
||||
}
|
||||
|
||||
/// Get the current number base (10 = decimal, 16 = hex).
|
||||
pub fn base(&mut self) -> u32 {
|
||||
// BASE is stored at SYSVAR_BASE_VAR in WASM memory
|
||||
self.vm.take_output(); // no-op side effect; just return base
|
||||
10 // TODO: read from memory once we have a getter
|
||||
}
|
||||
|
||||
/// Reset the VM to initial state.
|
||||
pub fn reset(&mut self) -> Result<(), JsError> {
|
||||
self.vm = ForthVM::<WebRuntime>::new().map_err(|e| JsError::new(&e.to_string()))?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,542 @@
|
||||
//! Browser runtime implementation using js-sys WebAssembly API.
|
||||
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use js_sys::{Function, Object, Reflect, Uint8Array, WebAssembly};
|
||||
use wasm_bindgen::JsCast;
|
||||
use wasm_bindgen::prelude::*;
|
||||
|
||||
use wafer_core::runtime::{HostAccess, HostFn, Runtime};
|
||||
|
||||
/// Browser-based WASM runtime using the WebAssembly JS API.
|
||||
pub(crate) struct WebRuntime {
|
||||
memory: JsValue,
|
||||
table: JsValue,
|
||||
dsp_global: JsValue,
|
||||
rsp_global: JsValue,
|
||||
fsp_global: JsValue,
|
||||
emit_func: JsValue,
|
||||
#[allow(dead_code)]
|
||||
output: Arc<Mutex<String>>,
|
||||
/// Keep closures alive to prevent GC.
|
||||
_closures: Vec<JsValue>,
|
||||
}
|
||||
|
||||
/// [`HostAccess`] for browser — wraps `js_sys` Memory/Globals.
|
||||
struct WebHostAccess {
|
||||
memory: JsValue,
|
||||
table: JsValue,
|
||||
dsp_global: JsValue,
|
||||
rsp_global: JsValue,
|
||||
fsp_global: JsValue,
|
||||
}
|
||||
|
||||
impl WebHostAccess {
|
||||
fn buffer(&self) -> js_sys::ArrayBuffer {
|
||||
let buf = Reflect::get(&self.memory, &"buffer".into()).unwrap();
|
||||
buf.unchecked_into()
|
||||
}
|
||||
}
|
||||
|
||||
impl HostAccess for WebHostAccess {
|
||||
fn mem_read_i32(&mut self, addr: u32) -> i32 {
|
||||
let view = js_sys::Int32Array::new(&self.buffer());
|
||||
view.get_index(addr / 4)
|
||||
}
|
||||
|
||||
fn mem_write_i32(&mut self, addr: u32, val: i32) {
|
||||
let view = js_sys::Int32Array::new(&self.buffer());
|
||||
view.set_index(addr / 4, val);
|
||||
}
|
||||
|
||||
fn mem_read_u8(&mut self, addr: u32) -> u8 {
|
||||
let view = Uint8Array::new(&self.buffer());
|
||||
view.get_index(addr)
|
||||
}
|
||||
|
||||
fn mem_write_u8(&mut self, addr: u32, val: u8) {
|
||||
let view = Uint8Array::new(&self.buffer());
|
||||
view.set_index(addr, val);
|
||||
}
|
||||
|
||||
fn mem_read_slice(&mut self, addr: u32, len: usize) -> Vec<u8> {
|
||||
let view = Uint8Array::new(&self.buffer());
|
||||
let sub = view.subarray(addr, addr + len as u32);
|
||||
sub.to_vec()
|
||||
}
|
||||
|
||||
fn mem_write_slice(&mut self, addr: u32, data: &[u8]) {
|
||||
let view = Uint8Array::new(&self.buffer());
|
||||
let src = Uint8Array::from(data);
|
||||
view.set(&src, addr);
|
||||
}
|
||||
|
||||
fn mem_len(&mut self) -> usize {
|
||||
let buf = self.buffer();
|
||||
buf.byte_length() as usize
|
||||
}
|
||||
|
||||
fn get_dsp(&mut self) -> u32 {
|
||||
Reflect::get(&self.dsp_global, &"value".into())
|
||||
.unwrap()
|
||||
.as_f64()
|
||||
.unwrap() as u32
|
||||
}
|
||||
|
||||
fn set_dsp(&mut self, val: u32) {
|
||||
Reflect::set(
|
||||
&self.dsp_global,
|
||||
&"value".into(),
|
||||
&JsValue::from(val as i32),
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
fn get_rsp(&mut self) -> u32 {
|
||||
Reflect::get(&self.rsp_global, &"value".into())
|
||||
.unwrap()
|
||||
.as_f64()
|
||||
.unwrap() as u32
|
||||
}
|
||||
|
||||
fn set_rsp(&mut self, val: u32) {
|
||||
Reflect::set(
|
||||
&self.rsp_global,
|
||||
&"value".into(),
|
||||
&JsValue::from(val as i32),
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
fn get_fsp(&mut self) -> u32 {
|
||||
Reflect::get(&self.fsp_global, &"value".into())
|
||||
.unwrap()
|
||||
.as_f64()
|
||||
.unwrap() as u32
|
||||
}
|
||||
|
||||
fn set_fsp(&mut self, val: u32) {
|
||||
Reflect::set(
|
||||
&self.fsp_global,
|
||||
&"value".into(),
|
||||
&JsValue::from(val as i32),
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
fn call_func(&mut self, fn_index: u32) -> anyhow::Result<()> {
|
||||
let get_fn = Reflect::get(&self.table, &"get".into()).unwrap();
|
||||
let get_fn: Function = get_fn.unchecked_into();
|
||||
let func = get_fn
|
||||
.call1(&self.table, &JsValue::from(fn_index))
|
||||
.map_err(|e| anyhow::anyhow!("table.get({fn_index}) failed: {e:?}"))?;
|
||||
let func: Function = func
|
||||
.dyn_into()
|
||||
.map_err(|_| anyhow::anyhow!("table entry {fn_index} is not a function"))?;
|
||||
func.call0(&JsValue::NULL)
|
||||
.map_err(|e| anyhow::anyhow!("call_func({fn_index}) failed: {e:?}"))?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Helper: create a WebAssembly.Global with mutable i32.
|
||||
fn make_global(init: u32) -> JsValue {
|
||||
let desc = Object::new();
|
||||
Reflect::set(&desc, &"value".into(), &"i32".into()).unwrap();
|
||||
Reflect::set(&desc, &"mutable".into(), &JsValue::TRUE).unwrap();
|
||||
let ctor = Reflect::get(&js_sys::global(), &"WebAssembly".into())
|
||||
.and_then(|wa| Reflect::get(&wa, &"Global".into()))
|
||||
.unwrap();
|
||||
let args = js_sys::Array::new();
|
||||
args.push(&desc);
|
||||
args.push(&JsValue::from(init as i32));
|
||||
Reflect::construct(&ctor.unchecked_into::<Function>(), &args).unwrap()
|
||||
}
|
||||
|
||||
/// Helper: build the import object for instantiating compiled Forth modules.
|
||||
fn build_imports(
|
||||
emit: &JsValue,
|
||||
memory: &JsValue,
|
||||
dsp: &JsValue,
|
||||
rsp: &JsValue,
|
||||
fsp: &JsValue,
|
||||
table: &JsValue,
|
||||
) -> Object {
|
||||
let env = Object::new();
|
||||
Reflect::set(&env, &"emit".into(), emit).unwrap();
|
||||
Reflect::set(&env, &"memory".into(), memory).unwrap();
|
||||
Reflect::set(&env, &"dsp".into(), dsp).unwrap();
|
||||
Reflect::set(&env, &"rsp".into(), rsp).unwrap();
|
||||
Reflect::set(&env, &"fsp".into(), fsp).unwrap();
|
||||
Reflect::set(&env, &"table".into(), table).unwrap();
|
||||
let imports = Object::new();
|
||||
Reflect::set(&imports, &"env".into(), &env).unwrap();
|
||||
imports
|
||||
}
|
||||
|
||||
impl Runtime for WebRuntime {
|
||||
fn new(
|
||||
memory_pages: u32,
|
||||
table_size: u32,
|
||||
dsp_init: u32,
|
||||
rsp_init: u32,
|
||||
fsp_init: u32,
|
||||
output: Arc<Mutex<String>>,
|
||||
) -> anyhow::Result<Self> {
|
||||
// WebAssembly.Memory({initial: pages})
|
||||
let mem_desc = Object::new();
|
||||
Reflect::set(&mem_desc, &"initial".into(), &JsValue::from(memory_pages)).unwrap();
|
||||
let memory = WebAssembly::Memory::new(&mem_desc)
|
||||
.map_err(|e| anyhow::anyhow!("Memory::new failed: {e:?}"))?;
|
||||
let memory: JsValue = memory.into();
|
||||
|
||||
// WebAssembly.Table({element: 'anyfunc', initial: size})
|
||||
let tbl_desc = Object::new();
|
||||
Reflect::set(&tbl_desc, &"element".into(), &"anyfunc".into()).unwrap();
|
||||
Reflect::set(&tbl_desc, &"initial".into(), &JsValue::from(table_size)).unwrap();
|
||||
let table = WebAssembly::Table::new(&tbl_desc)
|
||||
.map_err(|e| anyhow::anyhow!("Table::new failed: {e:?}"))?;
|
||||
let table: JsValue = table.into();
|
||||
|
||||
let dsp_global = make_global(dsp_init);
|
||||
let rsp_global = make_global(rsp_init);
|
||||
let fsp_global = make_global(fsp_init);
|
||||
|
||||
// Create emit function: WebAssembly.Function({parameters:['i32'],results:[]}, closure)
|
||||
let out_ref = Arc::clone(&output);
|
||||
let emit_closure = Closure::wrap(Box::new(move |code: i32| {
|
||||
let ch = code as u8 as char;
|
||||
out_ref.lock().unwrap().push(ch);
|
||||
}) as Box<dyn FnMut(i32)>);
|
||||
|
||||
// Use WebAssembly.Function if available, else wrap in a tiny module
|
||||
let emit_func = make_wasm_function_i32(&emit_closure.as_ref().into());
|
||||
let mut closures = vec![emit_closure.into_js_value()];
|
||||
let _ = &mut closures; // keep alive
|
||||
|
||||
Ok(WebRuntime {
|
||||
memory,
|
||||
table,
|
||||
dsp_global,
|
||||
rsp_global,
|
||||
fsp_global,
|
||||
emit_func,
|
||||
output,
|
||||
_closures: closures,
|
||||
})
|
||||
}
|
||||
|
||||
// -- Memory --
|
||||
|
||||
fn mem_read_i32(&mut self, addr: u32) -> i32 {
|
||||
let buf: js_sys::ArrayBuffer = Reflect::get(&self.memory, &"buffer".into())
|
||||
.unwrap()
|
||||
.unchecked_into();
|
||||
let view = js_sys::Int32Array::new(&buf);
|
||||
view.get_index(addr / 4)
|
||||
}
|
||||
|
||||
fn mem_write_i32(&mut self, addr: u32, val: i32) {
|
||||
let buf: js_sys::ArrayBuffer = Reflect::get(&self.memory, &"buffer".into())
|
||||
.unwrap()
|
||||
.unchecked_into();
|
||||
let view = js_sys::Int32Array::new(&buf);
|
||||
view.set_index(addr / 4, val);
|
||||
}
|
||||
|
||||
fn mem_read_u8(&mut self, addr: u32) -> u8 {
|
||||
let buf: js_sys::ArrayBuffer = Reflect::get(&self.memory, &"buffer".into())
|
||||
.unwrap()
|
||||
.unchecked_into();
|
||||
let view = Uint8Array::new(&buf);
|
||||
view.get_index(addr)
|
||||
}
|
||||
|
||||
fn mem_write_u8(&mut self, addr: u32, val: u8) {
|
||||
let buf: js_sys::ArrayBuffer = Reflect::get(&self.memory, &"buffer".into())
|
||||
.unwrap()
|
||||
.unchecked_into();
|
||||
let view = Uint8Array::new(&buf);
|
||||
view.set_index(addr, val);
|
||||
}
|
||||
|
||||
fn mem_read_slice(&mut self, addr: u32, len: usize) -> Vec<u8> {
|
||||
let buf: js_sys::ArrayBuffer = Reflect::get(&self.memory, &"buffer".into())
|
||||
.unwrap()
|
||||
.unchecked_into();
|
||||
let view = Uint8Array::new(&buf);
|
||||
view.subarray(addr, addr + len as u32).to_vec()
|
||||
}
|
||||
|
||||
fn mem_write_slice(&mut self, addr: u32, data: &[u8]) {
|
||||
let buf: js_sys::ArrayBuffer = Reflect::get(&self.memory, &"buffer".into())
|
||||
.unwrap()
|
||||
.unchecked_into();
|
||||
let view = Uint8Array::new(&buf);
|
||||
let src = Uint8Array::from(data);
|
||||
view.set(&src, addr);
|
||||
}
|
||||
|
||||
fn mem_len(&mut self) -> usize {
|
||||
let buf: js_sys::ArrayBuffer = Reflect::get(&self.memory, &"buffer".into())
|
||||
.unwrap()
|
||||
.unchecked_into();
|
||||
buf.byte_length() as usize
|
||||
}
|
||||
|
||||
// -- Globals --
|
||||
|
||||
fn get_dsp(&mut self) -> u32 {
|
||||
Reflect::get(&self.dsp_global, &"value".into())
|
||||
.unwrap()
|
||||
.as_f64()
|
||||
.unwrap() as u32
|
||||
}
|
||||
|
||||
fn set_dsp(&mut self, val: u32) {
|
||||
Reflect::set(
|
||||
&self.dsp_global,
|
||||
&"value".into(),
|
||||
&JsValue::from(val as i32),
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
fn get_rsp(&mut self) -> u32 {
|
||||
Reflect::get(&self.rsp_global, &"value".into())
|
||||
.unwrap()
|
||||
.as_f64()
|
||||
.unwrap() as u32
|
||||
}
|
||||
|
||||
fn set_rsp(&mut self, val: u32) {
|
||||
Reflect::set(
|
||||
&self.rsp_global,
|
||||
&"value".into(),
|
||||
&JsValue::from(val as i32),
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
fn get_fsp(&mut self) -> u32 {
|
||||
Reflect::get(&self.fsp_global, &"value".into())
|
||||
.unwrap()
|
||||
.as_f64()
|
||||
.unwrap() as u32
|
||||
}
|
||||
|
||||
fn set_fsp(&mut self, val: u32) {
|
||||
Reflect::set(
|
||||
&self.fsp_global,
|
||||
&"value".into(),
|
||||
&JsValue::from(val as i32),
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
// -- Table --
|
||||
|
||||
fn table_size(&mut self) -> u32 {
|
||||
let len = Reflect::get(&self.table, &"length".into()).unwrap();
|
||||
len.as_f64().unwrap() as u32
|
||||
}
|
||||
|
||||
fn ensure_table_size(&mut self, needed: u32) -> anyhow::Result<()> {
|
||||
let current = self.table_size();
|
||||
if needed >= current {
|
||||
let grow = needed - current + 64;
|
||||
let grow_fn: Function = Reflect::get(&self.table, &"grow".into())
|
||||
.unwrap()
|
||||
.unchecked_into();
|
||||
grow_fn
|
||||
.call1(&self.table, &JsValue::from(grow))
|
||||
.map_err(|e| anyhow::anyhow!("table.grow failed: {e:?}"))?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// -- Compilation and execution --
|
||||
|
||||
fn instantiate_and_install(&mut self, wasm_bytes: &[u8], fn_index: u32) -> anyhow::Result<()> {
|
||||
self.ensure_table_size(fn_index)?;
|
||||
|
||||
let bytes = Uint8Array::from(wasm_bytes);
|
||||
let module = WebAssembly::Module::new(&bytes.into())
|
||||
.map_err(|e| anyhow::anyhow!("Module::new failed: {e:?}"))?;
|
||||
|
||||
let imports = build_imports(
|
||||
&self.emit_func,
|
||||
&self.memory,
|
||||
&self.dsp_global,
|
||||
&self.rsp_global,
|
||||
&self.fsp_global,
|
||||
&self.table,
|
||||
);
|
||||
|
||||
let instance = WebAssembly::Instance::new(&module, &imports)
|
||||
.map_err(|e| anyhow::anyhow!("Instance::new failed: {e:?}"))?;
|
||||
|
||||
// Single-word modules export "fn"; multi-word modules use element section.
|
||||
let exports = Reflect::get(&instance, &"exports".into()).unwrap();
|
||||
if let Ok(func) = Reflect::get(&exports, &"fn".into())
|
||||
&& func.is_function()
|
||||
{
|
||||
let set_fn: Function = Reflect::get(&self.table, &"set".into())
|
||||
.unwrap()
|
||||
.unchecked_into();
|
||||
set_fn
|
||||
.call2(&self.table, &JsValue::from(fn_index), &func)
|
||||
.map_err(|e| anyhow::anyhow!("table.set failed: {e:?}"))?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn call_func(&mut self, fn_index: u32) -> anyhow::Result<()> {
|
||||
let get_fn: Function = Reflect::get(&self.table, &"get".into())
|
||||
.unwrap()
|
||||
.unchecked_into();
|
||||
let func = get_fn
|
||||
.call1(&self.table, &JsValue::from(fn_index))
|
||||
.map_err(|e| anyhow::anyhow!("table.get({fn_index}) failed: {e:?}"))?;
|
||||
let func: Function = func
|
||||
.dyn_into()
|
||||
.map_err(|_| anyhow::anyhow!("table entry {fn_index} is not callable"))?;
|
||||
func.call0(&JsValue::NULL)
|
||||
.map_err(|e| anyhow::anyhow!("call_func({fn_index}) failed: {e:?}"))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// -- Host functions --
|
||||
|
||||
fn register_host_func(&mut self, fn_index: u32, f: HostFn) -> anyhow::Result<()> {
|
||||
self.ensure_table_size(fn_index)?;
|
||||
|
||||
let memory = self.memory.clone();
|
||||
let table = self.table.clone();
|
||||
let dsp = self.dsp_global.clone();
|
||||
let rsp = self.rsp_global.clone();
|
||||
let fsp = self.fsp_global.clone();
|
||||
|
||||
let closure = Closure::wrap(Box::new(move || {
|
||||
let mut ctx = WebHostAccess {
|
||||
memory: memory.clone(),
|
||||
table: table.clone(),
|
||||
dsp_global: dsp.clone(),
|
||||
rsp_global: rsp.clone(),
|
||||
fsp_global: fsp.clone(),
|
||||
};
|
||||
if let Err(e) = f(&mut ctx) {
|
||||
// Throw a JS error to propagate the Forth error (e.g. ABORT, THROW)
|
||||
wasm_bindgen::throw_str(&e.to_string());
|
||||
}
|
||||
}) as Box<dyn FnMut()>);
|
||||
|
||||
let wasm_func = make_wasm_function_void(&closure.as_ref().into());
|
||||
|
||||
let set_fn: Function = Reflect::get(&self.table, &"set".into())
|
||||
.unwrap()
|
||||
.unchecked_into();
|
||||
set_fn
|
||||
.call2(&self.table, &JsValue::from(fn_index), &wasm_func)
|
||||
.map_err(|e| anyhow::anyhow!("table.set({fn_index}) failed: {e:?}"))?;
|
||||
|
||||
self._closures.push(closure.into_js_value());
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Create a `WebAssembly.Function({parameters:['i32'],results:[]}, jsFn)`.
|
||||
/// Falls back to a wrapper module if `WebAssembly.Function` is unavailable.
|
||||
fn make_wasm_function_i32(js_fn: &JsValue) -> JsValue {
|
||||
if let Ok(wasm_func_ctor) = get_wasm_function_ctor() {
|
||||
let desc = Object::new();
|
||||
let params = js_sys::Array::new();
|
||||
params.push(&"i32".into());
|
||||
Reflect::set(&desc, &"parameters".into(), ¶ms).unwrap();
|
||||
Reflect::set(&desc, &"results".into(), &js_sys::Array::new()).unwrap();
|
||||
let args = js_sys::Array::new();
|
||||
args.push(&desc);
|
||||
args.push(js_fn);
|
||||
Reflect::construct(&wasm_func_ctor.unchecked_into::<Function>(), &args).unwrap()
|
||||
} else {
|
||||
// Fallback: create a tiny WASM module that wraps the JS function
|
||||
make_wrapper_module_i32(js_fn)
|
||||
}
|
||||
}
|
||||
|
||||
/// Create a `WebAssembly.Function({parameters:[],results:[]}, jsFn)`.
|
||||
fn make_wasm_function_void(js_fn: &JsValue) -> JsValue {
|
||||
if let Ok(wasm_func_ctor) = get_wasm_function_ctor() {
|
||||
let desc = Object::new();
|
||||
Reflect::set(&desc, &"parameters".into(), &js_sys::Array::new()).unwrap();
|
||||
Reflect::set(&desc, &"results".into(), &js_sys::Array::new()).unwrap();
|
||||
let args = js_sys::Array::new();
|
||||
args.push(&desc);
|
||||
args.push(js_fn);
|
||||
Reflect::construct(&wasm_func_ctor.unchecked_into::<Function>(), &args).unwrap()
|
||||
} else {
|
||||
make_wrapper_module_void(js_fn)
|
||||
}
|
||||
}
|
||||
|
||||
/// Try to get the WebAssembly.Function constructor (Chrome 78+, Firefox 78+).
|
||||
fn get_wasm_function_ctor() -> Result<Function, ()> {
|
||||
let wa = Reflect::get(&js_sys::global(), &"WebAssembly".into()).map_err(|_| ())?;
|
||||
let ctor = Reflect::get(&wa, &"Function".into()).map_err(|_| ())?;
|
||||
if ctor.is_function() {
|
||||
Ok(ctor.unchecked_into())
|
||||
} else {
|
||||
Err(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Fallback: create a minimal WASM module that imports and re-exports a void→void function.
|
||||
fn make_wrapper_module_void(js_fn: &JsValue) -> JsValue {
|
||||
// (module (import "e" "f" (func)) (export "f" (func 0)))
|
||||
#[rustfmt::skip]
|
||||
let bytes: &[u8] = &[
|
||||
0x00, 0x61, 0x73, 0x6d, // magic
|
||||
0x01, 0x00, 0x00, 0x00, // version
|
||||
// type section: 1 type, () -> ()
|
||||
0x01, 0x04, 0x01, 0x60, 0x00, 0x00,
|
||||
// import section: import "e" "f" func type 0
|
||||
0x02, 0x07, 0x01, 0x01, 0x65, 0x01, 0x66, 0x00, 0x00,
|
||||
// export section: export "f" func 0
|
||||
0x07, 0x05, 0x01, 0x01, 0x66, 0x00, 0x00,
|
||||
];
|
||||
let u8arr = Uint8Array::from(bytes);
|
||||
let module = WebAssembly::Module::new(&u8arr.into()).unwrap();
|
||||
let env = Object::new();
|
||||
Reflect::set(&env, &"f".into(), js_fn).unwrap();
|
||||
let imports = Object::new();
|
||||
Reflect::set(&imports, &"e".into(), &env).unwrap();
|
||||
let instance = WebAssembly::Instance::new(&module, &imports).unwrap();
|
||||
let exports = Reflect::get(&instance, &"exports".into()).unwrap();
|
||||
Reflect::get(&exports, &"f".into()).unwrap()
|
||||
}
|
||||
|
||||
/// Fallback: create a minimal WASM module that imports and re-exports an (i32)→() function.
|
||||
fn make_wrapper_module_i32(js_fn: &JsValue) -> JsValue {
|
||||
// (module (import "e" "f" (func (param i32))) (export "f" (func 0)))
|
||||
#[rustfmt::skip]
|
||||
let bytes: &[u8] = &[
|
||||
0x00, 0x61, 0x73, 0x6d,
|
||||
0x01, 0x00, 0x00, 0x00,
|
||||
// type section: 1 type, (i32) -> ()
|
||||
0x01, 0x05, 0x01, 0x60, 0x01, 0x7f, 0x00,
|
||||
// import section: import "e" "f" func type 0
|
||||
0x02, 0x07, 0x01, 0x01, 0x65, 0x01, 0x66, 0x00, 0x00,
|
||||
// export section: export "f" func 0
|
||||
0x07, 0x05, 0x01, 0x01, 0x66, 0x00, 0x00,
|
||||
];
|
||||
let u8arr = Uint8Array::from(bytes);
|
||||
let module = WebAssembly::Module::new(&u8arr.into()).unwrap();
|
||||
let env = Object::new();
|
||||
Reflect::set(&env, &"f".into(), js_fn).unwrap();
|
||||
let imports = Object::new();
|
||||
Reflect::set(&imports, &"e".into(), &env).unwrap();
|
||||
let instance = WebAssembly::Instance::new(&module, &imports).unwrap();
|
||||
let exports = Reflect::get(&instance, &"exports".into()).unwrap();
|
||||
Reflect::get(&exports, &"f".into()).unwrap()
|
||||
}
|
||||
@@ -0,0 +1,259 @@
|
||||
import init, { WaferRepl } from './pkg/wafer_web.js';
|
||||
|
||||
let repl = null;
|
||||
const history = [];
|
||||
let historyIdx = -1;
|
||||
|
||||
const WORD_CATEGORIES = {
|
||||
'Stack': 'DUP DROP SWAP OVER ROT NIP TUCK 2DUP 2DROP 2SWAP 2OVER PICK ROLL DEPTH .S'.split(' '),
|
||||
'Arithmetic': '+ - * / MOD /MOD NEGATE ABS MIN MAX M* UM* UM/MOD FM/MOD SM/REM */ */MOD'.split(' '),
|
||||
'Comparison': '= <> < > 0= 0< 0<> 0> U< U> WITHIN'.split(' '),
|
||||
'Logic': 'AND OR XOR INVERT LSHIFT RSHIFT TRUE FALSE'.split(' '),
|
||||
'Memory': '@ ! C@ C! +! HERE ALLOT , C, CELLS CELL+ MOVE FILL ERASE BLANK'.split(' '),
|
||||
'I/O': '. U. .R U.R EMIT CR SPACE SPACES TYPE ." .( .S'.split(' '),
|
||||
'Defining': ': ; VARIABLE CONSTANT VALUE CREATE DOES> DEFER IS TO :NONAME IMMEDIATE'.split(' '),
|
||||
'Control': 'IF ELSE THEN DO LOOP +LOOP I J LEAVE BEGIN UNTIL WHILE REPEAT AGAIN ?DO CASE OF ENDOF ENDCASE EXIT RECURSE'.split(' '),
|
||||
'Strings': 'S" S\\" C" COUNT COMPARE SEARCH /STRING -TRAILING'.split(' '),
|
||||
'Double': 'S>D D>S D+ D- DNEGATE DABS D= D< D. D.R 2@ 2! 2CONSTANT 2VARIABLE'.split(' '),
|
||||
};
|
||||
|
||||
const output = document.getElementById('output');
|
||||
const input = document.getElementById('input');
|
||||
const prompt = document.getElementById('prompt');
|
||||
const stackBar = document.getElementById('stack-bar');
|
||||
|
||||
function appendLine(text, cls) {
|
||||
const span = document.createElement('span');
|
||||
span.className = `line ${cls}`;
|
||||
span.textContent = text + '\n';
|
||||
output.appendChild(span);
|
||||
output.scrollTop = output.scrollHeight;
|
||||
}
|
||||
|
||||
function updatePrompt() {
|
||||
if (!repl) return;
|
||||
prompt.textContent = repl.is_compiling() ? '] ' : '> ';
|
||||
}
|
||||
|
||||
function updateStack() {
|
||||
if (!repl) return;
|
||||
try {
|
||||
const stack = repl.data_stack();
|
||||
if (stack.length === 0) {
|
||||
stackBar.textContent = 'Stack: (empty)';
|
||||
} else {
|
||||
stackBar.textContent = `Stack <${stack.length}> ${stack.join(' ')}`;
|
||||
}
|
||||
} catch {
|
||||
stackBar.textContent = 'Stack: (error)';
|
||||
}
|
||||
}
|
||||
|
||||
function updateUserWords() {
|
||||
const cat = document.getElementById('cat-user');
|
||||
if (!cat) return;
|
||||
// We'll track user words by checking what the REPL evaluates
|
||||
// For now, just show the category
|
||||
}
|
||||
|
||||
function evaluate(line) {
|
||||
if (!repl) return;
|
||||
const trimmed = line.trim();
|
||||
if (!trimmed) return;
|
||||
|
||||
// Add to history
|
||||
history.push(trimmed);
|
||||
historyIdx = history.length;
|
||||
|
||||
try {
|
||||
const result = repl.evaluate(trimmed);
|
||||
// Show input + output on one line (traditional Forth style)
|
||||
const combined = result.length > 0 ? `${trimmed} ${result} ok` : `${trimmed} ok`;
|
||||
appendLine(combined, 'line-ok');
|
||||
} catch (e) {
|
||||
const msg = e.message || String(e);
|
||||
appendLine(`${trimmed}`, 'line-input');
|
||||
appendLine(`Error: ${msg}`, 'line-error');
|
||||
}
|
||||
|
||||
updatePrompt();
|
||||
updateStack();
|
||||
}
|
||||
|
||||
// Input handling
|
||||
input.addEventListener('keydown', (e) => {
|
||||
if (e.key === 'Enter') {
|
||||
evaluate(input.value);
|
||||
input.value = '';
|
||||
} else if (e.key === 'ArrowUp') {
|
||||
e.preventDefault();
|
||||
if (historyIdx > 0) {
|
||||
historyIdx--;
|
||||
input.value = history[historyIdx];
|
||||
}
|
||||
} else if (e.key === 'ArrowDown') {
|
||||
e.preventDefault();
|
||||
if (historyIdx < history.length - 1) {
|
||||
historyIdx++;
|
||||
input.value = history[historyIdx];
|
||||
} else {
|
||||
historyIdx = history.length;
|
||||
input.value = '';
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// Click output to focus input
|
||||
output.addEventListener('click', () => input.focus());
|
||||
|
||||
// Word panel
|
||||
document.getElementById('btn-toggle-words').addEventListener('click', () => {
|
||||
document.getElementById('word-panel').classList.toggle('collapsed');
|
||||
});
|
||||
|
||||
function buildWordPanel() {
|
||||
const container = document.getElementById('word-categories');
|
||||
container.innerHTML = '';
|
||||
for (const [name, words] of Object.entries(WORD_CATEGORIES)) {
|
||||
const cat = document.createElement('div');
|
||||
cat.className = 'word-category';
|
||||
const h4 = document.createElement('h4');
|
||||
h4.textContent = name;
|
||||
h4.addEventListener('click', () => cat.classList.toggle('collapsed'));
|
||||
cat.appendChild(h4);
|
||||
const list = document.createElement('div');
|
||||
list.className = 'word-list';
|
||||
for (const w of words) {
|
||||
const chip = document.createElement('span');
|
||||
chip.className = 'word-chip';
|
||||
chip.textContent = w;
|
||||
chip.title = w;
|
||||
chip.addEventListener('click', () => {
|
||||
input.value += (input.value.length > 0 ? ' ' : '') + w;
|
||||
input.focus();
|
||||
});
|
||||
list.appendChild(chip);
|
||||
}
|
||||
cat.appendChild(list);
|
||||
container.appendChild(cat);
|
||||
}
|
||||
|
||||
// User words category (dynamic)
|
||||
const userCat = document.createElement('div');
|
||||
userCat.className = 'word-category';
|
||||
userCat.id = 'cat-user';
|
||||
const h4 = document.createElement('h4');
|
||||
h4.textContent = 'User Words';
|
||||
h4.addEventListener('click', () => userCat.classList.toggle('collapsed'));
|
||||
userCat.appendChild(h4);
|
||||
const userList = document.createElement('div');
|
||||
userList.className = 'word-list';
|
||||
userList.id = 'user-word-list';
|
||||
userCat.appendChild(userList);
|
||||
container.appendChild(userCat);
|
||||
}
|
||||
|
||||
// Word filter
|
||||
document.getElementById('word-filter').addEventListener('input', (e) => {
|
||||
const q = e.target.value.toUpperCase();
|
||||
document.querySelectorAll('.word-chip').forEach(chip => {
|
||||
chip.style.display = chip.textContent.toUpperCase().includes(q) ? '' : 'none';
|
||||
});
|
||||
});
|
||||
|
||||
// Init code panel
|
||||
document.getElementById('btn-toggle-init').addEventListener('click', () => {
|
||||
const body = document.querySelector('.init-body');
|
||||
body.classList.toggle('collapsed');
|
||||
const btn = document.getElementById('btn-toggle-init');
|
||||
btn.innerHTML = body.classList.contains('collapsed') ? '▼' : '▲';
|
||||
});
|
||||
|
||||
document.getElementById('btn-run-init').addEventListener('click', () => {
|
||||
const code = document.getElementById('init-code').value;
|
||||
if (code.trim()) {
|
||||
// Run each line separately
|
||||
for (const line of code.split('\n')) {
|
||||
if (line.trim()) evaluate(line);
|
||||
}
|
||||
}
|
||||
localStorage.setItem('wafer-init-code', code);
|
||||
});
|
||||
|
||||
// Save init code on change
|
||||
document.getElementById('init-code').addEventListener('input', (e) => {
|
||||
localStorage.setItem('wafer-init-code', e.target.value);
|
||||
});
|
||||
|
||||
// Help
|
||||
document.getElementById('btn-help').addEventListener('click', () => {
|
||||
document.getElementById('help-overlay').classList.remove('hidden');
|
||||
});
|
||||
|
||||
document.getElementById('help-overlay').addEventListener('click', (e) => {
|
||||
if (e.target === e.currentTarget) {
|
||||
document.getElementById('help-overlay').classList.add('hidden');
|
||||
}
|
||||
});
|
||||
|
||||
document.querySelector('.close-help').addEventListener('click', () => {
|
||||
document.getElementById('help-overlay').classList.add('hidden');
|
||||
});
|
||||
|
||||
// Reset
|
||||
document.getElementById('btn-reset').addEventListener('click', () => {
|
||||
if (!repl) return;
|
||||
try {
|
||||
repl.reset();
|
||||
output.innerHTML = '';
|
||||
appendLine('WAFER reset.', 'line-ok');
|
||||
updatePrompt();
|
||||
updateStack();
|
||||
} catch (e) {
|
||||
appendLine(`Reset error: ${e.message}`, 'line-error');
|
||||
}
|
||||
});
|
||||
|
||||
// Boot
|
||||
async function boot() {
|
||||
output.innerHTML = '<div class="loading"><span>Loading WAFER...</span></div>';
|
||||
try {
|
||||
await init();
|
||||
repl = new WaferRepl();
|
||||
output.innerHTML = '';
|
||||
appendLine('WAFER — WebAssembly Forth Engine in Rust', 'line-output');
|
||||
appendLine(`Type Forth at the > prompt. Press ? for help.`, 'line-output');
|
||||
appendLine('', 'line-output');
|
||||
updatePrompt();
|
||||
updateStack();
|
||||
buildWordPanel();
|
||||
|
||||
// Restore and run init code
|
||||
const saved = localStorage.getItem('wafer-init-code');
|
||||
if (saved) {
|
||||
document.getElementById('init-code').value = saved;
|
||||
for (const line of saved.split('\n')) {
|
||||
if (line.trim()) evaluate(line);
|
||||
}
|
||||
}
|
||||
|
||||
// Load from URL hash if present
|
||||
if (location.hash.length > 1) {
|
||||
try {
|
||||
const code = atob(location.hash.slice(1));
|
||||
document.getElementById('init-code').value = code;
|
||||
for (const line of code.split('\n')) {
|
||||
if (line.trim()) evaluate(line);
|
||||
}
|
||||
} catch { /* ignore bad hash */ }
|
||||
}
|
||||
|
||||
input.focus();
|
||||
} catch (e) {
|
||||
output.innerHTML = '';
|
||||
appendLine(`Failed to initialize WAFER: ${e.message || e}`, 'line-error');
|
||||
console.error(e);
|
||||
}
|
||||
}
|
||||
|
||||
boot();
|
||||
@@ -0,0 +1,87 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>WAFER — WebAssembly Forth REPL</title>
|
||||
<link rel="stylesheet" href="style.css">
|
||||
</head>
|
||||
<body>
|
||||
<div id="app">
|
||||
<header>
|
||||
<h1>WAFER <span class="subtitle">WebAssembly Forth Engine in Rust</span></h1>
|
||||
<div class="header-actions">
|
||||
<button id="btn-reset" title="Reset VM">Reset</button>
|
||||
<button id="btn-help" title="Quick reference">?</button>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<div class="main-layout">
|
||||
<!-- Word panel (collapsible sidebar) -->
|
||||
<aside id="word-panel" class="collapsed">
|
||||
<button id="btn-toggle-words" title="Toggle word list">Words</button>
|
||||
<div class="word-content">
|
||||
<input type="text" id="word-filter" placeholder="Filter words...">
|
||||
<div id="word-categories"></div>
|
||||
</div>
|
||||
</aside>
|
||||
|
||||
<!-- Terminal -->
|
||||
<main id="terminal-area">
|
||||
<div id="output" tabindex="-1"></div>
|
||||
<div id="input-line">
|
||||
<span id="prompt">> </span>
|
||||
<input type="text" id="input" autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" autofocus>
|
||||
</div>
|
||||
<div id="stack-bar"></div>
|
||||
</main>
|
||||
</div>
|
||||
|
||||
<!-- Init code panel -->
|
||||
<div id="init-panel">
|
||||
<div class="init-header">
|
||||
<span>Init Code</span>
|
||||
<div class="init-actions">
|
||||
<button id="btn-run-init" title="Run init code">Run</button>
|
||||
<button id="btn-toggle-init" title="Expand/collapse">▲</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="init-body collapsed">
|
||||
<textarea id="init-code" placeholder="\ Forth code to run on startup : greet cr ." Hello WAFER!" ; greet" spellcheck="false"></textarea>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="help-overlay" class="hidden">
|
||||
<div class="help-content">
|
||||
<h2>Quick Reference</h2>
|
||||
<button class="close-help">×</button>
|
||||
<div class="help-columns">
|
||||
<div>
|
||||
<h3>Stack</h3>
|
||||
<code>DUP DROP SWAP OVER ROT NIP TUCK 2DUP 2DROP 2SWAP 2OVER PICK ROLL DEPTH .S</code>
|
||||
<h3>Arithmetic</h3>
|
||||
<code>+ - * / MOD /MOD NEGATE ABS MIN MAX</code>
|
||||
<h3>Comparison</h3>
|
||||
<code>= <> < > 0= 0< U<</code>
|
||||
<h3>Logic</h3>
|
||||
<code>AND OR XOR INVERT LSHIFT RSHIFT</code>
|
||||
</div>
|
||||
<div>
|
||||
<h3>Memory</h3>
|
||||
<code>@ ! C@ C! +! HERE ALLOT , C, CELLS CELL+ MOVE FILL</code>
|
||||
<h3>I/O</h3>
|
||||
<code>. U. .R U.R EMIT CR SPACE SPACES TYPE ." .S</code>
|
||||
<h3>Defining</h3>
|
||||
<code>: ; VARIABLE CONSTANT VALUE CREATE DOES> DEFER IS</code>
|
||||
<h3>Control</h3>
|
||||
<code>IF ELSE THEN DO LOOP +LOOP I J LEAVE BEGIN UNTIL WHILE REPEAT AGAIN</code>
|
||||
</div>
|
||||
</div>
|
||||
<p class="help-footer">Type Forth at the <code>></code> prompt. Press Enter to evaluate. Up/Down for history.</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script type="module" src="app.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,381 @@
|
||||
:root {
|
||||
--bg: #0d1117;
|
||||
--bg-panel: #161b22;
|
||||
--bg-input: #0d1117;
|
||||
--border: #30363d;
|
||||
--text: #e6edf3;
|
||||
--text-dim: #8b949e;
|
||||
--accent: #58a6ff;
|
||||
--accent-dim: #1f6feb;
|
||||
--ok: #3fb950;
|
||||
--error: #f85149;
|
||||
--prompt: #d2a8ff;
|
||||
--output: #79c0ff;
|
||||
--font-mono: 'JetBrains Mono', 'Fira Code', 'Cascadia Code', 'Consolas', monospace;
|
||||
}
|
||||
|
||||
* { margin: 0; padding: 0; box-sizing: border-box; }
|
||||
|
||||
body {
|
||||
font-family: var(--font-mono);
|
||||
font-size: 14px;
|
||||
background: var(--bg);
|
||||
color: var(--text);
|
||||
height: 100vh;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
#app {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
height: 100vh;
|
||||
}
|
||||
|
||||
/* Header */
|
||||
header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
padding: 8px 16px;
|
||||
background: var(--bg-panel);
|
||||
border-bottom: 1px solid var(--border);
|
||||
}
|
||||
|
||||
header h1 {
|
||||
font-size: 16px;
|
||||
font-weight: 600;
|
||||
color: var(--accent);
|
||||
}
|
||||
|
||||
header .subtitle {
|
||||
font-size: 11px;
|
||||
color: var(--text-dim);
|
||||
font-weight: 400;
|
||||
margin-left: 8px;
|
||||
}
|
||||
|
||||
.header-actions { display: flex; gap: 8px; }
|
||||
|
||||
.header-actions button, .init-actions button, #btn-toggle-words {
|
||||
background: var(--bg);
|
||||
border: 1px solid var(--border);
|
||||
color: var(--text-dim);
|
||||
padding: 4px 12px;
|
||||
border-radius: 6px;
|
||||
cursor: pointer;
|
||||
font-family: var(--font-mono);
|
||||
font-size: 12px;
|
||||
transition: all 0.15s;
|
||||
}
|
||||
|
||||
.header-actions button:hover, .init-actions button:hover, #btn-toggle-words:hover {
|
||||
color: var(--text);
|
||||
border-color: var(--accent-dim);
|
||||
background: var(--bg-panel);
|
||||
}
|
||||
|
||||
/* Main layout */
|
||||
.main-layout {
|
||||
display: flex;
|
||||
flex: 1;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
/* Word panel */
|
||||
#word-panel {
|
||||
width: 260px;
|
||||
background: var(--bg-panel);
|
||||
border-right: 1px solid var(--border);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
transition: width 0.2s;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
#word-panel.collapsed {
|
||||
width: 42px;
|
||||
}
|
||||
|
||||
#word-panel.collapsed .word-content {
|
||||
display: none;
|
||||
}
|
||||
|
||||
#btn-toggle-words {
|
||||
writing-mode: vertical-rl;
|
||||
text-orientation: mixed;
|
||||
padding: 12px 6px;
|
||||
border: none;
|
||||
border-radius: 0;
|
||||
background: transparent;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
#word-panel:not(.collapsed) #btn-toggle-words {
|
||||
writing-mode: horizontal-tb;
|
||||
padding: 8px 12px;
|
||||
border-bottom: 1px solid var(--border);
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
.word-content {
|
||||
flex: 1;
|
||||
overflow-y: auto;
|
||||
padding: 8px;
|
||||
}
|
||||
|
||||
#word-filter {
|
||||
width: 100%;
|
||||
background: var(--bg);
|
||||
border: 1px solid var(--border);
|
||||
color: var(--text);
|
||||
padding: 6px 8px;
|
||||
border-radius: 4px;
|
||||
font-family: var(--font-mono);
|
||||
font-size: 12px;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
|
||||
.word-category h4 {
|
||||
color: var(--accent);
|
||||
font-size: 11px;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.5px;
|
||||
margin: 12px 0 4px;
|
||||
cursor: pointer;
|
||||
user-select: none;
|
||||
}
|
||||
|
||||
.word-category h4::before {
|
||||
content: '\25BE ';
|
||||
font-size: 10px;
|
||||
}
|
||||
|
||||
.word-category.collapsed h4::before {
|
||||
content: '\25B8 ';
|
||||
}
|
||||
|
||||
.word-category.collapsed .word-list {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.word-list {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 3px;
|
||||
}
|
||||
|
||||
.word-chip {
|
||||
background: var(--bg);
|
||||
border: 1px solid var(--border);
|
||||
color: var(--text-dim);
|
||||
padding: 2px 6px;
|
||||
border-radius: 3px;
|
||||
font-size: 11px;
|
||||
cursor: pointer;
|
||||
transition: all 0.1s;
|
||||
}
|
||||
|
||||
.word-chip:hover {
|
||||
color: var(--text);
|
||||
border-color: var(--accent-dim);
|
||||
background: rgba(88, 166, 255, 0.1);
|
||||
}
|
||||
|
||||
.word-chip.user-word {
|
||||
border-color: var(--ok);
|
||||
color: var(--ok);
|
||||
}
|
||||
|
||||
/* Terminal */
|
||||
#terminal-area {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
#output {
|
||||
flex: 1;
|
||||
overflow-y: auto;
|
||||
padding: 12px 16px;
|
||||
white-space: pre-wrap;
|
||||
word-break: break-all;
|
||||
line-height: 1.6;
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.line { margin: 0; }
|
||||
.line-input { color: var(--text); }
|
||||
.line-output { color: var(--output); }
|
||||
.line-ok { color: var(--ok); }
|
||||
.line-error { color: var(--error); }
|
||||
|
||||
#input-line {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
padding: 8px 16px;
|
||||
background: var(--bg-panel);
|
||||
border-top: 1px solid var(--border);
|
||||
}
|
||||
|
||||
#prompt {
|
||||
color: var(--prompt);
|
||||
font-weight: 600;
|
||||
margin-right: 4px;
|
||||
user-select: none;
|
||||
}
|
||||
|
||||
#input {
|
||||
flex: 1;
|
||||
background: transparent;
|
||||
border: none;
|
||||
color: var(--text);
|
||||
font-family: var(--font-mono);
|
||||
font-size: 14px;
|
||||
outline: none;
|
||||
caret-color: var(--accent);
|
||||
}
|
||||
|
||||
#stack-bar {
|
||||
padding: 4px 16px;
|
||||
font-size: 11px;
|
||||
color: var(--text-dim);
|
||||
background: var(--bg-panel);
|
||||
border-top: 1px solid var(--border);
|
||||
min-height: 24px;
|
||||
}
|
||||
|
||||
/* Init panel */
|
||||
#init-panel {
|
||||
border-top: 1px solid var(--border);
|
||||
background: var(--bg-panel);
|
||||
}
|
||||
|
||||
.init-header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
padding: 4px 16px;
|
||||
cursor: pointer;
|
||||
font-size: 12px;
|
||||
color: var(--text-dim);
|
||||
}
|
||||
|
||||
.init-body {
|
||||
overflow: hidden;
|
||||
transition: max-height 0.2s;
|
||||
max-height: 200px;
|
||||
}
|
||||
|
||||
.init-body.collapsed {
|
||||
max-height: 0;
|
||||
}
|
||||
|
||||
#init-code {
|
||||
width: 100%;
|
||||
height: 120px;
|
||||
background: var(--bg);
|
||||
border: none;
|
||||
border-top: 1px solid var(--border);
|
||||
color: var(--text);
|
||||
font-family: var(--font-mono);
|
||||
font-size: 13px;
|
||||
padding: 8px 16px;
|
||||
resize: vertical;
|
||||
outline: none;
|
||||
}
|
||||
|
||||
/* Help overlay */
|
||||
#help-overlay {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
background: rgba(0, 0, 0, 0.7);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
z-index: 100;
|
||||
}
|
||||
|
||||
#help-overlay.hidden { display: none; }
|
||||
|
||||
.help-content {
|
||||
background: var(--bg-panel);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 12px;
|
||||
padding: 24px;
|
||||
max-width: 640px;
|
||||
max-height: 80vh;
|
||||
overflow-y: auto;
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.help-content h2 {
|
||||
color: var(--accent);
|
||||
font-size: 18px;
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
|
||||
.help-content h3 {
|
||||
color: var(--text-dim);
|
||||
font-size: 12px;
|
||||
text-transform: uppercase;
|
||||
margin: 12px 0 4px;
|
||||
}
|
||||
|
||||
.help-content code {
|
||||
display: block;
|
||||
color: var(--text);
|
||||
font-size: 12px;
|
||||
line-height: 1.8;
|
||||
word-spacing: 8px;
|
||||
}
|
||||
|
||||
.help-columns {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
gap: 16px;
|
||||
}
|
||||
|
||||
.help-footer {
|
||||
margin-top: 16px;
|
||||
font-size: 12px;
|
||||
color: var(--text-dim);
|
||||
}
|
||||
|
||||
.close-help {
|
||||
position: absolute;
|
||||
top: 12px;
|
||||
right: 16px;
|
||||
background: none;
|
||||
border: none;
|
||||
color: var(--text-dim);
|
||||
font-size: 24px;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.close-help:hover { color: var(--text); }
|
||||
|
||||
/* Loading state */
|
||||
.loading {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
height: 100%;
|
||||
color: var(--text-dim);
|
||||
font-size: 16px;
|
||||
}
|
||||
|
||||
@keyframes pulse {
|
||||
0%, 100% { opacity: 0.4; }
|
||||
50% { opacity: 1; }
|
||||
}
|
||||
|
||||
.loading span {
|
||||
animation: pulse 1.5s ease-in-out infinite;
|
||||
}
|
||||
|
||||
/* Responsive */
|
||||
@media (max-width: 768px) {
|
||||
#word-panel { display: none; }
|
||||
.help-columns { grid-template-columns: 1fr; }
|
||||
}
|
||||
@@ -1,15 +1,5 @@
|
||||
[advisories]
|
||||
ignore = [
|
||||
# wasmtime v31 known issues -- will resolve when upgrading wasmtime
|
||||
{ id = "RUSTSEC-2025-0046", reason = "wasmtime v31: fd_renumber panic" },
|
||||
{ id = "RUSTSEC-2025-0118", reason = "wasmtime v31: shared memory unsoundness" },
|
||||
{ id = "RUSTSEC-2026-0006", reason = "wasmtime v31: f64.copysign segfault" },
|
||||
{ id = "RUSTSEC-2026-0020", reason = "wasmtime v31: WASI resource exhaustion" },
|
||||
{ id = "RUSTSEC-2026-0021", reason = "wasmtime v31: fields instance panic" },
|
||||
# Unmaintained transitive deps from wasmtime/rustyline
|
||||
{ id = "RUSTSEC-2025-0057", reason = "fxhash: transitive dep, no alternative" },
|
||||
{ id = "RUSTSEC-2024-0436", reason = "paste: transitive dep, no alternative" },
|
||||
]
|
||||
ignore = []
|
||||
|
||||
[licenses]
|
||||
allow = [
|
||||
@@ -19,6 +9,7 @@ allow = [
|
||||
"BSD-2-Clause",
|
||||
"BSD-3-Clause",
|
||||
"BSL-1.0",
|
||||
"MPL-2.0",
|
||||
"Unicode-3.0",
|
||||
"Zlib",
|
||||
]
|
||||
@@ -31,15 +22,12 @@ wildcards = "deny"
|
||||
skip = [
|
||||
"getrandom",
|
||||
"hashbrown",
|
||||
"linux-raw-sys",
|
||||
"object",
|
||||
"rustix",
|
||||
"r-efi",
|
||||
"thiserror",
|
||||
"thiserror-impl",
|
||||
"wasm-encoder",
|
||||
"wasmparser",
|
||||
"wast",
|
||||
"windows-sys",
|
||||
"winnow",
|
||||
]
|
||||
|
||||
[sources]
|
||||
|
||||
Reference in New Issue
Block a user