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
+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; }
}