Repository navigation
Expand file tree
/
Copy pathforth.js
More file actions
1237 lines (1057 loc) · 30.6 KB
/
Copy pathforth.js
File metadata and controls
1237 lines (1057 loc) · 30.6 KB
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
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2024-2026 Jeff Bush
//
// Licensed under the Apache License, Version 2.0 (the 'License');
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an 'AS IS' BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Core FORTH interpreter
// This was inspired by the excellent jonesforth tutorial by Richard
// W.M. Jones: <http://git.annexia.org/?p=jonesforth.git;a=tree>
// That implementation used a direct threaded interpreter written in x86
// assembly, which is not applicable in Javascript. Instead I rely on
// dynamic typing, with instruction array slots containing either a closure
// for native words, or an array offset for user defined words.
//
// Number of bytes in the default machine integer data type (in many other
// languages, we would call this the machine 'word', but that term has a
// specific meaning in FORTH, so we use 'cell' instead).
const CELL_SIZE = 4;
// Size of memory in cells
const MEMORY_CELLS = 16384;
// Byte address of three built-in variables.
const HERE_PTR = 0;
const BASE_PTR = 4;
const STATE_PTR = 8;
// A large chunk of the FORTH interpreter is implemented in FORTH, which
// is one of the cool things about FORTH. The interpreter executes this
// when it starts to define common words and bootstrap itself. You can
// see as this progresses, it uses more and more of the words that it is
// defining.
const BASE_WORDS = `
${HERE_PTR} constant here
${BASE_PTR} constant base
${STATE_PTR} constant state
-1 constant true
0 constant false
: begin immediate
here @
;
: until immediate
' 0branch ,
, \\ branch address, from stack, beginning of loop
;
\\ paren comment
: ( immediate
begin \\ consume until end of comment
key dup
char ) =
swap -1 = \\ end of input
or
until
;
: while immediate
' 0branch , \\ create a conditional branch to break out if 0
here @ \\ Save new branch address
0 , \\ dummy offset
;
: repeat immediate
' branch , \\ branch at end of previous block
swap
, \\ push address of top of loop
\\ now patch the previous break out
here @ swap !
;
( limit index -- )
: do immediate
' >r , ' >r ,
here @ \\ Branch point
;
: loop immediate
' r> , ' r> , ( limit index )
' lit , 1 , ' + , \\ Increment index
' dup , ' >r , \\ put back on return stack
' over , ' >r ,
' = , \\ Is index greater than limit?
' 0branch , \\ No, continue
, \\ branch address is top of loop
' r> , ' drop ,
' r> , ' drop ,
;
: i immediate
' r> , ' r> , ( limit index )
' dup , ' >r ,
' swap , ' >r ,
;
: j immediate
' r> , ' r> , ' r> , ' r> , ( limit index limit index* )
' dup , ' >r ,
' swap , ' >r ,
' swap , ' >r ,
' swap , ' >r ,
;
: if immediate
' 0branch ,
here @ \\ save on stack
0 , \\ dummy offset
;
: then immediate
here @ swap ! \\ patch branch
;
: else immediate
' branch , \\ branch at end of previous block
here @ \\ Save new branch address
0 , \\ dummy offset
\\ Now patch previous branch
swap
here @ swap !
;
: case immediate
0 \\ stack delimiter
;
: of immediate
' over ,
' = ,
' 0branch ,
here @ \\ Save address to patch
0 , \\ dummy branch offset
' drop ,
;
: endof immediate
' branch , \\ branch at end of previous block
here @ \\ Save new branch address
0 , \\ dummy branch offset
\\ Now patch previous branch
swap
here @ swap !
;
: endcase immediate
' drop ,
begin
dup
while
here @ swap ! \\ patch branch
repeat
drop
;
: 0= 0 = ;
: > swap < ;
: >= < 0= ;
: <= swap < 0= ;
: <> = 0= ;
: 2dup over over ;
: allot ( n -- start_address )
here @ swap ( start_address count )
over + ( start_address end_address )
here ! ( start_address )
;
: cells ${CELL_SIZE} * ;
: variable immediate
create 0 ,
;
( offset -- value )
: pick
${CELL_SIZE} * dsp@ + @
;
( src dest count -- )
: move
0 do
over @ over !
${CELL_SIZE} + swap ${CELL_SIZE} + swap
loop
drop drop
;
( address count -- )
: erase
begin
dup 0 >
while
over 0 swap ! \\ write 0
1 - \\ decrement counter
swap ${CELL_SIZE} + swap \\ increment data pointer
repeat
drop drop
;
variable __rand_seed
_get_time __rand_seed !
: random
__rand_seed @ 1103515245 * 12345 +
2147483647 and
dup __rand_seed !
;
: negate 0 swap - ;
\\ Add n to the contents of addr and write back to addr.
( n addr -- )
: +!
swap over @
+ swap !
;
: dup2 over over ;
( a b c -- a c )
: nip swap drop ;
( a b c d -- a b d c d )
: tuck swap over ;
\\ Any literal numeric is interpreted in the current base, which means
\\ the hex and decimal words would not necessarily be idempotent
\\ if we didn't define these as constants up-front.
16 constant _BASE16
10 constant _BASE10
2 constant _BASE2
: hex immediate _BASE16 base ! ;
: decimal immediate _BASE10 base ! ;
: binary immediate _BASE2 base ! ;
`;
class ForthError extends Error {
constructor(message, stackCrawl=null) {
super(message);
this.name = this.constructor.name;
}
}
class ForthCompileError extends ForthError {
constructor(message, fileName, lineNum) {
super(fileName + ':' + lineNum + ': ' + message);
this.name = this.constructor.name;
this.fileName = fileName;
this.lineNum = lineNum;
}
}
class ForthRuntimeError extends ForthError {
constructor(message, stackCrawl=null) {
super(message);
this.name = this.constructor.name;
this.stackCrawl = stackCrawl;
}
toString() {
let result = this.message;
if (this.stackCrawl) {
result += '\n(Most recent call first)\n';
for (const frame of this.stackCrawl) {
result += `${frame[0]} (${frame[2]}:${frame[3]}) @${frame[1]}\n`;
}
}
return result;
}
}
// An entry in the dictionary; a callable function.
class Word {
constructor(value, immediate=false, literal=false) {
this.immediate = immediate;
this.literal = literal;
this.value = value;
}
}
const STATE_INTERP = 0;
const STATE_COMPILE = 1;
const ZERO_ASCII = '0'.charCodeAt(0);
const LOWER_A_ASCII = 'a'.charCodeAt(0);
const A_ASCII = 'A'.charCodeAt(0);
/**
* Stores information used to generate human readable traces, including mapping
* addresses to words and source line numbers.
* @note Does not always produce accurate results.
*/
class DebugInfo {
constructor() {
this.lineMappings = {};
this.wordMappings = [];
this.fileNames = [];
}
startFile(fileName) {
this.fileNames.push(fileName);
}
startWord(name, address) {
this.wordMappings.push([name, address, address]);
}
endWord(address) {
this.wordMappings[this.wordMappings.length - 1][2] = address;
}
addLineMapping(address, line) {
this.lineMappings[address] = [this.fileNames.length - 1, line];
}
lookupWord(address) {
for (const [name, start, end] of this.wordMappings) {
if (address >= start && address < end) {
return name;
}
}
return null;
}
lookupLine(address) {
return this.lineMappings[address];
}
}
export class ForthContext {
constructor() {
this.returnStack = [];
// The intepreter stores memory as an array of cells, which can contain
// either a 32-bit integer or a reference to a native javascript
// function. The data stack is also contained within here.
this.memory = Array(Math.floor(MEMORY_CELLS / CELL_SIZE)).fill(0);
this.stackPointer = MEMORY_CELLS - CELL_SIZE; // This is a byte address.
// 'here' is a built-in variable that tracks where the next compiled code
// will be emitted. The first 3 cells in memory contain built-in vars:
// here, state, base. Increment this by three to account for that.
this.here = CELL_SIZE * 3;
this.base = 10;
this.state = STATE_INTERP;
// Initialize the primitive built-in words that form the foundation for our
// interpreter.
this.dictionary = {
// Control flow/dictionary operations
'create': new Word(this._create),
'constant': new Word(this._constant, true),
':': new Word(this._colon, true),
';': new Word(this._semicolon, true),
'immediate': new Word(this._immediate, true),
'0branch': new Word(this._branchIfZero),
'branch': new Word(this._branch),
'exit': new Word(this._exit),
// Stack operations
'lit': new Word(this._lit),
'dup': new Word(this._dup),
'drop': new Word(this._drop),
'swap': new Word(this._swap),
'over': new Word(this._over),
'rot': new Word(this._rot),
'-rot': new Word(this._reverseRot),
'>r': new Word(this._pushReturn),
'r>': new Word(this._popReturn),
'dsp@': new Word(this._dsp),
// Arithmetic
'+': new Word(this._add),
'-': new Word(this._sub),
'*': new Word(this._mul),
'/': new Word(this._div),
'mod': new Word(this._mod),
'or': new Word(this._or),
'and': new Word(this._and),
'xor': new Word(this._xor),
'lshift': new Word(this._lshift),
'rshift': new Word(this._rshift),
'=': new Word(this._equals),
'<': new Word(this._lessThan),
'abs': new Word(this._abs),
// Memory access
'@': new Word(this._fetch),
'!': new Word(this._store),
'c@': new Word(this._fetchChar),
'c!': new Word(this._storeChar),
',': new Word(this._comma),
// Misc
'\'': new Word(this._tick),
'key': new Word(this._key),
's"': new Word(this._makeString, true),
'char': new Word(this._char, true),
'_get_time': new Word(this._getTime),
};
this.debugInfo = new DebugInfo();
this.currentFile = '';
this.interpretSource(BASE_WORDS, 'stdlib');
}
/**
* Read a cell of memory. This will silently align the pointer and will throw
* an exception for invalid addresses.
* @param {number} addr
* @return {number|function} memory value at address
* @throws {ForthRuntimeError}
*/
_fetchCell(addr) {
if (addr < 0 || addr >= MEMORY_CELLS) {
throw new ForthRuntimeError(`Memory fetch out of range: ${addr}`,
this._debugStackCrawl());
}
return this.memory[Math.floor(addr / CELL_SIZE)];
}
/**
* Write value to a memory cell.
* @param {number} addr
* @param {number|function} value
* @throws {ForthRuntimeError}
*/
_storeCell(addr, value) {
if (addr < 0 || addr >= MEMORY_CELLS) {
throw new ForthRuntimeError(`Memory store out of range: ${addr}`,
this._debugStackCrawl());
}
this.memory[Math.floor(addr / CELL_SIZE)] = value;
}
/**
* Read a byte from memory.
* @param {number} addr
* @return {number} Contents of location. The intepreter treats this as
* unsigned and won't sign extend it.
* @throws {ForthRuntimeError}
*/
fetchByte(addr) {
const shift = (addr % CELL_SIZE) * 8;
return (this._fetchCell(addr) >> shift) & 0xff;
}
_storeByte(addr, value) {
if (addr < 0 || addr >= MEMORY_CELLS) {
throw new ForthRuntimeError(`Memory store out of range: ${addr}`,
this._debugStackCrawl());
}
const shift = (addr % CELL_SIZE) * 8;
const index = Math.floor(addr / CELL_SIZE);
this.memory[index] &= ~(0xff << shift);
this.memory[index] |= (value & 0xff) << shift;
}
// Getters/setters for built-in words
get here() {
return this.memory[HERE_PTR / CELL_SIZE];
}
set here(value) {
this.memory[HERE_PTR / CELL_SIZE] = value;
}
get state() {
return this.memory[STATE_PTR / CELL_SIZE];
}
set state(value) {
this.memory[STATE_PTR / CELL_SIZE] = value;
}
get base() {
return this.memory[BASE_PTR / CELL_SIZE];
}
set base(value) {
this.memory[BASE_PTR / CELL_SIZE] = value;
}
/**
* Add a new forth word that calls a native Javascript function.
* If the callback returns a list, this will push it back onto the stack.
* (this allows dependency injection to test the interpreter standalone).
* @param {string} name Dictionary key.
* @param {number} argCount Number of arguments the interpreter will pop
* off the stack and pass to the callback.
* @param {function} callback Javascript function the interpreter will call
* when it executes this word.
* @throws {ForthRuntimeError} If the stack underflows while reading the
* arguments.
*/
createBuiltinWord(name, argCount, callback) {
const self = this;
this.dictionary[name] = new Word(() => {
if ((MEMORY_CELLS - self.stackPointer - CELL_SIZE) <
argCount * CELL_SIZE) {
throw new ForthRuntimeError('stack underflow',
this._debugStackCrawl());
}
const args = [];
let argPtr = this.stackPointer + (argCount - 1) * CELL_SIZE;
for (let i = 0; i < argCount; i++) {
args.push(self._fetchCell(argPtr));
argPtr -= CELL_SIZE;
}
self.stackPointer += argCount * CELL_SIZE;
const result = callback(...args);
if (result) {
for (const elem of result) {
self._push(elem);
}
}
});
}
/**
* Remove top value from operand stack and return it.
* @return {number|function}
* @throws {ForthRuntimeError} if the stack is empty.
*/
_pop() {
if (this.stackPointer >= MEMORY_CELLS) {
throw new ForthRuntimeError('stack underflow', this._debugStackCrawl());
}
const result = this._fetchCell(this.stackPointer);
this.stackPointer += CELL_SIZE;
return result;
}
/**
* Put a value on top of the operand stack
* @param {number|function} val What to push. The interpreter
* automatically truncates numbers to integers.
* @throws {ForthRuntimeError} if the stack is full.
*/
_push(val) {
if (val === undefined) {
throw new ForthRuntimeError('internal error: undefined pushed on stack',
this._debugStackCrawl());
}
if (this.stackPointer < this.here) {
throw new ForthRuntimeError('stack overflow', this._debugStackCrawl());
}
this.stackPointer -= CELL_SIZE;
if (!(val instanceof Function)) {
// the '| 0' forces this to fit in an int. The interpreter stores stack
// entries as integers (except function references for built-in words).
val |= 0;
}
this._storeCell(this.stackPointer, val);
}
/**
* During compilation, write a value at 'here' (next code address) and
* increment here by one cell.
* @param {number} value
* @throws {ForthRuntimeError}
*/
_emitCode(value) {
this.debugInfo.addLineMapping(this.here, this.lineNumber);
if (this.here >= MEMORY_CELLS) {
throw new ForthRuntimeError('out of memory');
}
this._storeCell(this.here, value);
this.here = this.here + CELL_SIZE;
}
/**
* Read the next character from the source string.
* @return {string} next character.
*/
_readChar() {
if (this.interpOffs == this.interpStr.length) {
return '';
}
const ch = this.interpStr[this.interpOffs++];
if (ch == '\n') {
this.lineNumber++;
}
return ch;
}
/**
* Read the next space delimited character sequence from the source string
* (this calls _readChar).
* @return {string} Next token, with leading and trailing whitespace stripped.
*/
_readWord() {
let singleLineComment = false;
let token = '';
while (true) {
const ch = this._readChar();
if (!ch) {
return token;
}
const isSpace = /\s/.test(ch);
if (singleLineComment) {
if (ch == '\n') {
singleLineComment = false;
}
} else if (!singleLineComment && ch == '\\') {
singleLineComment = true;
} else if (!isSpace) {
token += ch;
} else if (token != '') {
// If terminated by newline, push back to correct lineNumber.
if (this.interpStr[--this.interpOffs] == '\n') {
this.lineNumber--;
}
return token;
}
}
}
/**
* Add a word to the dictionary. Retrieve the name for this word from the next
* token in the input string and set the value to the current 'here' address
* (next code to be emitted)
* @throws {ForthCompileError}
*/
_create() {
if (this.state == STATE_COMPILE) {
throw new ForthCompileError('create inside colon def', this.currentFile,
this.lineNumber);
}
const name = this._readWord();
if (!name) {
throw new ForthCompileError('missing word name', this.currentFile,
this.lineNumber);
}
this.currentWord = new Word(this.here, false, true);
this.dictionary[name] = this.currentWord;
this.debugInfo.startWord(name, this.here);
}
/**
* Create a constant in the dictionary, setting name from the next token in
* the stream and popping its value from the stack.
* e.g.
* 10 constant foo
* @throws {ForthCompileError}
*/
_constant() {
if (this.state == STATE_COMPILE) {
throw new ForthCompileError(
'constant inside colon def', this.currentFile, this.lineNumber);
}
const name = this._readWord();
if (!name) {
throw new ForthCompileError('missing word name', this.currentFile,
this.lineNumber);
}
this.dictionary[name] = new Word(this._pop(), false, true);
}
/**
* Begin compiling a new word, adding the address to the dictionary, named
* the next token from the stream.
* Set the state to compiling.
* @throws {ForthCompileError}
*/
_colon() {
if (this.state == STATE_COMPILE) {
throw new ForthCompileError('nested colon def', this.currentFile,
this.lineNumber);
}
this._create();
this.currentWord.literal = false;
this.state = STATE_COMPILE;
}
/**
* Finish compilation of the current word and generate an implicit 'exit'
* word to return to the caller. Switch the state from compiling back to
* interpreting.
* @throws {ForthCompileError}
*/
_semicolon() {
if (this.state != STATE_COMPILE) {
throw new ForthCompileError('unmatched ;', this.currentFile,
this.lineNumber);
}
this.state = STATE_INTERP;
this._emitCode(this._exit);
this.debugInfo.endWord(this.here);
}
/**
* Set a flag on the most recently emitted word so the interpreter will
* execute it immediately when it reads it rather than compiling it.
*/
_immediate() {
// Note that this.currentWord can only be null if 'immediate'
// is the first word in BASE_WORDS.
this.currentWord.immediate = true;
}
_branchIfZero() {
if (this._pop()) {
// Don't branch
this.pc += CELL_SIZE;
} else {
// Condition is false, branch
this.pc = this._fetchCell(this.pc);
}
}
_branch() {
this.pc = this._fetchCell(this.pc);
}
/**
* Return from the current function.
*/
_exit() {
// Most FORTH interpreters execute the REPL as an infinite loop. However,
// this returns to the JavaScript caller once it finishes executing the
// topmost function. It clears the continueExec flag in that case (which
// exec() checks)
if (this.returnStack.length > 0) {
this.pc = this.returnStack.pop();
} else {
this.continueExec = false;
}
}
/**
* Push a constant (literal) value onto the stack. The interpreter generates
* this implicity when it encounters a number, but code can also reference
* as an explicit word, often paired with the tick operator. Only compiled
* code can invoke this. This pushes the value from the subsequent program
* address.
*/
_lit() {
this._push(this._fetchCell(this.pc));
this.pc += CELL_SIZE;
}
_dup() {
const val = this._pop();
this._push(val);
this._push(val);
}
_drop() {
this._pop();
}
_swap() {
const a = this._pop();
const b = this._pop();
this._push(a);
this._push(b);
}
_over() {
this._push(this._fetchCell(this.stackPointer + CELL_SIZE));
}
// ( a b c -- b c a )
_rot() {
const c = this._pop();
const b = this._pop();
const a = this._pop();
this._push(b);
this._push(c);
this._push(a);
}
// ( a b c -- c a b )
_reverseRot() {
const c = this._pop();
const b = this._pop();
const a = this._pop();
this._push(c);
this._push(a);
this._push(b);
}
/**
* Pop a value from the operand stack and push onto the return stack.
*/
_pushReturn() {
this.returnStack.push(this._pop());
}
/**
* Pop a value from the return stack and push onto the operand stack.
* @throws {ForthRuntimeError}
*/
_popReturn() {
if (this.returnStack.length == 0) {
throw new ForthRuntimeError(`return stack underflow`,
this._debugStackCrawl());
}
this._push(this.returnStack.pop());
}
/**
* Push the stack pointer.
*/
_dsp() {
this._push(this.stackPointer);
}
_add() {
this._push(this._pop() + this._pop());
}
_sub() {
const a = this._pop();
const b = this._pop();
this._push(b - a);
}
_mul() {
this._push(this._pop() * this._pop());
}
_div() {
const a = this._pop();
const b = this._pop();
this._push(b / a);
}
_mod() {
const a = this._pop();
const b = this._pop();
this._push(b % a);
}
_or() {
this._push(this._pop() | this._pop());
}
_and() {
this._push(this._pop() & this._pop());
}
_xor() {
this._push(this._pop() ^ this._pop());
}
_lshift() {
const a = this._pop();
const b = this._pop();
this._push(b << a);
}
_rshift() {
const a = this._pop();
const b = this._pop();
this._push(b >> a);
}
_equals() {
this._push(this._pop() === this._pop() ? -1 : 0);
}
_lessThan() {
const a = this._pop();
const b = this._pop();
this._push(b < a ? -1 : 0);
}
_abs() {
this._push(Math.abs(this._pop()));
}
/**
* Read a cell from memory and push onto the stack
*/
_fetch() {
this._push(this._fetchCell(this._pop()));
}
/**
* Pop address and value from the stack and store into memory.
*/
_store() {
const addr = this._pop();
const value = this._pop();
this._storeCell(addr, value);
}
/**
* Read a byte from memory and push on operand stack, treating it
* as unsigned and not sign extending.
*/
_fetchChar() {
const addr = this._pop();
this._push(this.fetchByte(addr));
}
/**
* Write a byte to memory, popping address and value from the operand stack
* and truncating the upper bits of the value to fit in a byte.
*/
_storeChar() {
const addr = this._pop();
const value = this._pop();
this._storeByte(addr, value);
}
_comma() {
this._emitCode(this._pop());
}
/**
* Push the function address for the next word onto the stack.
* This only works in compiled code. It uses the trick from jonesforth
* which grabs the pointer from the next cell.
*/
_tick() {
this._push(this._fetchCell(this.pc));
this.pc += CELL_SIZE;
}
/**
* Return the next input character from the source code string as a byte.
* This uses a single byte unicode encoding. If the character cannot
* be represented in a byte, a space is returned instead.
*/
_key() {
const val = this._readChar();
if (val) {
const code = val.charCodeAt(0);
this._push(code < 256 ? code : 32);
} else {
this._push(-1);
}
}
/**
* Compile a string, pushing its start address and length onto the stack.
* @note I could have implemented this in FORTH, but I was too lazy...
* @throws {ForthError}
*/
_makeString() {
const startLine = this.lineNumber;
const startAddr = this.here;
// The tokenizer will have pushed back the whitespace char, which a hack
// to ensure the line number is correct. Discard it here.
this._readChar();
// Create a jump over the contents of the string, which this emits in-line.
this._storeCell(startAddr, this._branch);
let curAddr = this.here + CELL_SIZE * 2;
while (true) {
if (curAddr >= MEMORY_CELLS) {