aboutsummaryrefslogtreecommitdiffstats
path: root/forth
diff options
context:
space:
mode:
authorelioat <{ID}+{username}@users.noreply.github.com>2025-08-21 18:39:31 -0400
committerelioat <{ID}+{username}@users.noreply.github.com>2025-08-21 18:39:31 -0400
commitaa2916ee04161301ae23f1425caaa692e63f458d (patch)
treeec673cc0e8ce23ffa2146993420e1f21bd52cb4c /forth
parent9c3e5894d90bf069c2178d8a8ac82d157c83159b (diff)
downloadtour-aa2916ee04161301ae23f1425caaa692e63f458d.tar.gz
*
Diffstat (limited to 'forth')
-rw-r--r--forth/foreforthfourth/README.md138
-rw-r--r--forth/foreforthfourth/forth.js538
-rw-r--r--forth/foreforthfourth/index.html326
-rw-r--r--forth/foreforthfourth/test-forth.js77
-rw-r--r--forth/forthfourth.html624
5 files changed, 764 insertions, 939 deletions
diff --git a/forth/foreforthfourth/README.md b/forth/foreforthfourth/README.md
new file mode 100644
index 0000000..381053d
--- /dev/null
+++ b/forth/foreforthfourth/README.md
@@ -0,0 +1,138 @@
+# 4-Stack Toy Forth Interpreter
+
+A pure functional implementation of a toy Forth interpreter with a unique 4-stack architecture, written in JavaScript.
+
+## Architecture
+
+This Forth interpreter features **4 separate stacks** that users can juggle between, unlike traditional single-stack Forth implementations:
+
+- **Stack 1 (Red)** - Default stack for most operations
+- **Stack 2 (Teal)** - Secondary stack for data organization
+- **Stack 3 (Blue)** - Tertiary stack for complex operations
+- **Stack 4 (Yellow)** - Quaternary stack for additional data
+
+## Features
+
+### Core Forth Operations
+- **Stack Manipulation**: `dup`, `swap`, `drop`, `2dup`, `2drop`, `over`, `rot`, `-rot`
+- **Arithmetic**: `+`, `-`, `*`, `/`, `mod`
+- **Comparison**: `=`, `<`, `>`, `and`, `or`, `not`
+- **Math Utilities**: `abs`, `min`, `max`
+- **Stack Inspection**: `.s` (non-destructive), `depth`
+
+### Multi-Stack Operations
+- **Push Operations**: `push.red`, `push.teal`, `push.blue`, `push.yellow`
+- **Pop Operations**: `pop.red`, `pop.teal`, `pop.blue`, `pop.yellow`
+- **Move Operation**: `move` (interactive stack-to-stack movement)
+
+### Word Definition System
+- **Define Words**: `: name ... ;` syntax
+- **List Words**: `words` command shows all available words
+- **User Dictionary**: Persistent storage of custom words
+
+## Project Structure
+
+```
+foreforthfourth/
+├── index.html # Web interface
+├── forth.js # Core Forth interpreter (standalone)
+├── test-forth.js # Test suite for the interpreter
+└── README.md # This file
+```
+
+## Testing
+
+### Run Tests
+```bash
+node test-forth.js
+```
+
+### Test Coverage
+The test suite covers:
+- Basic number pushing and arithmetic
+- Stack manipulation operations
+- Comparison and logical operators
+- Word definition and usage
+- Multi-stack operations
+- Error handling
+
+## Web Interface
+
+Open `index.html` in a web browser to use the interactive Forth interpreter with:
+- Visual representation of all 4 stacks
+- Real-time command execution
+- Output history
+- Responsive design for mobile and desktop
+
+## Usage Examples
+
+### Basic Stack Operations
+```forth
+5 3 2 .s # Push numbers and show stack
+dup over # Duplicate top, copy second over top
+2dup # Duplicate top two items
+```
+
+### Arithmetic
+```forth
+10 3 / # Integer division (result: 3)
+10 3 mod # Modulo (result: 1)
+-5 abs # Absolute value (result: 5)
+```
+
+### Multi-Stack Juggling
+```forth
+5 3 2 # Push to red stack
+push.teal # Move top of red to teal stack
+push.blue # Move top of red to blue stack
+```
+
+### Word Definition
+```forth
+: double dup + ; # Define 'double' word
+5 double # Use the word (result: 10)
+```
+
+### Comparison and Logic
+```forth
+5 3 > # 5 > 3 (result: -1 for true)
+5 3 < # 5 < 3 (result: 0 for false)
+5 3 > not # NOT (5 > 3) (result: 0)
+```
+
+## Design Principles
+
+### Pure Functional
+- **Immutable State**: All state updates return new state objects
+- **No Side Effects**: Functions are pure and predictable
+- **Functional Composition**: Operations compose naturally
+
+### 4-Stack Architecture
+- **Stack Independence**: Each stack operates independently
+- **Flexible Data Flow**: Move data between stacks as needed
+- **Organized Workflows**: Use different stacks for different purposes
+
+### ANS Forth Compatibility
+- **Standard Words**: Implements core ANS Forth words
+- **Familiar Syntax**: Standard Forth syntax and semantics
+- **Extensible**: Easy to add new words and functionality
+
+## Future Enhancements
+
+### Planned Features
+- **Control Flow**: `IF ... THEN`, `DO ... LOOP` constructs
+- **String Operations**: String literals and manipulation
+- **File I/O**: Load and save Forth programs
+- **Debugging Tools**: Step-by-step execution, breakpoints
+
+### Potential Extensions
+- **Graphics**: Simple drawing operations
+- **Networking**: HTTP requests and responses
+- **Persistence**: Save state between sessions
+- **Modules**: Import/export word definitions
+
+## Known Issues
+
+- The `move` operation requires two separate command inputs
+- Some edge cases in error handling may need refinement
+- Performance optimization for large programs
diff --git a/forth/foreforthfourth/forth.js b/forth/foreforthfourth/forth.js
new file mode 100644
index 0000000..baf14df
--- /dev/null
+++ b/forth/foreforthfourth/forth.js
@@ -0,0 +1,538 @@
+// 4-Stack Toy Forth Interpreter
+// Pure functional implementation with immutable state
+
+// Pure functional approach to Forth interpreter state
+const createInitialState = () => ({
+ stacks: [[], [], [], []],
+ dictionary: new Map(),
+ output: [],
+ compilingWord: null,
+ compilingDefinition: []
+});
+
+// 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 };
+};
+
+// 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}`]
+ });
+};
+
+// 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 });
+ },
+
+ '2drop': (state) => {
+ if (state.stacks[0].length < 2) {
+ return updateState(state, { output: [...state.output, 'Error: Stack underflow on 2drop'] });
+ }
+ const { stacks: stacks1 } = popFromStack(state.stacks, 0);
+ const { stacks } = popFromStack(stacks1, 0);
+ return updateState(state, { stacks });
+ },
+
+ 'over': (state) => {
+ if (state.stacks[0].length < 2) {
+ return updateState(state, { output: [...state.output, 'Error: Stack underflow on over'] });
+ }
+ const second = state.stacks[0][state.stacks[0].length - 2];
+ return updateState(state, {
+ stacks: pushToStack(state.stacks, 0, second)
+ });
+ },
+
+ '2dup': (state) => {
+ if (state.stacks[0].length < 2) {
+ return updateState(state, { output: [...state.output, 'Error: Stack underflow on 2dup'] });
+ }
+ const top = state.stacks[0][state.stacks[0].length - 1];
+ const second = state.stacks[0][state.stacks[0].length - 2];
+ const newStacks = pushToStack(state.stacks, 0, second);
+ return updateState(state, {
+ stacks: pushToStack(newStacks, 0, top)
+ });
+ },
+
+ 'rot': (state) => {
+ if (state.stacks[0].length < 3) {
+ return updateState(state, { output: [...state.output, 'Error: Stack underflow on rot'] });
+ }
+ const newStacks = state.stacks.map((stack, i) => [...stack]);
+ const a = newStacks[0].pop();
+ const b = newStacks[0].pop();
+ const c = newStacks[0].pop();
+ newStacks[0].push(b);
+ newStacks[0].push(a);
+ newStacks[0].push(c);
+ return updateState(state, { stacks: newStacks });
+ },
+
+ '-rot': (state) => {
+ if (state.stacks[0].length < 3) {
+ return updateState(state, { output: [...state.output, 'Error: Stack underflow on -rot'] });
+ }
+ const newStacks = state.stacks.map((stack, i) => [...stack]);
+ const a = newStacks[0].pop();
+ const b = newStacks[0].pop();
+ const c = newStacks[0].pop();
+ newStacks[0].push(a);
+ newStacks[0].push(c);
+ newStacks[0].push(b);
+ return updateState(state, { stacks: newStacks });
+ },
+
+ // 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))
+ });
+ },
+
+ // Comparison operators
+ '=': (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 ? -1 : 0)
+ });
+ },
+
+ '<': (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 ? -1 : 0)
+ });
+ },
+
+ '>': (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 ? -1 : 0)
+ });
+ },
+
+ // Logical operators
+ 'and': (state) => {
+ if (state.stacks[0].length < 2) {
+ return updateState(state, { output: [...state.output, 'Error: Stack underflow on and'] });
+ }
+ 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 ? -1 : 0)
+ });
+ },
+
+ 'or': (state) => {
+ if (state.stacks[0].length < 2) {
+ return updateState(state, { output: [...state.output, 'Error: Stack underflow on or'] });
+ };
+ 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 ? -1 : 0)
+ });
+ },
+
+ 'not': (state) => {
+ if (state.stacks[0].length === 0) {
+ return updateState(state, { output: [...state.output, 'Error: Stack underflow on not'] });
+ }
+ const { stacks, value } = popFromStack(state.stacks, 0);
+ return updateState(state, {
+ stacks: pushToStack(stacks, 0, value ? 0 : -1)
+ });
+ },
+
+ // Additional math operations
+ 'mod': (state) => {
+ if (state.stacks[0].length < 2) {
+ return updateState(state, { output: [...state.output, 'Error: Stack underflow on mod'] });
+ }
+ 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, a % b)
+ });
+ },
+
+ 'abs': (state) => {
+ if (state.stacks[0].length === 0) {
+ return updateState(state, { output: [...state.output, 'Error: Stack underflow on abs'] });
+ }
+ const { stacks, value } = popFromStack(state.stacks, 0);
+ return updateState(state, {
+ stacks: pushToStack(stacks, 0, Math.abs(value))
+ });
+ },
+
+ 'min': (state) => {
+ if (state.stacks[0].length < 2) {
+ return updateState(state, { output: [...state.output, 'Error: Stack underflow on min'] });
+ }
+ const { stacks: stacks1, value: b } = popFromStack(state.stacks, 0);
+ const { stacks: stacks2, value: a } = popFromStack(stacks1, 0);
+ return updateState(state, {
+ stacks: pushToStack(stacks2, 0, Math.min(a, b))
+ });
+ },
+
+ 'max': (state) => {
+ if (state.stacks[0].length < 2) {
+ return updateState(state, { output: [...state.output, 'Error: Stack underflow on max'] });
+ }
+ const { stacks: stacks1, value: b } = popFromStack(state.stacks, 0);
+ const { stacks: stacks2, value: a } = popFromStack(stacks1, 0);
+ return updateState(state, {
+ stacks: pushToStack(stacks2, 0, Math.max(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()]
+ });
+ },
+
+ // Stack inspection (non-destructive)
+ '.s': (state) => {
+ const stackContents = state.stacks[0].map(item => item.toString()).join(' ');
+ return updateState(state, {
+ output: [...state.output, `<${state.stacks[0].length}> ${stackContents}`]
+ });
+ },
+
+ 'depth': (state) => {
+ return updateState(state, {
+ stacks: pushToStack(state.stacks, 0, state.stacks[0].length)
+ });
+ },
+
+ // 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 (!state.moveInProgress) {
+ return updateState(state, {
+ moveInProgress: true,
+ 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 builtinWordNames = Object.keys(builtinWords);
+ const userWords = Array.from(state.dictionary.keys());
+ const allWords = [...builtinWordNames, ...userWords];
+
+ const builtinList = builtinWordNames.join(' ');
+ const userList = userWords.length > 0 ? userWords.join(' ') : 'none';
+
+ return updateState(state, {
+ output: [
+ ...state.output,
+ 'Built-in words: ' + builtinList,
+ 'User defined words: ' + userList,
+ 'Total words: ' + allWords.length
+ ]
+ });
+ },
+
+ 'clear': (state) => updateState(state, {
+ stacks: [[], [], [], []],
+ output: [...state.output, 'All stacks cleared']
+ })
+};
+
+// 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 (state.moveInProgress) {
+ if (state.moveFromStack === null) {
+ // Expecting source stack number
+ const from = parseInt(token);
+ if (isNaN(from) || from < 1 || from > 4) {
+ return updateState(state, {
+ moveInProgress: false,
+ moveFromStack: null,
+ output: [...state.output, 'Error: Invalid source stack. Must be 1-4']
+ });
+ }
+ if (state.stacks[from - 1].length === 0) {
+ return updateState(state, {
+ moveInProgress: false,
+ moveFromStack: null,
+ output: [...state.output, `Error: Stack ${from} is empty`]
+ });
+ }
+ return updateState(state, {
+ moveInProgress: true,
+ moveFromStack: from - 1, // Convert to 0-based index
+ 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) {
+ return updateState(state, {
+ moveInProgress: false,
+ moveFromStack: null,
+ output: [...state.output, 'Error: Invalid destination stack. Must be 1-4']
+ });
+ }
+ const toIndex = to - 1; // Convert to 0-based index
+ const fromIndex = state.moveFromStack;
+
+ // Reset move state
+ const newState = updateState(state, {
+ moveInProgress: false,
+ moveFromStack: null
+ });
+
+ // Perform the move
+ const { stacks, value } = popFromStack(newState.stacks, fromIndex);
+ return updateState(newState, {
+ stacks: pushToStack(stacks, toIndex, value),
+ output: [...newState.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`]
+ });
+ }
+
+ // If we're expecting a name, capture it
+ if (state.compilingWord === 'EXPECTING_NAME') {
+ return updateState(state, {
+ compilingWord: token,
+ compilingDefinition: []
+ });
+ }
+
+ // Otherwise, add to definition
+ return updateState(state, {
+ compilingDefinition: [...state.compilingDefinition, token]
+ });
+ }
+
+ // Start word definition
+ if (token === ':') {
+ return updateState(state, {
+ compilingWord: 'EXPECTING_NAME',
+ compilingDefinition: []
+ });
+ }
+
+ // 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}'`]
+ });
+};
+
+// Export for use in other modules or testing
+if (typeof module !== 'undefined' && module.exports) {
+ module.exports = {
+ createInitialState,
+ parseAndExecute,
+ executeToken,
+ builtinWords,
+ updateState,
+ pushToStack,
+ popFromStack
+ };
+} else if (typeof window !== 'undefined') {
+ // Browser environment
+ window.ForthInterpreter = {
+ createInitialState,
+ parseAndExecute,
+ executeToken,
+ builtinWords,
+ updateState,
+ pushToStack,
+ popFromStack
+ };
+}
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();
};
diff --git a/forth/foreforthfourth/test-forth.js b/forth/foreforthfourth/test-forth.js
new file mode 100644
index 0000000..54f9963
--- /dev/null
+++ b/forth/foreforthfourth/test-forth.js
@@ -0,0 +1,77 @@
+// Simple test file for the Forth interpreter
+// Run with: node test-forth.js
+
+const ForthInterpreter = require('./forth.js');
+
+console.log('🧪 Testing 4-Stack Toy Forth Interpreter\n');
+
+// Test 1: Basic number pushing
+console.log('Test 1: Basic number pushing');
+let state = ForthInterpreter.createInitialState();
+state = ForthInterpreter.parseAndExecute(state, '5 3 2');
+console.log('Stack 1 after "5 3 2":', state.stacks[0]);
+console.log('Expected: [5, 3, 2]\n');
+
+// Test 2: Basic arithmetic
+console.log('Test 2: Basic arithmetic');
+state = ForthInterpreter.parseAndExecute(state, '+');
+console.log('Stack 1 after "+":', state.stacks[0]);
+console.log('Expected: [5, 5] (3+2=5)\n');
+
+// Test 3: Stack manipulation
+console.log('Test 3: Stack manipulation');
+state = ForthInterpreter.parseAndExecute(state, 'dup over');
+console.log('Stack 1 after "dup over":', state.stacks[0]);
+console.log('Expected: [5, 5, 5, 5] (dup then over)\n');
+
+// Test 4: Stack inspection
+console.log('Test 4: Stack inspection');
+state = ForthInterpreter.parseAndExecute(state, '.s');
+console.log('Output:', state.output[state.output.length - 1]);
+console.log('Expected: <4> 5 5 5 5\n');
+
+// Test 5: Comparison operators
+console.log('Test 5: Comparison operators');
+state = ForthInterpreter.parseAndExecute(state, '5 3 >');
+console.log('Stack 1 after "5 3 >":', state.stacks[0]);
+console.log('Expected: [5, 5, 5, 5, -1] (5 > 3 = true = -1)\n');
+
+// Test 6: Word definition
+console.log('Test 6: Word definition');
+state = ForthInterpreter.parseAndExecute(state, ': double dup + ;');
+console.log('Output:', state.output[state.output.length - 1]);
+console.log('Expected: Word \'double\' defined\n');
+
+// Test 7: Using defined word
+console.log('Test 7: Using defined word');
+state = ForthInterpreter.parseAndExecute(state, 'double');
+console.log('Stack 1 after "double":', state.stacks[0]);
+console.log('Expected: [5, 5, 5, 5, -1, 10] (double of 5 = 10)\n');
+
+// Test 8: List all words
+console.log('Test 8: List all words');
+state = ForthInterpreter.parseAndExecute(state, 'words');
+console.log('Output:', state.output.slice(-3));
+console.log('Expected: Built-in words, User defined words, Total words count\n');
+
+// Test 9: Stack juggling
+console.log('Test 9: Stack juggling');
+state = ForthInterpreter.parseAndExecute(state, 'push.teal');
+console.log('Stack 1 after "push.teal":', state.stacks[0]);
+console.log('Stack 2 after "push.teal":', state.stacks[1]);
+console.log('Expected: Stack 1: [5, 5, 5, 5, -1], Stack 2: [10]\n');
+
+// Test 10: Error handling
+console.log('Test 10: Error handling');
+state = ForthInterpreter.parseAndExecute(state, 'drop drop drop drop drop drop drop drop drop drop drop');
+console.log('Output:', state.output[state.output.length - 1]);
+console.log('Expected: Error: Stack underflow on drop\n');
+
+console.log('✅ All tests completed!');
+console.log('\nFinal state:');
+console.log('Stack 1:', state.stacks[0]);
+console.log('Stack 2:', state.stacks[1]);
+console.log('Stack 3:', state.stacks[2]);
+console.log('Stack 4:', state.stacks[3]);
+console.log('Dictionary size:', state.dictionary.size);
+console.log('Output messages:', state.output.length);
diff --git a/forth/forthfourth.html b/forth/forthfourth.html
deleted file mode 100644
index 9fd1228..0000000
--- a/forth/forthfourth.html
+++ /dev/null
@@ -1,624 +0,0 @@
-<!DOCTYPE html>
-<html lang="en">
-<head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>4-Stack Toy Forth</title>
- <style>
- body {
- font-family: 'Courier New', monospace;
- margin: 0;
- padding: 10px;
- background-color: #000;
- color: #fff;
- min-height: 100vh;
- display: flex;
- flex-direction: column;
- }
-
- .container {
- max-width: 100%;
- flex: 1;
- display: flex;
- flex-direction: column;
- }
-
- h1 {
- font-size: 18px;
- margin: 0 0 10px 0;
- text-align: center;
- }
-
- .help {
- background-color: #111;
- border: 1px solid #333;
- padding: 10px;
- margin-bottom: 10px;
- font-size: 12px;
- line-height: 1.3;
- }
-
- .help h4 {
- margin: 0 0 5px 0;
- font-size: 13px;
- }
-
- .stacks-container {
- display: grid;
- grid-template-columns: repeat(4, 1fr);
- gap: 8px;
- margin-bottom: 10px;
- flex: 1;
- min-height: 200px;
- }
-
- .stack {
- border: 2px solid;
- padding: 8px;
- display: flex;
- flex-direction: column;
- background-color: #111;
- position: relative;
- }
-
- .stack-1 { border-color: #ff6b6b; }
- .stack-2 { border-color: #4ecdc4; }
- .stack-3 { border-color: #45b7d1; }
- .stack-4 { border-color: #f9ca24; }
-
- .stack h3 {
- margin: 0 0 8px 0;
- text-align: center;
- font-size: 12px;
- color: #fff;
- }
-
- .stack-items {
- flex: 1;
- display: flex;
- flex-direction: column-reverse;
- gap: 2px;
- align-items: stretch;
- }
-
- .stack-item {
- background-color: #222;
- padding: 4px 6px;
- text-align: center;
- border: 1px solid #555;
- font-size: 12px;
- word-break: break-all;
- }
-
- .input-section {
- margin-bottom: 10px;
- }
-
- .input-container {
- display: flex;
- gap: 5px;
- margin-bottom: 8px;
- }
-
- #forth-input {
- flex: 1;
- padding: 8px;
- font-family: 'Courier New', monospace;
- font-size: 14px;
- border: 1px solid #555;
- background-color: #111;
- color: #fff;
- }
-
- #forth-input:focus {
- outline: none;
- border-color: #fff;
- }
-
- button {
- padding: 8px 12px;
- font-family: 'Courier New', monospace;
- font-size: 12px;
- border: 1px solid #fff;
- background-color: #000;
- color: #fff;
- cursor: pointer;
- }
-
- button:hover, button:active {
- background-color: #fff;
- color: #000;
- }
-
- .output {
- background-color: #111;
- border: 1px solid #555;
- padding: 8px;
- height: 100px;
- overflow-y: auto;
- font-family: 'Courier New', monospace;
- font-size: 12px;
- line-height: 1.3;
- }
-
- .error {
- color: #fff;
- }
-
- .success {
- color: #fff;
- }
-
- /* Mobile optimizations */
- @media (max-width: 768px) {
- body { padding: 5px; }
-
- h1 { font-size: 16px; }
-
- .help {
- font-size: 11px;
- padding: 8px;
- }
-
- .stacks-container {
- gap: 4px;
- min-height: 150px;
- }
-
- .stack {
- padding: 6px;
- }
-
- .stack h3 {
- font-size: 11px;
- margin-bottom: 6px;
- }
-
- .stack-item {
- font-size: 11px;
- padding: 3px 4px;
- }
-
- #forth-input {
- font-size: 16px; /* Prevents zoom on iOS */
- padding: 6px;
- }
-
- button {
- font-size: 11px;
- padding: 6px 10px;
- }
-
- .output {
- height: 80px;
- font-size: 11px;
- padding: 6px;
- }
- }
-
- @media (max-width: 480px) {
- .stacks-container {
- grid-template-columns: repeat(2, 1fr);
- grid-template-rows: repeat(2, 1fr);
- }
-
- .input-container {
- flex-direction: column;
- }
-
- button {
- width: 100%;
- }
- }
- </style>
-</head>
-<body>
- <div class="container">
- <h1>4-Stack Toy Forth Interpreter</h1>
-
- <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) |
- 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)
- </div>
-
- <div class="stacks-container">
- <div class="stack stack-1">
- <h3>Stack 1 (Red)</h3>
- <div class="stack-items" id="stack-1-items"></div>
- </div>
- <div class="stack stack-2">
- <h3>Stack 2 (Teal)</h3>
- <div class="stack-items" id="stack-2-items"></div>
- </div>
- <div class="stack stack-3">
- <h3>Stack 3 (Blue)</h3>
- <div class="stack-items" id="stack-3-items"></div>
- </div>
- <div class="stack stack-4">
- <h3>Stack 4 (Yellow)</h3>
- <div class="stack-items" id="stack-4-items"></div>
- </div>
- </div>
-
- <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>
- </div>
- </div>
-
- <div class="output" id="output"></div>
- </div>
-
- <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 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 = () => {
- // Update stacks
- forthState.stacks.forEach((stack, index) => {
- const container = document.getElementById(`stack-${index + 1}-items`);
- container.innerHTML = '';
- stack.forEach(item => {
- const div = document.createElement('div');
- div.className = 'stack-item';
- div.textContent = item.toString();
- container.appendChild(div);
- });
- });
-
- // Update output
- const outputElement = document.getElementById('output');
- outputElement.innerHTML = forthState.output
- .slice(-20) // Show last 20 messages
- .map(msg => {
- const className = msg.startsWith('Error:') ? 'error' : 'success';
- return `<div class="${className}">${msg}</div>`;
- })
- .join('');
- outputElement.scrollTop = outputElement.scrollHeight;
- };
-
- // Execute Forth commands
- const executeForth = () => {
- const input = document.getElementById('forth-input');
- const command = input.value.trim();
-
- if (command) {
- forthState = parseAndExecute(forthState, command);
- updateDisplay();
- input.value = '';
- }
- };
-
- // Clear all stacks
- const clearAll = () => {
- forthState = createInitialState();
- moveInProgress = false;
- moveFromStack = null;
- updateDisplay();
- };
-
- // Handle Enter key in input
- document.getElementById('forth-input').addEventListener('keypress', (e) => {
- if (e.key === 'Enter') {
- executeForth();
- }
- });
-
- // Initialize display
- updateDisplay();
- </script>
-</body>
-</html> \ No newline at end of file