-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathperlforth
executable file
·1967 lines (1589 loc) · 60.3 KB
/
perlforth
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
#!/usr/bin/perl
# -------- description + version history -------- #FOLD00
=head1 PerlForth
an incremental compiler and interactive interpreter, based on a
virtual machine, executing indirect threaded code.
=cut
my $version = 29;
# to do: improve file interface. can only read source files to compile from now.
# 20190905,ls 0.29 partial unrolling main interpreter loop
# 20190905,ls 0.28 fixed /, stripping the hidden fractional part
# 20110512,ls colors
# 20110428,ls 0.27 arithmetic on addresses may result in negative mem array indici. changed some memory primitives to unsign addresses
# 20110427,ls problem with 64 bit. forcing to 32 bit for now.
# 20110420,ls 0.26 string packing and unpacking using W type strings.
# 20091001,ls 0.25 initialising catchframe in empty avoids undefined error handler when quitting in site-forth.4th
# 20090930,ls 0.24 loading /usr/local/share/perlforth/site-forth.4th at start
# 20090106,ls 0.23 fixes for 64bit Perl versions
# 20090106,ls 0.22 can compile source from included file.
# 20090103,ls 0.21 vocabularies.
# 20090101,ls 0.20 prepared for vocabularies.
# 20081228,ls 0.19 radix prefixes
# 20081228,ls 0.18 catch, throw, top level error handler, fixed bug in hash which rendered does> defective
# 20081228,ls 0.17 experimentally connected Perl exception handler to interpreter errors
# 20081223,ls 0.16 does>, keymap lister, linked vars, defers, constants, arrays.
# 20081223,ls 0.15 hilevelized/deperled many words. key is now deferred. cleanup. stuff added.
# 20081221,ls 0.14 simulated disk loaded during boot, extending interpreter.
# better compile-time word defining macros.
# branching version which moves definitions to simulated disk.
# 20081221,ls 0.13 simulated disk for testing compiling from file.
# 20081221,ls 0.12 some string support: ." s" ," /string move$
# 20081220,ls 0.11 added move fill for next leave ?leave i j do ?do loop
# 20081217,ls 0.10 numbers, if else then begin while repeat until again.
# 20081217,ls 0.09 added [ ], create, variable, : ; colon definitions work.
# 20081217,ls 0.08 input line is parsed now. "real" interpreter connected,
# but compilation and numbers are stubs.
# 20081217,ls 0.07 bit logic, comparison, keymap customizer, hide/reveal, skip/scan
# 20081215,ls 0.06 debugging and cleanup
# 20081215,ls 0.05 rudimentary command execution loop
# 20081214,ls 0.04 rudimentary buffered line input, more primitives.
# 20081213,ls 0.03 more run time words, primitives, flow control
# 20081211,ls 0.02 added run time words, constants, minimal flow control
# 20081210,ls 0.01 ITC inner interpreter executes lo- and hilevel
use strict;
use warnings;
use Term::ReadKey;
#use Term::ANSIColor;
# -------- configuration items -------- #FOLD00
my $tibsize = 256; # size of terminal input buffer
my $cell;
# override. uses perl compilation width if undefined.
# $cell = 0; # bits per cell determined by size perl has been compiled for
# $cell = 0xffff; # 16 bit override
$cell = 0xffffffff; # 32 bit override
# $cell = 0xffffffffffffffff; # 64 bit override
# 2011apr27,ls problem with 64 bit. forcing to 32 bit for now.
# -------- simulated sources disk -------- #FOLD00
# simulated source disk, contents are loaded and compiled during boot
my @disk =
(
"forth only",
"forth definitions",
'#10 base !',
': binary 2 base ! ;', # ( -- )
': octal 8 base ! ;', # ( -- )
': decimal 10 base ! ;', # ( -- )
': hex 16 base ! ;', # ( -- )
": align ; immediate", # ( -- )
": aligned ; immediate", # ( a1 -- a2 )
": pad here 256 + ;", # ( -- a )
": latest last @ ;", # ( -- a )
": recurse latest , ; immediate", # ( -- )
"also hidden",
": compile r> skim , >r ;", # ( -- )
": postpone ' , ; immediate", # ( -- )
": literal ?comp (lit) (lit) , , ; immediate", # ( x -- ) ( -- x )
": ['] ' postpone literal ; immediate", # ( -- ) ( -- a )
"previous",
# --- chars and strings ---
': char bl parse drop c@ ;', # ( -- c )
': [char] char postpone literal ; immediate', # ( -- ) ( -- c )
': ctrl char $1F and ;', # ( -- c )
': [ctrl] ctrl postpone literal ; immediate', # ( -- ) ( -- c )
': \ 0 parse 2drop ; immediate', # ( -- )
': // postpone \ ; immediate', # ( -- )
': s( [char] ) parse ;', # ( -- a n )
': ( s( 2drop ; immediate', # ( -- )
': .( s( type ;', # ( -- )
"also hidden",
': move$ 2dup c! 1+ swap move ;', # ( a1 n a2 -- )
': ,s here over 1+ allot move$ ;', # ( a n -- )
': ," [char] " parse ,s ;', # ( -- )
': s" ?comp [\'] (slit) , ," ; immediate', # ( -- ) ( -- a n )
': ." ?comp [\'] (.") , ," ; immediate', # ( -- ) ( -- )
# --- flow control ---
"definitions",
': resolve here - , ;', # ( a -- )
': <resolve here over - swap ! ;', # ( a -- )
": ?clause compile (0branch) ;", # ( -- )
": clause compile (branch) ;", # ( -- )
": mark here 0 , ;", # ( -- a )
"previous definitions",
"also hidden",
': if ?comp ?clause mark 1 ; immediate',
': else ?comp 1 structured clause mark swap <resolve 2 ; immediate',
': then ?comp dup 2 = + 1 structured <resolve ; immediate',
': endif postpone then ; immediate',
': begin ?comp here 3 ; immediate',
': while ?comp 3 structured ?clause mark 4 ; immediate',
': repeat ?comp 4 structured swap clause resolve <resolve ; immediate',
': until ?comp 3 structured ?clause resolve ; immediate',
': again ?comp 3 structured clause resolve ; immediate',
"definitions",
": docompiler create , , immediate",
" does> ?comp skim , @ >r",
" here innerloop exchange",
" mark r> ;",
": loopcompiler create , , immediate",
" does> ?comp skim >r @ structured r> , dup 1+ resolve <resolve innerloop ! ;",
"previous definitions",
"also hidden",
"5 ' (do) docompiler do",
"5 ' (?do) docompiler ?do",
"6 ' (for) docompiler for",
"5 ' (loop) loopcompiler loop",
"5 ' (+loop) loopcompiler +loop",
"6 ' (next) loopcompiler next",
": leave, ?comp innerloop @ ?dup 0= -26 and throw swap , , ;",
": leave ['] (leave) leave, ; immediate",
": ?leave ['] (?leave) leave, ; immediate",
": unloop ?comp innerloop @ 0= -26 and throw compile (unloop) ; immediate",
# ---
': tuck swap over ;', # ( x1 x2 -- x2 x1 x2 )
': pluck 2 pick ;', # ( x1 x2 x3 -- x1 x2 x3 x1 )
': max 2dup < if swap then drop ;', # ( x1 x2 -- x1|x2 )
': min 2dup > if swap then drop ;', # ( x1 x2 -- x1|x2 )
': -rot rot rot ;', # ( x1 x2 x3 -- x3 x1 x2 )
': (abort") if -2 dup r> count newerror throw then',
' r> count + >r ;',
': abort" ?comp compile (abort") ," ; immediate', # ( f -- )
': link here swap exchange , ;',
': unlink dup @ ?dup if @ over ! then drop ;',
# tricky: 'make new constants behave like "true" (which is a constant)'
# tricky: 'make new deferred words behave like "key" (which is a deferred word)'
# tricky: 'make new arrays behave like "keytable" (which is an array)'
# tricky: 'make new vocabularies behave like "forth" (which is a vocabulary)'
": constant constants link create , [ ' true @ ] literal use ;",
'1 constant cell',
": defer defers link create cell allot [ ' key @ ] literal use ;",
": array arrays link create dup , allot [ ' keytable @ ] literal use ;",
": vocabulary vocabularies link create 0 , 0 , [ ' forth @ ] literal use ;",
': variable variables link create cell allot ;',
": value constant ;", # values behave like constants. for now.
': vocs vocabularies begin @ ?dup while dup 1+ .name space repeat ;',
'previous',
': cell+ 1+ ; : char+ 1+ ;',
': cell- 1- ; : char- 1- ;',
': cells ; : chars ; ',
': range over + swap ;', # ( x1 n -- x2 x1 )
': erase 0 fill ;', # ( a n -- )
': blank bl fill ;', # ( a n -- )
': c, 255 and , ;', # ( c -- )
': within pluck < >r < r> or 0= ;', # ( n1 n2 n3 -- f )
': printable bl 127 within ;', # ( c -- f )
': emits swap dup 0> and', # ( u c -- )
' 0 ?do dup emit loop drop ;',
': spaces bl emits ;', # ( u -- )
': >body cell+ ; ', # ( a1 -- a2 )
': body> cell- ; ', # ( a1 -- a2 )
': word here >r parse r@ move$ r> ;', # ( c -- a )
': lines >r', # ( a -- )
' bl word count',
' fileopen',
' begin fileread',
' while r@ execute',
' repeat',
' fileclose rdrop ;',
": from fileopen", # ( a n -- )
" begin fileread",
" while evaluate",
" repeat fileclose ;",
': from" [char] " parse from ;', # ( -- )
# is and to identical yet but they will check to make sure the target is of proper type
# therefore no factoring in these words, as these are in transition.
"also hidden definitions",
": (was) r> dup cell+ >r @ >body @ ;",
": (is) r> dup cell+ >r @ >body ! ;",
": (to) r> dup cell+ >r @ >body ! ;",
"previous definitions",
"also hidden",
": was compiling if compile (was) exit then ' >body @ ; immediate",
": is compiling if compile (is) exit then ' >body ! ; immediate",
": to compiling if compile (to) exit then ' >body ! ; immediate",
"previous",
# --- obsolescent input parsing and vocabulary search. required by dpans94 ---
': find dup count hunt', # ( a1 -- a2 0 | a2 1 | a2 -1 )
' dup if', # 1: immediate. -1: non-immediate
' nip dup name>',
' swap ?imm invert 1 or',
' then ;',
# --- pictured number output conversion ---
': s>d dup 0< ;', # ( x -- d )
': <# swap >r pad tuck r> ;', # ( d -- a x a x )
': #> drop nip tuck - ;', # ( a x a x -- a x )
': hold rot 1-', # ( a x c -- a x )
' dup here < -17 and throw',
' -rot pluck c! ;',
': cipher dup 9 > if 7 + then [char] 0 + ;', # ( n -- c )
': # base @ u/mod swap cipher hold ;', # ( a x -- a x )
': #s begin # dup 0= until ;', # ( a x -- a x )
': sign pluck 0< if [char] - hold then ;', # ( x a x -- x a x )
': string <# #s sign #> ;', # ( n -- a n )
': (.) s>d >r abs r> string ;', # ( n1 -- a n2 )
': (u.) 0 string ;', # ( u -- a n )
': . (.) type space ;', # ( n -- )
': u. (u.) type space ;', # ( u -- )
': (.r) over - spaces type ;', # ( a n1 n2 -- )
': .r >r (.) r> (.r) ;', # ( n u -- )
': u.r >r (u.) r> (.r) ;', # ( u1 u2 -- )
': .b base exchange swap u. base ! ;', # ( n base -- )
': .% 2 .b ;', # ( n -- )
': .# 10 .b ;', # ( n -- )
': .$ 16 .b ;', # ( n -- )
': .s depth ?dup if', # ( -- )
' for i pick . next',
' else ." stack empty"',
' then ;',
': number ?number 0= -24 and throw ;', # ( a n1 -- n2 )
# --- string words
': /string over min tuck 2>r + 2r> - ;', # ( a n1 n2 -- )
': -trailing dup if dup for 1- 2dup + c@ bl <> ?leave next 1+ then ;',
# left/right boundary, centered type
': typer ( a n1 n2 -- ) over - 0 max spaces type ;',
': typel ( a n1 n2 -- ) over - 0 max >r type r> spaces ;',
': typec ( a n1 n2 -- ) over - 0 max dup 2/ dup spaces - >r type r> spaces ;',
# --- 'char, ^ctrlchar, >shellcommand input
"also hidden definitions",
': toshell 1 /string drop 0 parse + over -', # ( a n -- )
' compiling if compile (slit) ,s compile then shell ;',
": andchar nip swap 1+ c@ and compiling if postpone literal then ;", # ( a n -- c )
": tochar 255 andchar ;", # ( a n -- c )
": toctrl 31 andchar ;", # ( a n -- c )
': dispatchable s" \'^>" rot scan nip ;', # ( c -- u )
" create action ] toshell toctrl tochar [",
': dispatch action + @ execute ;', # ( a n1 n2 -- ? )
": prefixes over c@ dispatchable ?dup if 1- dispatch exit then",
#" 2dup analyze_input if process_input exit then",
" (notfound) ;",
"' prefixes is notfound", # ( a n -- ? )
': .? dup defined if . else drop ." undefined" then ;',
': .linknames',
' >r begin @ ?dup',
' while dup 1+',
' dup cr .name ." : "',
' >body @ r@ execute',
' repeat rdrop cr ;',
": .variables variables ['] .? .linknames ;",
": .constants constants ['] . .linknames ;",
": .arrays arrays ['] . .linknames ;",
": .defers defers ['] .name .linknames ;",
": .vocs vocabularies ['] . .linknames ;",
": user_interrupt -28 throw ;",
"previous definitions",
': shell: create ," does> count shell ;',
'shell: page clear',
'shell: ps ps auxf|pager',
'shell: sh bash',
': command: create does> drop source shell postpone \ ;',
'command: ls',
': cls page ;',
': commandline ." (ctrl-D to exit)" sh ." ok" cr ;',
': .keys -1 keytable @ 0 do',
' i keytable @',
' ?dup if',
" dup ['] nop <> if",
' cr ." ctrl-" i \'@ + emit',
' 3 spaces dup .name',
' then',
' drop',
' then',
' loop cr ;',
# "0 keytable -1 keytable @ ' nop fill",
"0 keytable bl ' nop fill",
": bindkey keytable ! ;",
"also hidden",
"' .arrays ^A bindkey",
"' .constants ^B bindkey",
"' user_interrupt ^C bindkey",
"' commandline ^D bindkey",
"' .defers ^E bindkey",
" 0 ^H bindkey",
" 0 ^I bindkey",
" 0 ^J bindkey",
"' .keys ^K bindkey",
"' page ^L bindkey",
"' order ^O bindkey",
"' bye ^Q bindkey",
"' .variables ^V bindkey",
"' words ^W bindkey",
"' .vocs ^X bindkey",
': fkey',
' begin (key)',
' dup bl < 0= unless',
' dup keytable @',
' ?dup while',
' execute drop',
' repeat ;',
': accept >r 0', # ( a n1 -- n2 )
' begin dup r@ <>',
' while fkey dup 10 =',
' if r> 2drop dup >r',
' else decode',
' then',
' repeat swap r> 2drop ;',
': query tib dup tibsize accept dup #tib ! pushsource space ;',
"definitions",
": (quit) empty postpone [ begin query interpret prompt again ;",
"' (quit) is quit",
': (prompt) compiling 0= if ." ok" depth 0 ?do \'. emit loop then cr ;',
"' (prompt) is prompt",
"previous definitions",
": :noname ?exec here [ latest @ ] literal , ] ; immediate",
# -- time
": time ( -- secs ) epoch 86400 mod ;",
": ##: ( u1 -- u2 ) base @ >r decimal # 6 base ! # ': hold r> base ! ;",
": .now ( -- ) time s>d <# ##: ##: #s #> type ;",
": now ( -- s m h ) time 60 /mod 60 /mod ;",
# load site-forth.4th at start
' :noname ( -- ) s" /usr/local/share/perlforth/site-forth.4th" from ; catch drop',
# ' \ dup -38 <> and throw',
'.( Threaded Code Interpreter in Perl, version )',
" version s>d <# # # '. hold #s #> type",
" '. emit here . cr space",
);
# -------- virtual machine data --------
# VM memory
my @m; # main memory
my @s; # user stack
my @r; # return stack
# global VM registers
my $sp; # user stack pointer
my $rp; # return stack pointer
my $w; # word pointer
my $ip; # instruction pointer
# global interpreter/compiler variables
my $dp = 0; # pointer to free VM mem
my $wc = 0; # word count, analog the name field address
my @header; # word headers
my @body; # pointers to word code fields
my @voclink; # pointer to index of next word of same vocabulary
my @precedence; # reveal/precedence flags per word
my $parsebuf; # pointer to current source buffer
my $parsebuflen; # size of current source buffer
my @sourcestack; # holds nested source buffer
my %does; # helper hash for create .. does> simplification
my $catchframe = 0; # pointer to prev catch/throw context (or 0)
my $maxu = (-1|0); # determine cell size in bits
$maxu = $cell if ($cell); # or use override
my $wrap = $maxu+1; # modulo for trimming results to fit into cell
my $msb = 1; # value with only the most significant bit set
my $bits = 1;
for (;$msb<$wrap/2;$msb+=$msb) {$bits++}
#print "$msb, $bits";
my $revealbit = 1;
my $precedencebit = 2;
# variables residing in interpreter virtual memory space.
sub comma {
$m[$dp] = shift(@_);
return $dp++;
}
my @vocstack;
my $xlaststore = comma 0;
my $xcurrentstore = comma 0;
my $xcontextstore = comma 0;
# -------- virtual machine --------
#$meow = $model ? sub { 'purr' } : sub { q/=^_^=/ }; $meow->();
sub nest { $r[++$rp] = $ip; $ip = $w+1; }
sub unnest { $ip = $r[$rp--]; }
my $unnest = $dp;
$m[$dp++] = \&unnest;
sub doconst { $s[++$sp] = $m[$w+1]; }
sub dovar { $s[++$sp] = $w+1; }
sub dodefer { $w = $m[$w+1]; $m[$w](); }
sub dovoc { $m[$xcontextstore] = $w; }
# -------- vocabularies --------
sub reveal { $precedence[$wc-1] |= $revealbit; }
sub immediate { $precedence[$wc-1] |= $precedencebit; }
sub hide { $precedence[$wc-1] &= ~$revealbit; }
sub header {
$header[$wc] = shift(@_);
$body[$wc] = $dp;
$precedence[$wc] = 0;
$voclink[$wc] = $m[$m[$xcurrentstore]+2];
$m[$xlaststore] = $dp;
$m[$m[$xcurrentstore]+1] = $dp;
$m[$m[$xcurrentstore]+2] = $wc;
$wc++;
return $dp;
}
sub xlink {
my $anchor = (shift(@_))+1;
($m[$anchor], $m[$dp]) = ($dp, $m[$anchor]);
$dp++;
}
sub allot { $dp += shift(@_); }
my $xvocabularies = comma \&dovar; comma 0; # a hand-built variable, needed early.(for linking
# vocabularies needed to contain the link anchors
# of variables, constant, vocabularies...)
sub vocabulary {
xlink $xvocabularies;
my $addr = comma \&dovoc; comma 0; comma 0; # last cfa, last wc.
return $addr;
}
my $xonlyvoc = vocabulary; sub only { $m[$xcontextstore] = $xonlyvoc; }
my $xforth = vocabulary; sub forth { $m[$xcontextstore] = $xforth; }
my $xhidden = vocabulary; sub hidden { $m[$xcontextstore] = $xhidden; }
sub definitions { $m[$xcurrentstore] = $m[$xcontextstore] }
hidden; definitions;
header ""; # must be header 0 (0 represents end
# of chain, common for all vocabularies)
# to do:
# hand-craft a link anchor, used as link anchor for list of link anchors here.
# link "vocabularies" link anchor to this link anchor. later, create a header,
# link "anchors" to itself. moala - mother of all link anchors.
header "vocabularies"; reveal; # header for vocabularies link anchor.
$body[$wc-1] = $xvocabularies;
only; definitions;
header "forth"; reveal;
$body[$wc-1] = $xforth;
forth; definitions;
header "only"; reveal;
$body[$wc-1] = $xonlyvoc;
header "hidden"; reveal;
$body[$wc-1] = $xhidden;
# -------- macros: defining words -------- #FOLD00
sub compile {
my $addr = $dp;
foreach my $i (0..$#_) {
comma $_[$i];
}
return $addr;
}
sub colon {
header shift(@_);
return compile \&nest;
}
sub semicolon {
compile $unnest;
reveal;
}
sub unnamedprimitive {
return compile shift(@_);
}
sub primitive {
header shift(@_);
reveal;
return compile shift(@_);
}
sub create {
header shift(@_);
reveal;
return compile \&dovar;
}
sub xnop { }
my $xnop = primitive "nop", \&xnop;
hidden; definitions;
my $xconstants = create "constants"; comma 0;
sub constant {
xlink $xconstants;
header shift(@_);
reveal;
return compile \&doconst, shift(@_);
}
my $xvariables = create "variables"; comma 0;
sub variable {
xlink $xvariables;
header shift(@_);
reveal;
return compile \&dovar, shift(@_);
}
sub alias {
my $cfa = $body[$wc-1];
header shift(@_);
reveal;
$body[$wc-1] = $cfa;
return $cfa;
}
my $xdefers = create "defers"; comma 0;
sub defer {
xlink $xdefers;
header shift(@_);
reveal;
return compile \&dodefer, shift(@_);
}
# ( a n -- ) packs chars at $m[$a..$a+n-1] into string which is returned.
sub string {
my $x2 = $s[$sp--]&$cell;
my $x1 = $s[$sp--]&$cell;
return pack "W*",@m[$x1..$x1+$x2-1];
}
# ( a -- n ) unpacks chars of string par to $m[$a..]
sub unstring {
my @arg = unpack "W*", $_[0];
$w = @arg;
(my $addr, $s[$sp]) = ($s[$sp], $w);
@m[$addr..$addr+$w-1] = @arg;
}
# -------- vocabularies search order -------- #FOLD00
only; definitions;
sub xalso { push @vocstack, $m[$xcontextstore]; }
primitive "also", \&xalso;
forth; definitions;
my $xlast = constant "last", $xlaststore;
constant "context", $xcontextstore;
constant "current", $xcurrentstore;
sub xprevious {
$m[$xcontextstore] = pop @vocstack if ($#vocstack >= 0);
}
primitive "previous", \&xprevious;
sub xonly {
$m[$xcontextstore] = $xonlyvoc;
@vocstack = $xonlyvoc;
}
my $xonly = primitive "only", \&xonly;
sub xdefinitions { $m[$xcurrentstore] = $m[$xcontextstore]; }
primitive "definitions", \&xdefinitions;
# -------- error handling -------- #FOLD00
my %throwmessage = (
-1 => "aborted",
-2 => "aborted",
-3 => "stack overflow",
-4 => "stack underflow",
-5 => "return stack overflow",
-6 => "return stack underflow",
# -7 => "do loops nested too deeply",
# -8 => "dictionary overflow",
-9 => "invalid memory address",
-10 => "division by zero",
-11 => "result out of range",
-12 => "argument type mismatch",
-13 => "word not found",
-14 => "use only during compilation",
-15 => "invalid forget",
-16 => "attempt to use zero-length string as name",
-17 => "pictured numeric output string overflow",
-18 => "parsed string overflow",
# -19 => "word name too long",
-20 => "write to a read-only location",
-21 => "unsupported operation",
-22 => "unstructured",
# -23 => "address alignment exception",
-24 => "invalid numeric argument",
-25 => "return stack imbalance",
-26 => "loop parameters unavailable",
-27 => "invalid recursion",
-28 => "user interrupt",
-29 => "compiler nesting",
-30 => "obsolescent feature",
-31 => ">BODY used on non-CREATEd definition",
-32 => "invalid name argument",
-33 => "Block read exception",
-34 => "Block write exception",
-35 => "Invalid block number",
-36 => "Invalid file position",
-37 => "File I/O exception",
-38 => "File not found",
# additional error messages:
-64 => "use only while interpreting",
-65 => "executed BODY> on a non-body address",
-67 => "TO must be used on a VALUE",
-72 => "Invalid memory region specifier, or heap corrupted",
);
# used by abort" to introduce new abort messages
sub xnewerror { # ( n1 a n2 -- )
$throwmessage{$s[$sp--]} = string;
}
primitive "newerror", \&xnewerror;
# executed at the end of word executed by catch.
sub xbrthrow0 {
($ip, $sp, $catchframe) = @r[$rp-2..$rp]; # restore previous catch context
$rp -= 3;
$s[$sp] = 0; # throw value 0
}
my $xbrthrow0 = compile unnamedprimitive \&xbrthrow0; # not a primitive - returning to.
sub xexecute { $w = $s[$sp--]; $m[$w](); }
my $xexecute = primitive "execute", \&xexecute;
# ( a -- x )
sub xcatch {
$rp += 3; # room for new catch frame
@r[$rp-2..$rp] = ($ip, $sp, $catchframe); # save previous catch context
$catchframe = $rp; # point to this catch frame
$r[++$rp] = $xbrthrow0; # inject return address to throw0
xexecute; # call word running under catch
}
my $xcatch = primitive "catch", \&xcatch;
# ( err -- )
sub throw {
my $exception = shift; # throw value other than 0?
if ($exception) {
if ($catchframe) { # does previous catch frame exist?
$rp = $catchframe; # yes: point to prev catch frame
($ip, $sp, $catchframe) = @r[$rp-2..$rp]; # restore previous catch context
$rp -= 3;
$s[$sp] = $exception; # return throw value
} else { # throw without catch: top level
die $exception;
}
}
}
sub xthrow { throw $s[$sp--]; }
my $xthrow = primitive "throw", \&xthrow;
hidden; definitions;
sub xbrerror { throw -1; }
sub xstackunderflow { throw -4; }
sub xbrnotfound { throw -13; }
my $xbrerror = primitive "(error)", \&xbrerror;
my $xstackunderflow = unnamedprimitive \&xstackunderflow;
my $xbrnotfound = primitive "(notfound)", \&xbrnotfound;
my $xnotfound = defer "notfound", $xbrnotfound;
my $xlastword = create "lastword"; allot 2;
forth; definitions;
my $xerror = defer "error", $xbrerror;
# -------- run time words: literals and flow control --------
hidden; definitions;
sub xlit { $s[++$sp] = $m[$ip++]; }
my $xlit = primitive "(lit)", \&xlit;
sub xslit {
my $count = $m[$ip++];
$sp += 2;
@s[$sp-1..$sp] = ($ip, $count);
$ip += $count;
}
my $xslit = primitive '(slit)', \&xslit;
sub xbrdotquote { xslit; print string; }
my $xbrdotquote = primitive '(.")', \&xbrdotquote;
sub xbranch { $ip += $m[$ip]; }
my $xbranch = primitive "(branch)", \&xbranch;
sub xbranch0 {
if ($s[$sp--]) {
$ip++;
} else {
$ip += $m[$ip];
}
}
my $xbranch0 = primitive "(0branch)", \&xbranch0;
sub xbrfor {
$r[++$rp] = $s[$sp]-1;
$r[++$rp] = $s[$sp--]-1;
$ip++;
}
my $xbrfor = primitive "(for)", \&xbrfor;
sub xbrnext {
if ($r[$rp]--) {
$ip += $m[$ip];
} else {
$rp -= 2;
$ip++;
}
}
my $xbrnext = primitive "(next)", \&xbrnext;
sub xbrdo {
$rp += 2;
@r[$rp-1..$rp] = @s[$sp-1..$sp];
$sp -= 2;
$ip++;
}
my $xbrdo = primitive "(do)", \&xbrdo;
sub xbrqdo {
if ($s[$sp] == $s[$sp-1]) {
$ip += $m[$ip];
} else {
$rp += 2;
@r[$rp-1..$rp] = @s[$sp-1..$sp];
$ip++ ;
}
$sp -= 2;
}
my $xbrqdo = primitive "(?do)", \&xbrqdo;
sub xbrleave {
$rp -= 2;
$ip = $m[$ip];
$ip += $m[$ip];
}
my $xbrleave = primitive "(leave)", \&xbrleave;
sub xbrqleave {
if ($s[$sp--]) {
xbrleave;
} else {
$ip++;
}
}
my $xbrqleave = primitive "(?leave)", \&xbrqleave;
sub xbrloop {
if (++$r[$rp] != $r[$rp-1]) { # index+1 != limit
$ip += $m[$ip]; # add branch offset to instruction pointer
} else {
$rp -= 2; # discard loop parameters
$ip++; # skip branch offset
}
}
my $xbrloop = primitive "(loop)", \&xbrloop;
sub xbrplusloop { # determine loop exit condition by simulating sign overflow:
$w = $r[$rp] - $r[$rp-1]; # temp = index-limit
$r[$rp] += $s[$sp--]; # index += loop increment
if ((($r[$rp] - $r[$rp-1]) ^ $w) < $msb) { # sign change of index-limit before and after?
$ip += $m[$ip]; # no: add branch offset to instruction pointer
} else {
$rp -= 2; # yes: exit loop: discard loop parameters
$ip++; # skip branch offset
}
}
my $xbrplusloop = primitive "(+loop)", \&xbrplusloop;
sub xbrunloop { $rp -= 2; }
my $xbrunloop = primitive "(unloop)", \&xbrunloop;
sub doarray {
if (($s[$sp] < $m[$w+1]) && ($s[$sp] >= -1)) { # legal index. -1 addresses array size
$s[$sp] += ($w+2); # index > address
} else {
throw -24;
}
}
my $xarrays = create "arrays"; comma 0;
sub array {
xlink $xarrays;
header shift(@_);
reveal;
my $cfa = compile \&doarray;
my $count = shift(@_);
comma $count;
allot $count;
return $cfa;
}
forth; definitions;
# -------- constants, variables -------- #FOLD00
my $xesc = constant "esc", 27;
my $xbl = constant "bl", 32;
my $xfalse = constant "false", 0;
my $xzero = alias "0";
my $xtrue = constant "true", -1;
my $xminusone = alias "-1";
constant "msb", $msb;
constant "maxu", $maxu;
my $xstate = variable "state", 0;
my $xbase = variable "base", 10;
my $xhashtib = variable "#tib", 0;
my $xtoin = variable ">in", 0;
my $xinnerloop = variable "innerloop", 0;
my $xtib = create "tib"; allot $tibsize;
constant "version", int $version;
constant "tibsize", $tibsize;
my $xkeytable = array "keytable", 32;
# -------- stack handling --------
sub xdrop { $sp--; }
sub xrdrop { $rp--; }
sub x2drop { $sp -= 2; }
sub xsp { $s[++$sp] = $sp; }
sub xrp { $s[++$sp] = $rp; }
sub xdup { $s[++$sp] = $s[$sp]; }
sub xqdup { $s[++$sp] = $s[$sp] if ( $s[$sp]); }
sub xover { $s[++$sp] = $s[$sp-1]; }
sub xnip { $s[$sp] = $s[$sp--]; }
sub xpick { $s[$sp] = $s[$sp-$s[$sp]-1]; }
sub xdepth { $s[++$sp] = $sp; }
sub xswap { @s[$sp-1..$sp] = ($s[$sp], $s[$sp-1]); }
sub xrot { @s[$sp-2, $sp-1, $sp] = @s[$sp-1, $sp, $sp-2]; }
sub x2dup { $sp += 2; @s[$sp-1..$sp] = @s[$sp-3..$sp-2]; }
sub x2over { $sp += 2; @s[$sp-1..$sp] = @s[$sp-5..$sp-4]; }
sub x2swap { @s[$sp-3..$sp] = (@s[$sp-1..$sp], @s[$sp-3..$sp-2]);}
sub xtor { $r[++$rp] = $s[$sp--]; }
sub xrfrom { $s[++$sp] = $r[$rp--]; }
sub xrfetch { $s[++$sp] = $r[$rp]; }
sub x2tor { $r[++$rp] = $s[$sp--];
$r[++$rp] = $s[$sp--]; }
sub x2rfrom { $s[++$sp] = $r[$rp--];
$s[++$sp] = $r[$rp--]; }
sub x2rfetch { $s[++$sp] = $r[$rp];
$s[++$sp] = $r[$rp-1]; }
my $xdup = primitive "dup", \&xdup;
my $xqdup = primitive "?dup", \&xqdup;
my $xdrop = primitive "drop", \&xdrop;
my $xover = primitive "over", \&xover;
my $xswap = primitive "swap", \&xswap;
my $xrot = primitive "rot", \&xrot;
my $xnip = primitive "nip", \&xnip;
my $x2dup = primitive "2dup", \&x2dup;
my $x2drop = primitive "2drop", \&x2drop;
my $x2swap = primitive "2swap", \&x2swap;
my $x2over = primitive "2over", \&x2over;
my $xpick = primitive "pick", \&xpick;
my $xdepth = primitive "depth", \&xdepth;
my $xtor = primitive ">r", \&xtor;
my $xrfrom = primitive "r>", \&xrfrom;
my $xrfetch = primitive "r@", \&xrfetch;
my $xrdrop = primitive "rdrop", \&xrdrop;
my $x2tor = primitive "2>r", \&x2tor;
my $x2rfrom = primitive "2r>", \&x2rfrom;
my $x2rfetch = primitive "2r@", \&x2rfetch;
primitive "rp", \&xrp;
primitive "sp", \&xsp;
# -------- flow control -------- #FOLD00
my $xexit = primitive "exit", \&unnest;
sub xi { $s[++$sp] = $r[$rp]; }
my $xi = primitive "i", \ξ
sub xj { $s[++$sp] = $r[$rp-2]; }
my $xj = primitive "j", \&xj;
sub xuse { $m[$body[$wc-1]] = $s[$sp--]; }
my $xuse = primitive "use", \&xuse;
sub xunless { $ip = $r[$rp--] if ($s[$sp--]) }
my $xunless = primitive "unless", \&xunless;
sub xbye { print "\n"; exit; }
my $xbye = primitive "bye", \&xbye;
sub XIF {
comma $xbranch0;
$s[++$sp] = $dp++;
}
sub XELSE {
comma $xbranch;
my $offs = $s[$sp];
$s[$sp] = $dp++;
$m[$offs] = $dp-$offs;
}
sub XTHEN {
$m[$s[$sp]] = $dp-$s[$sp];
$sp--;
}