Files
WAFER/crates/web/www/app.js
T
Oleksandr Kozachuk f584066a0a feat(repl): usability batch - errors, WORDS, .S, BYE, DUMP, history
Core:
- Uncaught THROW prints its standard message ("Stack underflow
  (throw -4)"; unknown codes as "Catch = <n>") instead of the
  "forth-throw" sentinel. ABORT" text is carried as a structured
  payload and shown only when the -2 throw goes uncaught -- CATCH
  stays silent and the payload cannot go stale. ABORT throws -1
  through the same path.
- WORDS: optional same-line substring filter (WORDS FDEPTH), skips
  internal words (new INTERNAL header flag, set at create for
  underscore-prefixed names), wraps at 78 columns, prints a count.
  ORDER names wids (FORTH / wid#N) instead of Rust debug output.
- .S honors BASE. New: F.S (float stack), DUMP (hex+ASCII,
  bounds-checked, 4K cap), ? (fetch-and-print, boot.fth). BYE is a
  real word now: sets a VM flag the driver honors (exits REPL,
  stops rest of line/file).

CLI:
- Persistent history (~/.local/state/wafer/history, 0600 perms,
  $WAFER_HISTORY override), Tab completion over the live dictionary
  (snapshot refreshed after each line), Up/Down do prefix history
  search, Ctrl-C clears the line instead of exiting.

Web:
- History survives reloads (localStorage, cap 200, dedup, init-code
  runs excluded), User Words palette populated via new words()
  export, stack bar annotates non-decimal BASE, base() reads the
  real BASE sysvar instead of returning a hardcoded 10.
2026-08-05 14:57:12 +02:00

288 lines
9.0 KiB
JavaScript

import init, { WaferRepl } from './pkg/wafer_web.js';
let repl = null;
const HISTORY_KEY = 'wafer-history';
const HISTORY_MAX = 200;
const history = JSON.parse(localStorage.getItem(HISTORY_KEY) || '[]');
let historyIdx = history.length;
let builtinWords = null;
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();
const base = repl.base();
const suffix = base !== 10 ? ` [base ${base}]` : '';
if (stack.length === 0) {
stackBar.textContent = `Stack: (empty)${suffix}`;
} else {
stackBar.textContent = `Stack <${stack.length}> ${stack.join(' ')}${suffix}`;
}
} catch {
stackBar.textContent = 'Stack: (error)';
}
}
function updateUserWords() {
const list = document.getElementById('user-word-list');
if (!list || !repl || !builtinWords) return;
list.innerHTML = '';
for (const w of repl.words()) {
if (!builtinWords.has(w)) list.appendChild(wordChip(w));
}
}
function evaluate(line, record = true) {
if (!repl) return;
const trimmed = line.trim();
if (!trimmed) return;
// Add to history (user-typed lines only; skip consecutive duplicates)
if (record && history[history.length - 1] !== trimmed) {
history.push(trimmed);
if (history.length > HISTORY_MAX) history.splice(0, history.length - HISTORY_MAX);
localStorage.setItem(HISTORY_KEY, JSON.stringify(history));
}
historyIdx = history.length;
try {
let result = repl.evaluate(trimmed);
// PAGE (form feed) clears the screen
if (result.includes('\x0C')) {
output.innerHTML = '';
result = result.replaceAll('\x0C', '');
}
// 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();
updateUserWords();
}
// 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 wordChip(w) {
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();
});
return chip;
}
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) {
list.appendChild(wordChip(w));
}
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, false);
}
}
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();
updateUserWords();
} 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();
// Everything defined at boot is "builtin"; later definitions are user words
builtinWords = new Set(repl.words());
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 !== null) {
document.getElementById('init-code').value = saved;
}
const initCode = document.getElementById('init-code').value;
if (initCode.trim()) {
for (const line of initCode.split('\n')) {
if (line.trim()) evaluate(line, false);
}
localStorage.setItem('wafer-init-code', initCode);
}
// 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, false);
}
} catch { /* ignore bad hash */ }
}
input.focus();
} catch (e) {
output.innerHTML = '';
appendLine(`Failed to initialize WAFER: ${e.message || e}`, 'line-error');
console.error(e);
}
}
boot();