aboutsummaryrefslogtreecommitdiffstats
path: root/forth/foreforthfourth/index.html
diff options
context:
space:
mode:
Diffstat (limited to 'forth/foreforthfourth/index.html')
-rw-r--r--forth/foreforthfourth/index.html326
1 files changed, 11 insertions, 315 deletions
diff --git a/forth/foreforthfourth/index.html b/forth/foreforthfourth/index.html
index 9fd1228..e175c96 100644
--- a/forth/foreforthfourth/index.html
+++ b/forth/foreforthfourth/index.html
@@ -3,7 +3,7 @@
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>4-Stack Toy Forth</title>
+ <title>4-Stack Forth</title>
<style>
body {
font-family: 'Courier New', monospace;
@@ -219,10 +219,11 @@
<div class="help">
<h4>Built-in Words:</h4>
Numbers (push to stack 1/red) | push.red push.teal push.blue push.yellow (move top of red to target) |
- pop.red pop.teal pop.blue pop.yellow (pop and print) | + - * / (red stack arithmetic) |
- dup swap drop (red stack manipulation) | . (print top of red stack) |
+ pop.red pop.teal pop.blue pop.yellow (pop and print) | + - * / mod (red stack arithmetic) |
+ dup swap drop 2dup 2drop over rot -rot (red stack manipulation) | . .s depth (stack inspection) |
+ = < > and or not (comparison & logic) | abs min max (math utilities) |
move (usage: move 2 3 - moves top from stack 2 to stack 3) |
- : name ... ; (define new word) | words (list defined words) | clear (clear all stacks)
+ : name ... ; (define new word) | words (list all available words) | clear (clear all stacks)
</div>
<div class="stacks-container">
@@ -247,322 +248,19 @@
<div class="input-section">
<div class="input-container">
<input type="text" id="forth-input" placeholder="Enter Forth commands here..." />
- <button onclick="executeForth()">Execute</button>
- <button onclick="clearAll()">Clear All</button>
+ <button onclick="executeForth()">Run</button>
+ <button onclick="clearAll()">Clear</button>
</div>
</div>
<div class="output" id="output"></div>
</div>
+ <script src="forth.js"></script>
<script>
- // Pure functional approach to Forth interpreter state
- const createInitialState = () => ({
- stacks: [[], [], [], []],
- dictionary: new Map(),
- output: [],
- compilingWord: null,
- compilingDefinition: []
- });
-
- let forthState = createInitialState();
-
- // Pure function to update state
- const updateState = (state, updates) => ({
- ...state,
- ...updates
- });
-
- // Pure function to push to a specific stack
- const pushToStack = (stacks, stackIndex, value) => {
- const newStacks = stacks.map((stack, i) => [...stack]);
- newStacks[stackIndex].push(value);
- return newStacks;
- };
-
- // Pure function to pop from a specific stack
- const popFromStack = (stacks, stackIndex) => {
- const newStacks = stacks.map((stack, i) => [...stack]);
- const value = newStacks[stackIndex].pop();
- return { stacks: newStacks, value };
- };
+ let forthState = ForthInterpreter.createInitialState();
- let moveInProgress = false;
- let moveFromStack = null;
-
- // Built-in word implementations
- const builtinWords = {
- // Stack manipulation for stack 1 (default)
- 'dup': (state) => {
- if (state.stacks[0].length === 0) {
- return updateState(state, { output: [...state.output, 'Error: Stack underflow on dup'] });
- }
- const top = state.stacks[0][state.stacks[0].length - 1];
- return updateState(state, {
- stacks: pushToStack(state.stacks, 0, top)
- });
- },
-
- 'swap': (state) => {
- if (state.stacks[0].length < 2) {
- return updateState(state, { output: [...state.output, 'Error: Stack underflow on swap'] });
- }
- const newStacks = state.stacks.map((stack, i) => [...stack]);
- const a = newStacks[0].pop();
- const b = newStacks[0].pop();
- newStacks[0].push(a);
- newStacks[0].push(b);
- return updateState(state, { stacks: newStacks });
- },
-
- 'drop': (state) => {
- if (state.stacks[0].length === 0) {
- return updateState(state, { output: [...state.output, 'Error: Stack underflow on drop'] });
- }
- const { stacks } = popFromStack(state.stacks, 0);
- return updateState(state, { stacks });
- },
-
- // Arithmetic operations on stack 1
- '+': (state) => {
- if (state.stacks[0].length < 2) {
- return updateState(state, { output: [...state.output, 'Error: Stack underflow on +'] });
- }
- const { stacks: stacks1, value: b } = popFromStack(state.stacks, 0);
- const { stacks: stacks2, value: a } = popFromStack(stacks1, 0);
- return updateState(state, {
- stacks: pushToStack(stacks2, 0, a + b)
- });
- },
-
- '-': (state) => {
- if (state.stacks[0].length < 2) {
- return updateState(state, { output: [...state.output, 'Error: Stack underflow on -'] });
- }
- const { stacks: stacks1, value: b } = popFromStack(state.stacks, 0);
- const { stacks: stacks2, value: a } = popFromStack(stacks1, 0);
- return updateState(state, {
- stacks: pushToStack(stacks2, 0, a - b)
- });
- },
- '*': (state) => {
- if (state.stacks[0].length < 2) {
- return updateState(state, { output: [...state.output, 'Error: Stack underflow on *'] });
- }
- const { stacks: stacks1, value: b } = popFromStack(state.stacks, 0);
- const { stacks: stacks2, value: a } = popFromStack(stacks1, 0);
- return updateState(state, {
- stacks: pushToStack(stacks2, 0, a * b)
- });
- },
-
- '/': (state) => {
- if (state.stacks[0].length < 2) {
- return updateState(state, { output: [...state.output, 'Error: Stack underflow on /'] });
- }
- const { stacks: stacks1, value: b } = popFromStack(state.stacks, 0);
- const { stacks: stacks2, value: a } = popFromStack(stacks1, 0);
- if (b === 0) {
- return updateState(state, {
- stacks: pushToStack(pushToStack(stacks2, 0, a), 0, b),
- output: [...state.output, 'Error: Division by zero']
- });
- }
- return updateState(state, {
- stacks: pushToStack(stacks2, 0, Math.floor(a / b))
- });
- },
-
- // Print top of stack 1
- '.': (state) => {
- if (state.stacks[0].length === 0) {
- return updateState(state, { output: [...state.output, 'Error: Stack underflow on .'] });
- }
- const { stacks, value } = popFromStack(state.stacks, 0);
- return updateState(state, {
- stacks,
- output: [...state.output, value.toString()]
- });
- },
-
- // Push operations
- 'push.red': (state) => state,
- 'push.teal': (state) => moveBetweenStacks(state, 0, 1),
- 'push.blue': (state) => moveBetweenStacks(state, 0, 2),
- 'push.yellow': (state) => moveBetweenStacks(state, 0, 3),
-
- // Pop operations
- 'pop.red': (state) => popAndPrint(state, 0),
- 'pop.teal': (state) => popAndPrint(state, 1),
- 'pop.blue': (state) => popAndPrint(state, 2),
- 'pop.yellow': (state) => popAndPrint(state, 3),
-
- // Move operation
- 'move': (state) => {
- if (!moveInProgress) {
- moveInProgress = true;
- return updateState(state, {
- output: [...state.output, 'Move: Enter source stack number (1-4)']
- });
- } else {
- return state; // This shouldn't happen in normal flow
- }
- },
-
- // Utility words
- 'words': (state) => {
- const userWords = Array.from(state.dictionary.keys()).join(' ');
- return updateState(state, {
- output: [...state.output, 'User defined words: ' + (userWords || 'none')]
- });
- },
-
- 'clear': (state) => updateState(state, {
- stacks: [[], [], [], []],
- output: [...state.output, 'All stacks cleared']
- })
- };
-
- // Helper function to move value from one stack to another
- const moveBetweenStacks = (state, fromIndex, toIndex) => {
- if (state.stacks[fromIndex].length === 0) {
- return updateState(state, {
- output: [...state.output, `Error: Stack ${fromIndex + 1} underflow`]
- });
- }
- const { stacks, value } = popFromStack(state.stacks, fromIndex);
- return updateState(state, {
- stacks: pushToStack(stacks, toIndex, value)
- });
- };
-
- // Helper function to pop and print from specific stack
- const popAndPrint = (state, stackIndex) => {
- const stackNames = ['red', 'teal', 'blue', 'yellow'];
- if (state.stacks[stackIndex].length === 0) {
- return updateState(state, {
- output: [...state.output, `Error: ${stackNames[stackIndex]} stack underflow`]
- });
- }
- const { stacks, value } = popFromStack(state.stacks, stackIndex);
- return updateState(state, {
- stacks,
- output: [...state.output, `${stackNames[stackIndex]}: ${value}`]
- });
- };
-
- // Parse and execute Forth input
- const parseAndExecute = (state, input) => {
- const tokens = input.trim().split(/\s+/).filter(token => token.length > 0);
- return tokens.reduce(executeToken, state);
- };
-
- // Execute a single token
- const executeToken = (state, token) => {
- // Handle move operation state machine
- if (moveInProgress) {
- if (moveFromStack === null) {
- // Expecting source stack number
- const from = parseInt(token);
- if (isNaN(from) || from < 1 || from > 4) {
- moveInProgress = false;
- return updateState(state, {
- output: [...state.output, 'Error: Invalid source stack. Must be 1-4']
- });
- }
- if (state.stacks[from - 1].length === 0) {
- moveInProgress = false;
- return updateState(state, {
- output: [...state.output, `Error: Stack ${from} is empty`]
- });
- }
- moveFromStack = from - 1; // Convert to 0-based index
- return updateState(state, {
- output: [...state.output, `Moving from stack ${from}. Enter destination stack (1-4):`]
- });
- } else {
- // Expecting destination stack number
- const to = parseInt(token);
- if (isNaN(to) || to < 1 || to > 4) {
- moveInProgress = false;
- moveFromStack = null;
- return updateState(state, {
- output: [...state.output, 'Error: Invalid destination stack. Must be 1-4']
- });
- }
- const toIndex = to - 1; // Convert to 0-based index
- const fromIndex = moveFromStack;
-
- // Reset move state
- moveInProgress = false;
- moveFromStack = null;
-
- // Perform the move
- const { stacks, value } = popFromStack(state.stacks, fromIndex);
- return updateState(state, {
- stacks: pushToStack(stacks, toIndex, value),
- output: [...state.output, `Moved ${value} from stack ${fromIndex + 1} to stack ${toIndex + 1}`]
- });
- }
- }
-
- // Handle word definition compilation
- if (state.compilingWord !== null) {
- if (token === ';') {
- const newDictionary = new Map(state.dictionary);
- newDictionary.set(state.compilingWord, [...state.compilingDefinition]);
- return updateState(state, {
- dictionary: newDictionary,
- compilingWord: null,
- compilingDefinition: [],
- output: [...state.output, `Word '${state.compilingWord}' defined`]
- });
- }
- return updateState(state, {
- compilingDefinition: [...state.compilingDefinition, token]
- });
- }
-
- // Start word definition
- if (token === ':') {
- return updateState(state, {
- compilingWord: 'EXPECTING_NAME',
- compilingDefinition: []
- });
- }
-
- // Capture word name during definition
- if (state.compilingWord === 'EXPECTING_NAME') {
- return updateState(state, {
- compilingWord: token
- });
- }
-
- // Check if it's a number
- if (!isNaN(token)) {
- const number = parseFloat(token);
- return updateState(state, {
- stacks: pushToStack(state.stacks, 0, number)
- });
- }
-
- // Check built-in words
- if (builtinWords[token]) {
- return builtinWords[token](state);
- }
-
- // Check user-defined words
- if (state.dictionary.has(token)) {
- const definition = state.dictionary.get(token);
- return definition.reduce(executeToken, state);
- }
-
- // Unknown word
- return updateState(state, {
- output: [...state.output, `Error: Unknown word '${token}'`]
- });
- };
// Update visual display
const updateDisplay = () => {
@@ -596,7 +294,7 @@
const command = input.value.trim();
if (command) {
- forthState = parseAndExecute(forthState, command);
+ forthState = ForthInterpreter.parseAndExecute(forthState, command);
updateDisplay();
input.value = '';
}
@@ -604,9 +302,7 @@
// Clear all stacks
const clearAll = () => {
- forthState = createInitialState();
- moveInProgress = false;
- moveFromStack = null;
+ forthState = ForthInterpreter.createInitialState();
updateDisplay();
};