-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathbashforth
executable file
·3801 lines (2729 loc) · 83.4 KB
/
bashforth
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
#!/bin/bash
set -u
# set -x
# required bash 2.04 or more recent, but probably depends on bash 3.x now, since v0.54
version="0.63a"
# bashforth - forth interpreter in bash
# v0.03 20030219 ls added bool, logical, constants, fixed nip and other
# v0.04 20030219 ls added ?dup, fixed 0branch
# v0.05 20030220 ls reviewed auto-inc/dec addressing modi, fixed 0branch again
# v0.06 20030220 ls constants redone
# v0.07 20030220 ls added lshift rshift
# v0.08 20030220 ls emit outputs correctly decimal numbers on stack. thanks dufflebunk
# v0.09 20030220 ls simplified asc table building.
# v0.10 20030220 ls accept works. uses external command cut right now.
# v0.11 20030220 ls added pad c@ @ c! ! count
# v0.12 20030221 ls key and accept return asciis, rather than chars.
# emit, type, find work on asciis
# v0.13 20030221 ls word, input stream parser, query, interpret, quit added
# this enables multiple words on input line
# v0.14 20030221 ls ?number added, extended interpreter. numbers work, but
# only decimal
# v0.15 20030221 ls added deferred words, improved error handler. first
# defining words. creation of variables works.
# v0.16 20030221 ls immediate, colon definitions work
# v0.17 20030222 ls improved prompt, added ' and ['], compiles numbers
# find returns the word#, can get to xt, name and header flags.
# added 2*, 2/, negate, begin..again begin..until
# v0.18 20030222 ls if..then, if..else..then begin..while..repeat work. structure is tested
# v0.19 20030222 ls do..loop, i, j, negative numbers input, commented out debug output
# from virtual machine for 50% speed improvement
# v0.20 20030223 ls added does> 2+
# v0.21 20030223 ls hide, reveal, constant. started redoing error handler. loops broken
# v0.22 20030223 ls loops fixed. ?comp
# v0.23 20030223 ls added catch throw ?exec . fixed key (space). ctrl chars return asc of space too.
# v0.24 20030224 ls added ." , s" , $, .( fixed bug in word . tests stack underflow
# v0.26 20030225 ls added s( \ (
# v0.27 20030225 ls errorhandler through throw. top level error handler catches gracefully
# v0.28 20030225 ls speed increase of about 50 %
# v0.29 20030225 ls exit, outputs asciis 0...31, speeded up compares, improved move
# v0.30 20030225 ls .. outputs decimal (quick), . respects base (slower), number input respects base
# added hex, decimal, binary
# v0.31 20030226 ls pictured number output added ( <# # #s #> #>type sign )
# v0.31a20030226 ls hold (forgotten, pictured number output), rot, -rot
# v0.32 20030226 ls system (shells to command), pack ( a n -- x ) packs string to string on tos,
# unpack (explodes tos string to memory), cleaned up messy accept and name
# v0.33 20030226 ls added bash, fixed does>, started include. sent out for does> fix
# v0.34 20030226 ls first rough version of include works. no nesting yet. thanks deltab for getting the source into vars
# v0.35 20030226 ls fixed backslash bug in include.
# this is for the time being the last version of bashforth. i'm now busy working on a target translator which allows to generate source
# for several languages, including bash
# v0.36 20030305 ls added pick, found a way to split input stream into chars w/o requiring external cut, as a result
# including source files works much quicker. bashforth is "pure" now.
# v0.37 20030309 ls number output with . doesn't complain about zero-string stack elements.
# stack order reversed. added */ */mod ?do leave . speeded up type
# v0.37a20030310 ls fixed include, broken in 0.37 because of changed do
# v0.37b20030310 ls fixed include again. * in source was expanded to file list
# v0.37c20030310 ls fixed ." which had cr appended
# v0.38 20030310 ls added skip, scan, tuck, compare
# v0.39 20030310 ls added min max abs fill doc, abort throws, removed ?exec
# v0.40 20030311 ls bugfix for 2.05a, hopefully for 2.04 too. incompatible with 2.03
# v0.41 20030311 ls redone doc. this implementation writes line number to word body. added rnd +! cell cells chars
# v0.42 20030311 ls more consistent use of addressing modes, added
# date&time.fixed negative number big introduced with .40
# v0.42a20030313 ls changed email address. verified function on bash 2.04. thanks, stepan
# v0.42b20030315 ls fixed sign bug, result of v0.40, added >name
# v0.43 20030316 ls added .name, roll, improved locate and >name, last points now to cfa of last word
# v0.44 20030316 ls added cell+ char +loop ?leave **
# v0.45 20030316 ls added 2>r 2r>, cleaned up code, speeded up some words (type, #, words)
# v0.46 20030316 ls added literal, compiling, addressing modes optimizations
# v0.46a20030316 ls bugfix addressing modes v0.46. untested with bash 2.04
# v0.47 20030319 ls added black yellow green red blue magenta cyan white fg bg colors
# v0.47a20030320 ls added normal bold underscore reverse attr@ attr!
# v0.47b20030320 ls added at home
# v0.47c20030325 ls added ?at (doesn't work yet) number /string right$ left$
# v0.48 20030325 ls added system2 2swap dup$ drop$ depth$ 2dup$ swap$ over$ nip$ rot$ push$ pop$ append$
# modified left$ right$, these work on stop string stack element now
# modified doc to show word description, besides stack effect. optimized does>
# v0.48a20030325 ls added/modified descriptions
# v0.48b20030526 ls replaced hide/reveal against versions by h-peter recktenwald. these ones seem
# to be less sensitive for the used version of bash
# v0.48c20030527 ls bug fix "hold", bug discovered by h-peter recktenwald
# v0.48d20030530 ls merged with h-peter recktenwald's patches: info, hold, immediate
# hi-level . is about 50 % slower than former primitive version
# (output 1000 number 7.5 rather than 4.7 seconds now)
# v0.48e20030808 ls attempted fix of ?number, number and * for bash v2.04 on BEOS
# v0.49 20030809 ls fixed time&date, broken after 2.04 fix in 0.48e
# v0.49a20030809 ls fixed loop +loop for 2.04
# v0.49b20030818 ls found a better fix for time&date
# v0.49c20031019 ls fixed : foo ." *" ; bug which displayed current directory
# v0.49d20031019 ls added for .. next, compatible with i j , added spaces.
# made count tolerant for non-initialized memory locations
# v0.49e20031019 ls attempt to include nonexisting file throws -38
# 0.50 20031028 ls added see (does not decompile, shows script source instead)
# 0.50a 20040101 ls fixed : $structured, not structured in until
# 0.50b 20040928 ls optional doc <word> uses sed rather than tail - recently tail args were changed.
# 0.51 20041004 ls added 2@ and 2!, suggested by Antonio Maschio
# 0.52 20041116 ls slow (1sec) version of key?, added secs and epoche
# 0.52a 20041123 ls can emit ascii <32 correctly
# 0.53 20041217 ls ***STACK EFFECT OF 'WORD' HAS CHANGED*** previously ( c -- a n ), it is now ( c -- cstring ), with string at HERE
# previous a was pointing into input stream. STREAM was added, providing function of former WORD. new WORD uses STREAM.
# added :noname . bugfix compare .
# 0.53a 20041220 ls trapped Ctrl-C: warm start
# 0.53b 20041220 ls added >body body>
# 0.53c 20041222 ls include appends .bashforth extension and retries if file not found
# 0.54 20050119 ls fixed bug in move
# 0.54a 20050222 ls added ?
# 0.54b 20050331 ls div/0 exception
# 0.55 20060314 ls unhandled exceptions quit, not warmstart, leaving radix untouched
# 0.55a 20061003 lsls removed unnecessary cat in see
# 0.55b 20071220 ls reversed logic in key?
# changed comparison against empty string to -z test in exception and 2 other
# speeded up by using [[ or (( instead of [
# simplified logic here and there
# 0.55c20071223 ls exception accepts literal
# 0.56 20071229 ls line numbers (for doc and see) dont't require info #LINENO per word anymore
# changed all function foo { } to foo() { }
# passed command line is executed
# string stack underflow detected
# string stack emptied on warm and cold
# fixed bug in include
# string stack operators testing for underflow
# first mac debian package
# 0.56a 20071231 ls fix in key (returns ascii for space now)
# added nanoseconds, time (measures execution time)
# made distance between HERE and PAD a config variable: PADAWAY
# tib size configurable too
# simplified some logic
# changed find to resemble a bit more the standard
# using new find in interpreter loop
# using printf instead of echo
# misc small speedups (or rather, removed a few slowdowns)
# 0.56b intermediate testing speed improvements
# 0.56c 20080114 ls added control characters in output ascii table
# using (( cond )) && action where appropriate
# changing spacing to accommodate fte syntax highlighting better
# some more arithmetic optimisations
# 0.57 20091005 ls key?, needs bash 4, waits 1ms. single char buffer,
# read by key?, used by key and accept.
# 0.57a 20101022 ls fixed bug in (s") which must have slipped into with
# a recent version
# slight optimisation of abs
# 0.57b 20101101 ls added env, removed "upload" handling, which went into a source file by the same name.
# renamed "timestamp" to "epoche"
# renamed "merge$" to "append$"
# attempts to source ~/.bashforthrc, use to set variables:
# sources=/path/to/sourcefiles # "include" reads source files from that dir,
# # and defaults to current directory if unset.
# added "type$"
# 0.57c 20101112 ls simplified exception, and some style improvements sprinkled all over the code
# user interrupt (ctrl-c) improved
# 0.57d 20101127 ls removed load and loadfrom. reversed logic on -z string tests.
# removed -n from string tests.
# 0.58 20101220 ls replaced right$. simpler, shorter, faster
# changed result generation of key?
# bug fix number - may have another, dropping sign with hex -ff
# 0.58a 20110819 ls fixed bug with multiple consecutive revealheader
# 0.58b 20120312 ls multi line compound arithmetic expressions problem with bash 4.2-1 at hash
# 0.58c 20170609 ls A syntax error affecting bash v4.4 was fixed.
# ASCII to char translation array initialised with char(1) now.
# 0.59 20190806 ls uses $EPOCHSECONDS instead of $(date +%s) for epoche when running under bash 5+
# 0.59a 20190821 ls some more quoting, removed saving IFS contents in key and key?
# changed !(( to ! (( to pacify shellcheck.
# 0.60 20190830 ls added restore, restore-from, save-system, saveas, contributed by quaraman-me
# type$ didn't drop top string stack element. Fixed
# changed output of .s$ to vertical. top of string stack is uppermost output line.
# Fixed error in type when outputting % char.
# 0.60a 20190830 ls .s$ autodecrements
# 0.60b 20190830 ls added nlimit, producing highest signed number.
# fixed rshift: making it logical right shift while bash does arithmetic right shift.
# partially (attempted to fix) sign problem in #
# 0.60c 20190830 ls see prevented from mangling output lines.
# 0.60d 20190830 ls fixed expanding * in restore.
# 0.60e 20190830 ls fixed: number input accepting some non numeric chars. A side effect is that digits > 10 are now case insensitive.
# added: 2swap d= sub$
# changed: left$ and right$ call sub$, ?number uses (fixed) number
# 0.60f 20190831 ls fixed: wrong number output when outputting a number with only msb set (nlimit+1)
# changed (already in a previous version): executing save-system and restore without file name write to/read from $sources directory
# 0.61 20190831 ls functionally reverted to 0.60f, undoing changes to floored modulo and division, causing more damage than benefits
# 0.61a 20190831 ls fixed: (s") bug from 0.57a again, seems to have reinstroduced when reverting.
# 0.62 20190909 ls added: !sourcepath complements sourcepath
# changed: set working variables in compare to local
# 0.63 20190909 ls changed: words attempts to break lines
# 0.63a 20201121 ls fixed: exposed one superfluous "epoche" header
#
# known bugs:
# catch: doesn't return the thrown value correctly sometimes
# include: max line length in source files isn't checked against TIBSIZE
# env: without name abort with "invalid variable name"
# see: doesn't look into included source files
# /: while modulo and divison of /mod and */mod are floored, / isn't.
# global variables:
# ip virtual machine instruction pointer
# w virtual machine word pointer.
# sp data stack pointer
# rp return stack pointer
# wc word count, number of headers. used as name field address
# temp scratch. never used to carry data across words/functions
# tos top of stack, stack cache
# dp dictionary pointer, "here". new words are added at this address
# state compile/interpret switch
# catchframe pointer to latest frame
# ssp string stack pointer
# global variable arrays:
# m memory
# s data stack
# r return stack
# h headers (word names)
# hf header flags (precedence bit, smudge bit)
# x execution tokens
# asc characters array, indexed by decimal ascii
# ss string stack
################################# example primitive #####################################
# # ( -- ) description # stack diagram, description
# revealheader "foo" # name in forth vocabulary
# code foo foo # name in bash, call of executable
# --------- executable may follow, but may also be seperated ----------
# foo() { # executable implementated as function
# s[++sp]=$tos # stack push
# tos=${s[sp--]} # stack pop
# } # empty lines follows
#
#########################################################################################
################################# example hi-level word #####################################
# # ( -- ) description # stack diagram, description
# revealheader "foo" # name in forth vocabulary
# colon foo \ # name in bash. line continuation
# $word $word $word \ # compiled words, line continuation
# $word $word # last line does not need continuation, empty line follows
#
#########################################################################################
#
#
#
# -------------------------------------------------------------------------
# --- configuration ---
# -------------------------------------------------------------------------
PADAWAY=256 # distance between HERE and PAD
TIBSIZE=256
PROMPT="ok"
LOADING=""
EDITOR=sensible-editor
# -------------------------------------------------------------------------
# --- allocate memory / initialize vars ---
# -------------------------------------------------------------------------
m=() # memory
s=() # data stack
r=() # return stack
h=() # headers, wordcount
hf=() # header flags, corresponding to headers
x=() # execution tokens, corresponding to headers
ss=() # string stack
declare -i ip w # instruction and word pointer of virtual machine
declare -i s0=0 sp # data stack origin and pointer
declare -i r0=0 rp # return stack origin and pointer
declare -i ss0=0 ssp # string stack origin and pointer
declare -i dp=0 # dictionary pointer
declare -i wc=0 # word count
declare -i state=0 # compiler/interpreter switch
declare -i catchframe=0 # pointer to latest catch frame, or 0
sources="." # unless overwritten from .bashforthrc or !sourcepath
# ---- bitmasks ------------------------------------------------------------
# declared as read-only, integer
declare -ri precedencebit=1 # immediate words
declare -ri smudgebit=2 # hide/reveal headers
# --------------- build decimal>ascii lookup table for emit ----------------
asc=()
for i in {1..255}; do
asc[i]=$(echo -en "\\x$(printf '%x' $i)") # ascii 0-255
done
# ------------------------------- "macros" ---------------------------------
# --- array of variables and functions which will be removed after the script has been loaded ---
# --- only to use with words which help building bashforth, but aren't required at runtime ---
remove=()
transient() {
remove[${#remove[@]}]=$1
}
transient remove # remove must either be non-transient, or the first transient.
transient transient
transient compile
compile() {
for nextword in $*
do
m[dp++]="${nextword}"
done
}
transient code
code() {
(( $1 = dp ))
shift
m[dp++]="$*"
}
dovar() {
s[++sp]="$tos"
tos="$w"
}
transient var
var() {
(( $1 = dp ))
compile dovar 0
}
var lastxt
header() {
m[lastxt+1]=$dp
x[wc]=$dp
hf[wc]=0
h[wc++]="$1" # word name
}
reveal() {
((hf[wc-1] |= smudgebit))
}
hide() {
((hf[wc-1] &= ~smudgebit))
}
transient revealheader
revealheader() {
((m[dp++]=BASH_LINENO[0]-1)) # source line number - consider to put file/line into an array with source locations
header "$1"
reveal
}
transient semicolon
semicolon() {
compile "$unnest"
reveal
}
transient colon
colon() {
(( $1 = dp ))
shift 1
compile nest
compile "$*"
semicolon
}
doconst() {
s[++sp]=$tos
tos=${m[w]}
}
transient constant
constant() {
(( $1 = dp ))
shift
compile doconst "$1"
}
dodefer() { ip=$w; }
transient defer
defer() {
(( $1 = dp ))
compile dodefer 0
}
# -----------------------------------------------------------------------------
# -------------------------------- system start -------------------------------
# -----------------------------------------------------------------------------
revealheader ""
# warm start vector
# ( ??? -- ) init stacks and vars, restart interpreter
revealheader "warm"
defer warm
# -------------------------------------------------------------------------
# --- ctrl-c: user interrupt ---
# -------------------------------------------------------------------------
#trap "echo bashforth finished" EXIT
#trap "echo err" ERR
#trap "echo return" RETURN
ctrl-c() {
tos=-28
ip=$warm
printf '%s\n' " ${throw[-tos]}"
return 0
}
trap ctrl-c 2
# -----------------------------------------------------------------------------
# ------------------------------ virtual machine ------------------------------
# -----------------------------------------------------------------------------
nest() {
r[++rp]=$ip
ip=$w
}
# ( -- ) exits the current definition. compiled by ;
revealheader "exit"
code unnest unnest
unnest() {
ip=${r[rp--]}
}
# ----------------------------------------------------------------------------
# --------------------------- constants, variables ---------------------------
# ----------------------------------------------------------------------------
msb=1; until ((msb<0)); do ((msb<<=1)); done
# ( -- -1 )
revealheader "true"
constant minone -1
# ( -- -1 )
revealheader "-1"
constant minone -1
# ( -- 0 )
revealheader "false"
constant zero 0
# ( -- 0 )
revealheader "0"
constant zero 0
# ( -- 1 )
revealheader "cell"
constant one 1
# ( -- 1 )
revealheader "1"
constant one 1
# ( -- 2 )
revealheader "2"
constant two 2
# ( -- 3 )
revealheader "3"
constant three 3
# ( -- 4 )
revealheader "4"
constant four 4
# ( -- 5 )
revealheader "5"
constant five 5
# ( -- 6 )
revealheader "6"
constant six 6
# ( -- 27 ) ASCII of Escape char
revealheader "esc"
constant esc 27
# ( -- 32 ) ASCII of space char
revealheader "bl"
constant bl 32
# ( -- x ) highest signed number
revealheader "nlimit"
constant nlimit $((msb-1))
# ( -- a )
revealheader ">in"
var in
# ( -- a ) flags/switches interpret/compile mode
revealheader "state"
var state
# ( -- a ) variable, pointing to cfa of last word
revealheader "last"
constant last $((lastxt+1))
# ( -- a ) a memory area, relative to here, for user purposes
revealheader "tib"
var tib
((dp+=TIBSIZE))
# ( -- a ) variable containing the input and output radix
revealheader "base"
var base
# ----------------------------------------------------------------------------
# ------------------------------- run time -----------------------------------
# ----------------------------------------------------------------------------
# ( -- ) run time word - to be compiled by another word
revealheader "branch"
code branch branch
branch() { ((ip+=m[ip])); }
# ( f -- ) run time word - to be compiled by another word
revealheader "0branch"
code branch0 branch0
branch0() {
if ((tos)); then
((ip++))
else
((ip+=m[ip]))
fi
tos=${s[sp--]}
}
# ( f -- ) run time word - compiled internally instead of 0= branch0
code branchx branchx
branchx() {
if ((tos)); then
((ip+=m[ip]))
else
((ip++))
fi
tos=${s[sp--]}
}
# ( -- x ) when compiled into a word, the contents of the cell under $ip are pushed to stack and skipped from execution
revealheader "lit"
code lit lit
lit() {
s[++sp]=$tos
tos=${m[ip++]}
}
# ( a n -- x ) assembles asciis at m[a] to string in tos
revealheader "pack"
code pack pack
pack() {
i=$tos
temp=${s[sp--]}
unset tos
while ((i--)); do
tos+="${asc[m[temp++]]}"
done
}
#pack() {
# temp="${s[sp--]}"
# temp2=$tos
# tos="$(printf '\x0' $(printf '%x' "${m[@]:temp:temp2}"))"
# echo ">>> $tos <<<"
# printf '\x0%x ' "${m[@]:temp:temp2}"
#}
# ( x a -- n ) unpacks string x to ascii ordinals at a
revealheader "unpack"
code unpack unpack
unpack() {
local string=${s[sp--]}
len=${#string}
((dest=tos+len))
tos=$len
for ((; len; len-- )); do
m[--dest]=$(printf '%d' "'${string:len-1:1}")
done
}
# ( -- a c ) run time word - to be compiled by s"
revealheader '(s")'
code dosquote dosquote
dosquote() {
s[++sp]=$tos
tos=${m[ip++]}
s[++sp]=$ip
((ip+=tos))
}
# ( -- ) run time word - to be compiled by ."
revealheader '(.")'
code dodotquote dodotquote
dodotquote() {
dosquote
pack
printf '%s' "$tos"
tos=${s[sp--]}
}
# ( limit start -- ) run time word - to be compiled by for
revealheader "(for)"
code dofor dofor
dofor() {
r[++rp]=$tos
r[++rp]=$tos
tos=${s[sp--]}
((ip++))
}
# ( -- ) run time word - to be compiled by next
revealheader "(next)"
code donext donext
donext() {
((r[rp]--))
if ((r[rp])); then
((ip+=m[ip]))
else
((ip++, rp-=2))
fi
}
# ( limit start -- ) run time word - to be compiled by do
revealheader "(do)"
code dodo dodo
dodo() {
r[++rp]=${s[sp--]}
r[++rp]=$tos
((ip++))
tos=${s[sp--]}
}
# ( limit start -- ) run time word - to be compiled by ?do
revealheader "(?do)"
code doqdo doqdo
doqdo() {
if (( tos == s[sp] )); then
((sp--))
((ip+=m[ip]))
else
r[++rp]=${s[sp--]}
r[++rp]=$tos
((ip++))
fi
tos=${s[sp--]}
}
# ( -- ) run time word - to be compiled by leave
revealheader "(leave)"
code doleave doleave
doleave() {
((rp-=2))
ip=${m[ip]}
((ip+=m[ip]))
}
# ( -- ) run time word - to be compiled by ?leave
revealheader "(?leave)"
code doqleave doqleave
doqleave() {
if ((tos)); then
doleave
else
((ip++))
fi
tos=${s[sp--]}
}
# ( -- ) run time word - to be compiled by loop
revealheader "(loop)"
code doloop doloop
doloop() {
((r[rp]++))
if ((r[rp] - r[rp-1])); then
((ip += m[ip]))
else
((ip++, rp -= 2))
fi
}
# ( -- ) run time word - to be compiled by +loop
revealheader "(+loop)"
code doplusloop doplusloop
doplusloop() {
((temp = r[rp] - r[rp-1],
r[rp] += tos,
tos = s[sp--]))
if (( (temp ^ (r[rp] - r[rp-1])) > 0 )); then
((ip += m[ip]))
else
(( ip++, rp -= 2 ))
fi
}
# ( ? xt -- ? )
revealheader "execute"
code execute execute
execute() {
w=$tos
tos=${s[sp--]}
${m[w++]}
}
# -----------------------------------------------------------------------------
# ------------------------------ stack operators ------------------------------
# -----------------------------------------------------------------------------
# ( -- n ) returns number stack elements on data stack
revealheader "depth"
code depth depth
depth() {
s[++sp]=$tos
((tos=sp-s0-1))
}
# ( x -- x x ) duplicate top stack element
revealheader "dup"
code dup dup
dup() { s[++sp]=$tos; }
# ( x1 x2 -- x1 x2 x1 x2 ) duplicate top two stck elements
revealheader "2dup"
code dup2 dup2
dup2() {
s[++sp]=$tos
s[++sp]=${s[sp-1]}
}
# ( 0 -- 0 ) ( x -- x x ) duplicate top stack element only if it is not zero
revealheader "?dup"
code qdup qdup
qdup() {
((tos)) && s[++sp]=$tos
}
# ( x -- ) discard top stack element
revealheader "drop"
code drop drop
drop() {
tos=${s[sp--]}
}
# ( x1 x2 -- ) discard top two stack elements
revealheader "2drop"
code drop2 drop2
drop2() {
((sp--))
tos=${s[sp--]}
}
# ( x1 x2 -- x2 x1 ) swap the top two stack elements with each other
revealheader "swap"
code swap swap
swap() {
temp=$tos
tos=${s[sp]}
s[sp]=$temp
}
# ( x1 x2 x3 x4 -- x3 x4 x1 x2 ) swap top 2 stack items against 3rd and 4th of stack
revealheader "2swap"
code swap2 swap2
swap2() {
temp=${s[sp-1]}
s[sp-1]=$tos
tos=$temp
temp=${s[sp-2]}
s[sp-2]=${s[sp]}
s[sp]=$temp
}
# ( x1 x2 -- x1 x2 x1 ) push copy of second stack element to top
revealheader "over"
code over over
over() {
s[++sp]=$tos
tos=${s[sp-1]}
}
# ( x1 x2 x3 x4 -- x1 x2 x3 x4 x1 x2 ) copy 3rd and 4th stack item to stack top
revealheader "2over"
code over2 over2
over2() {
s[++sp]=$tos
tos=${s[sp-3]}
s[++sp]=$tos
tos=${s[sp-3]}
}
# ( x1 x2 -- x2 ) discard second stack element
revealheader "nip"
code nip nip
nip() {
((sp--))
}
# ( x1 x2 -- x2 x1 x2 ) insert a copy of top of stack under second stack element
revealheader "tuck"
code tuck tuck
tuck() {
temp=${s[sp]}
s[sp]=$tos
s[++sp]=$temp
}
# ( x1 x2 x3 -- x2 x3 x1 ) rotate third stack element to top
revealheader "rot"
code rot rot
rot() {
temp=${s[sp]}
s[sp]=$tos
tos=${s[sp-1]}
s[sp-1]=$temp
}
# ( x1 x2 x3 -- x3 x1 x2 ) rotate top stack element under second stack element
revealheader "-rot"
code minrot minrot
minrot() {
temp=${s[sp-1]}
s[sp-1]=$tos
tos=${s[sp]}
s[sp]=$temp
}
# ( ... x2 x1 x0 n -- xn ) place a copy of stack element n on top of stack
revealheader "pick"
code pick pick
pick() { tos=${s[sp-tos]}; }
# ( ... x2 x1 x0 n -- ... x2 x1 x0 xn ) rotate stack element n to top of stack
revealheader "roll"
code roll roll
roll() {
temp=${s[sp-tos]}
for ((; tos; --tos)); do
s[sp-tos]=${s[sp-tos+1]}
done
((sp--))
tos=$temp
}
# ( x -- ) moves top of data stack to return stack
revealheader ">r"