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:
2026-04-13 10:06:37 +02:00
parent 7780ea3ab3
commit 321f001232
20 changed files with 3576 additions and 2707 deletions
+21
View File
@@ -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"
+56
View File
@@ -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(())
}
}
+542
View File
@@ -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(), &params).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()
}
+259
View File
@@ -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') ? '&#x25BC;' : '&#x25B2;';
});
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();
+87
View File
@@ -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">&gt; </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">&#x25B2;</button>
</div>
</div>
<div class="init-body collapsed">
<textarea id="init-code" placeholder="\ Forth code to run on startup&#10;: greet cr .&quot; Hello WAFER!&quot; ;&#10;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">&times;</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>= &lt;&gt; &lt; &gt; 0= 0&lt; U&lt;</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&gt; 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>&gt;</code> prompt. Press Enter to evaluate. Up/Down for history.</p>
</div>
</div>
<script type="module" src="app.js"></script>
</body>
</html>
+381
View File
@@ -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; }
}