aboutsummaryrefslogtreecommitdiffstats
path: root/forth/foreforthfourth/index.html
blob: 9fd1228f0c38db9a6b7568007bccf9fb4c0e92b1 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
<!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>