forked from howerj/libforth
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathforth.fth
4529 lines (3541 loc) · 134 KB
/
forth.fth
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
#!./forth
( Welcome to libforth, A dialect of Forth. Like all versions
of Forth this version is a little idiosyncratic, but how
the interpreter works is documented here and in various
other files.
This file contains most of the start up code, some basic
start up code is executed in the C file as well which makes
programming at least bearable. Most of Forth is programmed in
itself, which may seem odd if your back ground in programming
comes from more traditional language [such as C], although
less so if you know already know lisp.
For more information about this interpreter and Forth see:
https://en.wikipedia.org/wiki/Forth_%28programming_language%29
And within this code base:
readme.md : for a manual for this interpreter
libforth.h : for information about the C API
libforth.c : for the interpreter itself
unit.c : unit tests for libforth.c
unit.fth : unit tests against this file
main.c : an example interpreter
The interpreter and this code originally descend from a Forth
interpreter written in 1992 for the International obfuscated
C Coding Competition.
See:
http://www.ioccc.org/1992/buzzard.2.design
The manual for the interpreter should be read first before
looking into this code. It is important to understand the
execution model of Forth, especially the differences between
command and compile mode, and how immediate and compiling
words work.
Each of these sections is clearly labeled and they are
generally in dependency order.
Unfortunately the code in this file is not as portable as it
could be, it makes assumptions about the size of cells provided
by the virtual machine, which will take time to rectify. Some
of the constructs are subtly different from the DPANs Forth
specification, which is usually noted. Eventually this should
also be fixed.
A little note on how code is formatted, a line of Forth code
should not exceed 64 characters. All words stack effect, how
many variables on the stack it accepts and returns, should
be commented with the following types:
char / c A character
c-addr An address of a character
addr An address of a cell
r-addr A real address*
u A unsigned number
n A signed number
c" xxx" The word parses a word
c" x" The word parses a single character
xt An execution token
bool A boolean value
ior A file error return status [0 on no error]
fileid A file identifier.
CODE A number from a words code field
PWD A number from a words previous word field
* A real address is one outside the range of the
Forth address space.
In the comments Forth words should be written in uppercase. As
this is supposed to be a tutorial about Forth and describe the
internals of a Forth interpreter, be as verbose as possible.
The code in this file will need to be modified to abide by
these standards, but new code should follow it from the start.
Doxygen style tags for documenting bugs, todos and warnings
should be used within comments. This makes finding code that
needs working on much easier.)
( ==================== Basic Word Set ======================== )
( We'll begin by defining very simple words we can use later,
these a very basic words, that perform simple tasks, they
will not require much explanation.
Even though the words are simple, their stack comment and
a description for them will still be included so external
tools can process and automatically extract the document
string for a given work. )
: postpone ( c" xxx" -- : postpone execution of a word )
immediate find , ;
: constant
:: ( compile word header )
here 1 - h ! ( decrement dictionary pointer )
( change instruction to CONST )
here @ instruction-mask invert and doconst or here !
here 1 + h ! ( increment dictionary pointer )
, ( write in value )
postpone [ ; ( back into command mode )
( These constants are defined as a space saving measure,
numbers in a definition usually take up two cells, one
for the instruction to push the next cell and the cell
itself, for the most frequently used numbers it is worth
defining them as constants, it is just as fast but saves
a lot of space )
-1 constant -1
0 constant 0
1 constant 1
2 constant 2
3 constant 3
0 constant false
1 constant true ( @warning not standards compliant )
( Confusingly the word CR prints a line feed )
10 constant lf ( line feed )
lf constant nl ( new line - line feed on Unixen )
13 constant cret ( carriage return )
-1 -1 1 rshift invert and constant min-signed-integer
min-signed-integer invert constant max-signed-integer
( The following version number is used to mark whether core
files will be compatible with each other, The version number
gets stored in the core file and is used by the loader to
determine compatibility )
4 constant version ( version number for the interpreter )
( This constant defines the number of bits in an address )
cell size 8 * * constant address-unit-bits
( Bit corresponding to the sign in a number )
-1 -1 1 rshift and invert constant sign-bit
( @todo test by how much, if at all, making words like 1+,
1-, <>, and other simple words, part of the interpreter would
speed things up )
: 1+ ( x -- x : increment a number )
1 + ;
: 1- ( x -- x : decrement a number )
1 - ;
: chars ( c-addr -- addr : convert a c-addr to an addr )
size / ;
: chars> ( addr -- c-addr: convert an addr to a c-addr )
size * ;
: tab ( -- : print a tab character )
9 emit ;
: 0= ( n -- bool : is 'n' equal to zero? )
0 = ;
: not ( n -- bool : is 'n' true? )
0= ;
: <> ( n n -- bool : not equal )
= 0= ;
: logical ( n -- bool : turn a value into a boolean )
not not ;
: 2, ( n n -- : write two values into the dictionary )
, , ;
: [literal] ( n -- : write a literal into the dictionary )
dolit 2, ;
: literal ( n -- : immediately compile a literal )
immediate [literal] ;
: sliteral immediate ( I: c-addr u --, Run: -- c-addr u )
swap [literal] [literal] ;
( @todo throw if not found )
: ['] ( I: c" xxx", Run: -- xt )
immediate find [literal] ;
: >instruction ( CODE -- u : extract instruction CODE field )
instruction-mask and ;
( IMMEDIATE-MASK pushes the mask for the compile bit,
which can be used on a CODE field of a word )
1 compile-bit lshift constant immediate-mask
: hidden? ( PWD -- PWD bool : is a word hidden? )
dup 1+ @ hidden-mask and logical ;
: compiling? ( PWD -- PWD bool : is a word immediate? )
dup 1+ @ immediate-mask and logical ;
: cr ( -- : emit a newline character )
nl emit ;
: < ( x1 x2 -- bool : signed less than comparison )
- dup if max-signed-integer u> else logical then ;
: > ( x1 x2 -- bool : signed greater than comparison )
- dup if max-signed-integer u< else logical then ;
( The pad area is an area used for temporary storage, some
words use it, although which ones do should be kept to a
minimum. It is an area of space #pad amount of characters
after the latest dictionary definition. The area between
the end of the dictionary and start of PAD space is used for
pictured numeric output [<#, #, #S, #>]. It is best not to
use the pad area that much. )
128 constant #pad
: pad ( -- addr : push pointer to the pad area )
here #pad + ;
( @todo this can be improved a lot, currently it uses more
space than it has to, 4 cells instead of three.
It does:
push value
push value
Instead of:
magic-2literal-word
value
value
)
: 2literal immediate ( n n -- : compile two literals )
swap [literal] [literal] ;
: latest ( get latest defined word )
pwd @ ;
: stdin ( -- fileid : push fileid for standard input )
`stdin @ ;
: stdout ( -- fileid : push fileid for standard output )
`stdout @ ;
: stderr ( -- fileid : push fileid for the standard error )
`stderr @ ;
: stdin? ( -- bool : are we reading from standard input )
`fin @ stdin = ;
: *+ ( n1 n2 n3 -- n )
* + ;
: 2- ( n -- n : decrement by two )
2 - ;
: 2+ ( n -- n : increment by two )
2 + ;
: 3+ ( n -- n : increment by three )
3 + ;
: 2* ( n -- n : multiply by two )
1 lshift ;
: 2/ ( n -- n : divide by two )
1 rshift ;
: 4* ( n -- n : multiply by four )
2 lshift ;
: 4/ ( n -- n : divide by four )
2 rshift ;
: 8* ( n -- n : multiply by eight )
3 lshift ;
: 8/ ( n -- n : divide by eight )
3 rshift ;
: 256* ( n -- n : multiply by 256 )
8 lshift ;
: 256/ ( n -- n : divide by 256 )
8 rshift ;
: 2dup ( n1 n2 -- n1 n2 n1 n2 : duplicate two values )
over over ;
: mod ( u1 u2 -- u : calculate the remainder of u1/u2 )
2dup / * - ;
( @todo implement UM/MOD in the VM, then use this to implement
'/' and MOD )
: um/mod ( u1 u2 -- rem quot : remainder and quotient of u1/u2 )
2dup / >r mod r> ;
( @warning this does not use a double cell for the multiply )
: */ ( n1 n2 n3 -- n4 : [n2*n3]/n1 )
* / ;
: char ( -- n : read in a character from the input steam )
key drop key ;
: [char] ( c" x" -- R: -- char : immediately compile next char )
immediate char [literal] ;
( COMPOSE is a high level function that can take two executions
tokens and produce a unnamed function that can do what they
both do.
It can be used like so:
:noname 2 ;
:noname 3 + ;
compose
execute
.
5 <-- 5 is printed!
I have not found a use for it yet, but it sure is neat.)
: compose ( xt1 xt2 -- xt3 : create a function from xt-tokens )
>r >r ( save execution tokens )
postpone :noname ( create a new :noname word )
r> , ( write first token )
r> , ( write second token )
(;) ; ( terminate new :noname )
( CELLS is a word that is not needed in this interpreter but
it required to write portable code [I have probably missed
quite a few places where it should be used]. The reason it
is not needed in this interpreter is a cell address can only
be in multiples of cells, not in characters. This should be
addressed in the libforth interpreter as it adds complications
when having to convert to and from character and cell address.)
: cells ( n1 -- n2 : convert cell count to address count)
immediate ;
: cell+ ( a-addr1 -- a-addr2 )
cell + ;
: cell- ( a-addr1 -- addr2 )
cell - ;
: negative? ( x -- bool : is a number negative? )
sign-bit and logical ;
: mask-byte ( x -- x : generate mask byte )
8* 255 swap lshift ;
: select-byte ( u i -- c )
8* rshift 0xff and ;
: xt-instruction ( PWD -- CODE : extract instruction from PWD )
cell+ @ >instruction ;
: defined-word? ( PWD -- bool : is defined or a built-in word)
xt-instruction dolist = ;
: char+ ( c-addr -- c-addr : increment a c-addr one c-addr )
1+ ;
: 2chars ( c-addr1 c-addr2 -- addr addr : chars on two c-addr)
chars swap chars swap ;
: 2chars> ( addr addr -- c-addr c-addr: chars> on two addr )
chars> swap chars> swap ;
: hex ( -- : print out hex )
16 base ! ;
: octal ( -- : print out octal )
8 base ! ;
: binary ( -- : print out binary )
2 base ! ;
: decimal ( -- : print out decimal )
0 base ! ;
: negate ( x -- x )
-1 * ;
: abs ( x -- u : return the absolute value of a number )
dup negative? if negate then ;
: square ( x -- x )
dup * ;
: sum-of-squares ( a b -- c : compute a^2 + b^2 to get c )
square swap square + ;
: drup ( x y -- x x )
drop dup ;
: +! ( x addr -- : add x to a value stored at addr )
tuck @ + swap ! ;
: 1+! ( addr -- : increment a value at an address )
1 swap +! ;
: 1-! ( addr -- : decrement a value at an address )
-1 swap +! ;
: c+! ( x c-addr -- : add x to a value stored at c-addr )
tuck c@ + swap c! ;
: toggle ( addr u -- : xor value at addr with u )
over @ xor swap ! ;
: lsb ( x -- x : mask off the least significant byte of a cell )
255 and ;
: \ ( -- : immediate word, used for single line comments )
immediate begin key nl = until ;
: ?dup ( x -- ? )
dup if dup then ;
: min ( n n -- n : return the minimum of two integers )
2dup < if drop else nip then ;
: max ( n n -- n : return the maximum of two integers )
2dup > if drop else nip then ;
: umin ( u u -- u : return the minimum of two unsigned numbers )
2dup u< if drop else nip then ;
: umax ( u u -- u : return the maximum of two unsigned numbers )
2dup > if drop else nip then ;
: limit ( x min max -- x : limit x with a minimum and maximum )
rot min max ;
: >= ( n n -- bool )
< not ;
: <= ( n n -- bool )
> not ;
: 2@ ( a-addr -- u1 u2 : load two consecutive memory cells )
dup 1+ @ swap @ ;
: 2! ( u1 u2 a-addr -- : store two values at two consecutive memory cells )
2dup ! nip 1+ ! ;
( @bug I don't think this is correct. )
: r@ ( -- u, R: u -- )
r> r @ swap >r ;
: rp@ ( -- u, R: u -- )
r> r @ swap >r ;
( @todo r!, rp! )
: 0> ( n -- bool )
0 > ;
: 0<= ( n -- bool )
0> not ;
: 0< ( n -- bool )
0 < ;
: 0>= ( n -- bool )
0< not ;
: 0<> ( n -- bool )
0 <> ;
: signum ( n -- -1 | 0 | 1 : Signum function )
dup 0> if drop 1 exit then
0< if -1 exit then
0 ;
: nand ( u u -- u : bitwise NAND )
and invert ;
: odd ( u -- bool : is 'n' odd? )
1 and ;
: even ( u -- bool : is 'n' even? )
odd not ;
: nor ( u u -- u : bitwise NOR )
or invert ;
: ms ( u -- : wait at least 'u' milliseconds )
clock + begin dup clock u< until drop ;
: sleep ( u -- : sleep for 'u' seconds )
1000 * ms ;
: align ( addr -- addr : align an address, nop in this implemented )
immediate ;
: ) ( -- : do nothing, this allows easy commenting out of code )
immediate ;
: bell ( -- : emit an ASCII BEL character )
7 emit ;
: b/buf ( -- u : bytes per buffer )
1024 ;
: .d ( x -- x : debug print )
dup . ;
: compile, ( x -- : )
, ;
: >mark ( -- : write a hole into the dictionary and push a pointer to it )
here 0 , ;
: <resolve ( addr -- : )
here - , ;
: end immediate ( a synonym for until )
postpone until ;
: bye ( -- : quit the interpreter )
0 r ! ;
: pick ( xu ... x1 x0 u -- xu ... x1 x0 xu )
sp@ swap cells - cell - @ ;
: 3dup ( x1 x2 x3 -- x1 x2 x3 x1 x2 x3 : duplicate a set of three items )
2 pick 2 pick 2 pick ;
: rpick ( R: xu ... x1 x0 u -- xu ... x1 x0 xu )
r@ swap - @ ;
: within ( test low high -- bool : is test between low and high )
over - >r - r> u< ;
: invalidate ( -- : invalidate this Forth core )
1 `invalid ! ;
: signed ( x -- bool : return true if sign bit set )
[ 1 size 8 * 1- lshift ] literal and logical ;
: u>= ( x y -- bool : unsigned greater than or equal to )
2dup u> >r = r> or ;
: u<= ( x y -- bool : unsigned less than or equal to )
u>= not ;
: rdrop ( R: x -- : drop a value from the return stack )
r> ( get caller's return address )
r> ( get value to drop )
drop ( drop it like it's hot )
>r ; ( return return address )
: rdup
r> ( get caller's return address )
r> ( get value to duplicate )
dup ( ... )
>r >r >r ; ( make it all work )
: chere ( -- c-addr : here as in character address units )
here chars> ;
: source ( -- c-addr u )
#tib ( size of input buffer, in characters )
tib ; ( start of input buffer, in characters )
: stdin? ( -- bool : are we reading from standard in? )
`fin @ `stdin @ = ;
: source-id ( -- 0 | -1 | file-id )
(
Value Input Source
-1 String
0 Reading from user input / standard in
file-id )
`source-id @
0= if
stdin? if 0 else `fin @ then
else
-1
then ;
: under ( x1 x2 -- x1 x1 x2 )
>r dup r> ;
: 2nip ( n1 n2 n3 n4 -- n3 n4 )
>r >r 2drop r> r> ;
: 2over ( n1 n2 n3 n4 – n1 n2 n3 n4 n1 n2 )
>r >r 2dup r> swap >r swap r> r> -rot ;
: 2swap ( n1 n2 n3 n4 – n3 n4 n1 n2 )
>r -rot r> -rot ;
: 2tuck ( n1 n2 n3 n4 – n3 n4 n1 n2 n3 n4 )
2swap 2over ;
: 3drop ( n1 n2 n3 -- )
drop 2drop ;
: 4drop ( n1 n2 n3 n4 -- )
2drop 2drop ;
: nos1+ ( x1 x2 -- x1+1 x2 : increment the next variable on that stack )
swap 1+ swap ;
: ?dup-if immediate ( x -- x | - : ?dup and if rolled into one! )
['] ?dup , postpone if ;
: ?if ( -- : non destructive if )
immediate ['] dup , postpone if ;
: (hide) ( token -- hide-token : this hides a word from being found by the interpreter )
?dup-if
dup @ hidden-mask or swap tuck ! exit
then 0 ;
: hide ( WORD -- : hide with drop )
find dup if (hide) then drop ;
: reveal ( hide-token -- : reveal a hidden word )
dup @ hidden-mask invert and swap ! ;
: ?exit ( x -- : exit current definition if not zero )
if rdrop exit then ;
: decimal? ( c -- f : is character a number? )
[char] 0 [ char 9 1+ ] literal within ;
: lowercase? ( c -- f : is character lower case? )
[char] a [ char z 1+ ] literal within ;
: uppercase? ( C -- f : is character upper case? )
[char] A [ char Z 1+ ] literal within ;
: alpha? ( C -- f : is character part of the alphabet? )
dup lowercase? swap uppercase? or ;
: alphanumeric? ( C -- f : is character alphabetic or a number ? )
dup alpha? swap decimal? or ;
: printable? ( c -- bool : is printable, excluding new lines and tables )
32 127 within ;
: >upper ( c -- C : convert char to uppercase iff lower case )
dup lowercase? if bl xor then ;
: >lower ( C -- c : convert char to lowercase iff upper case )
dup uppercase? if bl xor then ;
: <=> ( x y -- z : spaceship operator! )
2dup
> if 2drop -1 exit then
< ;
: start-address ( -- c-addr : push the start address )
`start-address @ ;
: >real-address ( c-addr -- r-addr : convert an interpreter address to a real address )
start-address + ;
: real-address> ( c-addr -- r-addr : convert a real address to an interpreter address )
start-address - ;
: peek ( r-addr -- n : )
pad chars> >real-address swap size memory-copy pad @ ;
: poke ( n r-addr -- : )
swap pad ! pad chars> >real-address size memory-copy ;
: die! ( x -- : controls actions when encountering certain errors )
`error-handler ! ;
: start! ( cfa -- : set the word to execute at startup )
`instruction ! ;
: warm ( -- : restart the interpreter, warm restart )
1 restart ;
: trip ( x -- x x x : triplicate a number )
dup dup ;
: roll ( xu xu-1 ... x0 u -- xu-1 ... x0 xu : move u+1 items on the top of the stack by u )
[ smudge ] ( un-hide this word so we can call it recursively )
dup 0 >
if
swap >r 1- roll r> swap
else
drop
then ;
smudge
: 2rot ( n1 n2 n3 n4 n5 n6 – n3 n4 n5 n6 n1 n2 )
5 roll 5 roll ;
: s>d ( x -- d : convert a signed value to a double width cell )
( @note the if...else...then is only necessary as this Forths
booleans are 0 and 1, not 0 and -1 as it usually is )
dup 0< if -1 else 0 then ;
: trace ( level -- : set tracing level )
`debug ! ;
: verbose ( -- : get the log level )
`debug @ ;
: count ( c-addr1 -- c-addr2 u : get a string whose first char is its length )
dup c@ nos1+ ;
: bounds ( x y -- y+x x : make an upper and lower bound )
over + swap ;
: aligned ( unaligned -- aligned : align a pointer )
[ size 1- ] literal +
[ size 1- ] literal invert and ;
: rdepth
max-core `stack-size @ - r @ swap - ;
: argv ( -- r-addr : push pointer to array of string pointers to program )
`argv @ ;
: argc ( -- u : push the number of arguments in the argv array )
`argc @ ;
: +- ( x1 x2 -- x3 : copy the sign of x1 to x2 giving x3 )
[ sign-bit 1- ] literal and
swap
sign-bit and or ;
: /string ( c-addr1 u1 u2 -- c-addr2 u2 : advance a string by n characters )
over min rot over + -rot - ;
hide stdin?
: cfa immediate ( find-address -- cfa )
( Given the address of the PWD field of a word this
function will return an execution token for the word )
( @todo if < dictionary start PWD is invalid )
;
: again immediate
( loop unconditionally in a begin-loop:
begin ... again )
['] branch , <resolve ;
\ : >body ( xt -- a-addr : a-addr is data field of a CREATEd word )
\ cfa 5 + ;
: execute ( xt -- : given an execution token, execute the word )
( create a word that pushes the address of a hole to write to.
A literal takes up two words, '!' takes up one, that's right,
some self modifying code! )
[ here 3 cells + literal ] ( calculate place to write to )
! ( write an execution token to a hole )
[ 0 , ] ; ( this is the hole we write )
( @todo integrate catch/throw into the interpreter as primitives )
: catch ( xt -- exception# | 0 : return addr on stack )
sp@ >r ( xt : save data stack pointer )
`handler @ >r ( xt : and previous handler )
r@ `handler ! ( xt : set current handler )
execute ( execute returns if no throw )
r> `handler ! ( restore previous handler )
r> drop ( discard saved stack ptr )
0 ; ( 0 : normal completion )
( @todo use this everywhere )
: throw ( ??? exception# -- ??? exception# )
?dup-if ( exc# \ 0 throw is no-op )
`handler @ r ! ( exc# : restore prev return stack )
r> `handler ! ( exc# : restore prev handler )
r> swap >r ( saved-sp : exc# on return stack )
sp! drop r> ( exc# : restore stack )
( return to the caller of catch because return )
( stack is restored to the state that existed )
( when catch began execution )
then ;
: interpret ( c1" xxx" ... cn" xxx" -- : This word implements the interpreter loop )
begin
['] read catch
?dup-if [char] ! emit tab . cr then ( exception handler of last resort )
again ;
: [interpret] ( c1" xxx" ... cn" xxx" -- : immediate version of interpret )
immediate interpret ;
interpret ( use the new interpret word, which can catch exceptions )
find [interpret] cell+ start! ( the word executed on restart is now our new word )
( The following words are using in various control structure related
words to make sure they only execute in the correct state )
: ?comp ( -- : error if not compiling )
state @ 0= if -14 throw then ;
: ?exec ( -- : error if not executing )
state @ if -22 throw then ;
( begin...while...repeat These are defined in a very "Forth" way )
: while
?comp
immediate postpone if ( branch to repeats THEN ) ;
: whilst postpone while ;
: repeat immediate
?comp
swap ( swap BEGIN here and WHILE here )
postpone again ( again jumps to begin )
postpone then ; ( then writes to the hole made in if )
: never ( never...then : reserve space in word )
immediate 0 [literal] postpone if ;
: unless ( bool -- : like IF but execute clause if false )
immediate ?comp ['] 0= , postpone if ;
: endif ( synonym for THEN )
immediate ?comp postpone then ;
( Experimental FOR ... NEXT )
: for immediate
?comp
['] 1- ,
['] >r ,
here ;
: (next) ( -- bool, R: val -- | val+1 )
r> r> 1- dup 0< if drop >r 1 else >r >r 0 then ;
: next immediate
?comp
['] (next) ,
['] ?branch ,
here - , ;
( ==================== Basic Word Set ======================== )
( ==================== DOER/MAKE ============================= )
( DOER/MAKE is a word set that is quite powerful and is
described in Leo Brodie's book "Thinking Forth". It can be
used to make words whose behavior can change after they
are defined. It essentially makes the structured use of
self-modifying code possible, along with the more common
definitions of "defer/is".
According to "Thinking Forth", it has two purposes:
1. To change the state of a function.
2. To factor out common phrases of a words definition.
An example of the first instance:
doer say
: sad " Good bye, cruel World!" cr ;
: happy " Hello, World!" cr ;
: person say ;
make person happy
person \ prints "Good bye, cruel World!"
make person sad
person \ prints "Hello, World!"
An example of the second:
doer op
: sum \ n0 ... nX X -- sum<0..X>
make op + 1 do op loop ;
: mul \ n0 ... nX X -- mul<0..X>
make op * 1 do op loop ;
The above example is a bit contrived, the definitions and
functionality are too simple for this to be worth factoring
out, but it shows how you can use DOER/MAKE. )
: noop ; ( -- : default word to execute for doer, does nothing )
: doer ( c" xxx" -- : make a work whose behavior can be changed by make )
immediate ?exec :: ['] noop , (;) ;
: found? ( xt -- xt : thrown an exception if the xt is zero )
dup 0= if -13 throw then ;
( It would be nice to provide a MAKE that worked with
execution tokens as well, although "defer" and "is" can be
used for that. MAKE expects two word names to be given as
arguments. It will then change the behavior of the first word
to use the second. MAKE is a state aware word. )
: make immediate ( c1" xxx" c2" xxx" : change parsed word c1 to execute c2 )
find found? cell+
find found?
state @ if ( compiling )
swap postpone 2literal ['] ! ,
else ( command mode )
swap !
then ;
( ==================== DOER/MAKE ============================= )
( ==================== Extended Word Set ===================== )
: r.s ( -- : print the contents of the return stack )
r>
[char] < emit rdepth (.) drop [char] > emit
space
rdepth dup 0> if dup
begin dup while r> -rot 1- repeat drop dup
begin dup while rot dup . >r 1- repeat drop
then drop cr
>r ;
: log ( u base -- u : command the _integer_ logarithm of u in base )
>r
dup 0= if -11 throw then ( logarithm of zero is an error )
0 swap
begin
nos1+ rdup r> / dup 0= ( keep dividing until 'u' is zero )
until
drop 1- rdrop ;
: log2 ( u -- u : compute the _integer_ logarithm of u )
2 log ;
: alignment-bits ( c-addr -- u : get the bits used for aligning a cell )
[ 1 size log2 lshift 1- literal ] and ;
: time ( " ccc" -- n : time the number of milliseconds it takes to execute a word )
clock >r
find found? execute
clock r> - ;
( defer...is is probably not standards compliant, it is still neat! )
: (do-defer) ( -- self : pushes the location into which it is compiled )
r> dup >r 1- ;
: defer immediate ( " ccc" -- , Run Time -- location :
creates a word that pushes a location to write an execution token into )
?exec
:: ['] (do-defer) , (;) ;
: is ( location " ccc" -- : make a deferred word execute a word )
find found? swap ! ;
hide (do-defer)
( This RECURSE word is the standard Forth word for allowing
functions to be called recursively. A word is hidden from the
compiler until the matching ';' is hit. This allows for previous
definitions of words to be used when redefining new words, it
also means that words cannot be called recursively unless the
recurse word is used.
RECURSE calls the word being defined, which means that it
takes up space on the return stack. Words using recursion
should be careful not to take up too much space on the return
stack, and of course they should terminate after a finite
number of steps.
We can test "recurse" with this factorial function:
: factorial dup 2 < if drop 1 exit then dup 1- recurse * ;
)
: recurse immediate
?comp
latest cell+ , ;
: myself ( -- : myself is a synonym for recurse )
immediate postpone recurse ;
( The "tail" function implements tail calls, which is just a
jump to the beginning of the words definition, for example
this word will never overflow the stack and will print "1"
followed by a new line forever,
: forever 1 . cr tail ;
Whereas
: forever 1 . cr recurse ;
or