Repository navigation
Expand file tree
/
Copy pathueforth.js
More file actions
3743 lines (3471 loc) · 108 KB
/
Copy pathueforth.js
File metadata and controls
3743 lines (3471 loc) · 108 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 2021 Bradley D. Nelson
//
// 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.
'use strict';
(function() {
const HEAP_SIZE = (4 * 1024 * 1024);
const STACK_CELLS = 4096;
const VOCABULARY_DEPTH = 16;
const IMMEDIATE = 1;
const SMUDGE = 2;
const BUILTIN_FORK = 4;
const BUILTIN_MARK = 8;
const DEBUGGING = false;
const boot = `
: ( bl nl + 1- parse drop drop ; immediate ( Now can do comments! )
( bl=32 nl=10 so nl+32-1=41, right paren )
: \\ nl parse drop drop ; immediate
: #! nl parse drop drop ; immediate ( shebang for scripts )
: aligned ( a -- a ) cell 1 - dup >r + r> invert and ;
: align here aligned here - allot ;
( Dictionary Format )
: >flags& ( xt -- a ) cell - ; : >flags ( xt -- flags ) >flags& c@ ;
: >name-length ( xt -- n ) >flags& 1+ c@ ;
: >params ( xt -- n ) >flags& 2 + sw@ $ffff and ;
: >size ( xt -- n ) dup >params cells swap >name-length aligned + 3 cells + ;
: >link& ( xt -- a ) 2 cells - ; : >link ( xt -- a ) >link& @ ;
( Stack Baseline )
sp@ constant sp0
rp@ constant rp0
fp@ constant fp0
( Quoting Words )
: ' bl parse 2dup find dup >r -rot r> 0= 'notfound @ execute 2drop ;
: ['] ' aliteral ; immediate
: char bl parse drop c@ ;
: [char] char aliteral ; immediate
( Core Control Flow )
create BEGIN ' nop @ ' begin ! : begin ['] begin , here ; immediate
create AGAIN ' branch @ ' again ! : again ['] again , , ; immediate
create UNTIL ' 0branch @ ' until ! : until ['] until , , ; immediate
create AHEAD ' branch @ ' ahead ! : ahead ['] ahead , here 0 , ; immediate
create THEN ' nop @ ' then ! : then ['] then , here swap ! ; immediate
create IF ' 0branch @ ' if ! : if ['] if , here 0 , ; immediate
create ELSE ' branch @ ' else ! : else ['] else , here 0 , swap here swap ! ; immediate
create WHILE ' 0branch @ ' while ! : while ['] while , here 0 , swap ; immediate
create REPEAT ' branch @ ' repeat ! : repeat ['] repeat , , here swap ! ; immediate
create AFT ' branch @ ' aft ! : aft drop ['] aft , here 0 , here swap ; immediate
( Recursion )
: recurse current @ @ aliteral ['] execute , ; immediate
( Tools to build postpone later out of recognizers )
: immediate? ( xt -- f ) >flags 1 and 0= 0= ;
: postpone, ( xt -- ) aliteral ['] , , ;
( Rstack nest depth )
variable nest-depth
( FOR..NEXT )
create FOR ' >r @ ' for ! : for 1 nest-depth +! ['] for , here ; immediate
create NEXT ' donext @ ' next ! : next -1 nest-depth +! ['] next , , ; immediate
( Define a data type for Recognizers. )
: RECTYPE: ( xt-interpret xt-compile xt-postpone "name" -- ) CREATE , , , ;
: do-notfound ( a n -- ) -1 'notfound @ execute ;
' do-notfound ' do-notfound ' do-notfound RECTYPE: RECTYPE-NONE
' execute ' , ' postpone, RECTYPE: RECTYPE-WORD
' execute ' execute ' , RECTYPE: RECTYPE-IMM
' drop ' execute ' execute RECTYPE: RECTYPE-NUM
: RECOGNIZE ( c-addr len addr1 -- i*x addr2 )
dup @ for aft
cell+ 3dup >r >r >r @ execute
dup RECTYPE-NONE <> if rdrop rdrop rdrop rdrop exit then
drop r> r> r>
then next
drop RECTYPE-NONE
;
( Define a recognizer stack. )
create RECSTACK 0 , bl 2/ ( 16 no numbers yet ) cells allot
: +RECOGNIZER ( xt -- ) 1 RECSTACK +! RECSTACK dup @ cells + ! ;
: -RECOGNIZER ( -- ) -1 RECSTACK +! ;
: GET-RECOGNIZERS ( -- xtn..xt1 n )
RECSTACK @ for RECSTACK r@ cells + @ next ;
: SET-RECOGNIZERS ( xtn..xt1 n -- )
0 RECSTACK ! for aft +RECOGNIZER then next ;
( Create recognizer based words. )
: postpone ( "name" -- ) bl parse RECSTACK RECOGNIZE @ execute ; immediate
: +evaluate1
bl parse dup 0= if 2drop exit then
RECSTACK RECOGNIZE state @ 1+ 1+ cells + @ execute
;
( Setup recognizing words. )
: REC-FIND ( c-addr len -- xt addr1 | addr2 )
find dup if
dup immediate? if RECTYPE-IMM else RECTYPE-WORD then
else
drop RECTYPE-NONE
then
;
' REC-FIND +RECOGNIZER
( Setup recognizing integers. )
: REC-NUM ( c-addr len -- n addr1 | addr2 )
s>number? if
['] aliteral RECTYPE-NUM
else
RECTYPE-NONE
then
;
' REC-NUM +RECOGNIZER
: interpret0 begin +evaluate1 again ; interpret0
( Useful stack/heap words )
: depth ( -- n ) sp@ sp0 - cell/ ;
: fdepth ( -- n ) fp@ fp0 - 4 / ;
: remaining ( -- n ) 'heap-start @ 'heap-size @ + 'heap @ - ;
: used ( -- n ) 'heap @ sp@ 'stack-cells @ cells + - 28 + ;
( DO..LOOP )
variable leaving
: leaving, here leaving @ , leaving ! ;
: leaving( leaving @ 0 leaving ! 2 nest-depth +! ;
: )leaving leaving @ swap leaving ! -2 nest-depth +!
begin dup while dup @ swap here swap ! repeat drop ;
: DO ( n n -- .. ) swap r> -rot >r >r >r ;
: do ( lim s -- ) leaving( postpone DO here ; immediate
: ?DO ( n n -- n n f .. )
2dup = if 2drop r> @ >r else swap r> cell+ -rot >r >r >r then ;
: ?do ( lim s -- ) leaving( postpone ?DO leaving, here ; immediate
: UNLOOP r> rdrop rdrop >r ;
: LEAVE r> rdrop rdrop @ >r ;
: leave postpone LEAVE leaving, ; immediate
: +LOOP ( n -- ) r> r> dup r@ - >r rot + r> -rot
dup r@ - -rot >r >r xor 0<
if r> cell+ rdrop rdrop >r else r> @ >r then ;
: +loop ( n -- ) postpone +LOOP , )leaving ; immediate
: LOOP r> r> dup r@ - >r 1+ r> -rot
dup r@ - -rot >r >r xor 0<
if r> cell+ rdrop rdrop >r else r> @ >r then ;
: loop postpone LOOP , )leaving ; immediate
create I ' r@ @ ' i ! ( i is same as r@ )
: J ( -- n ) rp@ 3 cells - @ ;
: K ( -- n ) rp@ 5 cells - @ ;
( Exceptions )
variable handler
handler 'throw-handler !
: catch ( xt -- n )
fp@ >r sp@ >r handler @ >r rp@ handler ! execute
r> handler ! rdrop rdrop 0 ;
: throw ( n -- )
dup if handler @ rp! r> handler !
r> swap >r sp! drop r> r> fp! else drop then ;
' throw 'notfound !
( Values )
: value ( n -- ) constant ;
: value-bind ( xt-val xt )
>r >body state @ if
r@ ['] ! = if rdrop ['] doset , , else aliteral r> , then
else r> execute then ;
: to ( n -- ) ' ['] ! value-bind ; immediate
: +to ( n -- ) ' ['] +! value-bind ; immediate
( Deferred Words )
: defer ( "name" -- ) create 0 , does> @ dup 0= throw execute ;
: is ( xt "name -- ) postpone to ; immediate
: >name ( xt -- a n )
dup >flags 8 and if
dup >link swap >name-length
else
dup >name-length swap >link& over aligned - swap
then
;
: fill32 ( a n v ) swap >r swap r> 0 ?do 2dup ! cell+ loop 2drop ;
( Defer I/O to platform specific )
defer type
defer key
defer key?
defer terminate
: bye 0 terminate ;
: emit ( n -- ) >r rp@ 1 type rdrop ;
: space bl emit ; : cr 13 emit nl emit ;
( Numeric Output )
variable hld
: pad ( -- a ) here 80 + ;
: digit ( u -- c ) 9 over < 7 and + 48 + ;
: extract ( n base -- n c ) u/mod swap digit ;
: <# ( -- ) pad hld ! ;
: hold ( c -- ) hld @ 1 - dup hld ! c! ;
: # ( u -- u ) base @ extract hold ;
: #s ( u -- 0 ) begin # dup while repeat ;
: sign ( n -- ) 0< if 45 hold then ;
: #> ( w -- b u ) drop hld @ pad over - ;
: str ( n -- b u ) dup >r abs <# #s r> sign #> ;
: hex ( -- ) 16 base ! ; : octal ( -- ) 8 base ! ;
: decimal ( -- ) 10 base ! ; : binary ( -- ) 2 base ! ;
: u. ( u -- ) <# #s #> type space ;
: . ( w -- ) base @ 10 xor if u. exit then str type space ;
: ? ( a -- ) @ . ;
: n. ( n -- ) base @ swap decimal <# #s #> type base ! ;
( Strings )
: parse-quote ( -- a n ) [char] " parse ;
: $place ( a n -- ) for aft dup c@ c, 1+ then next drop ;
: zplace ( a n -- ) $place 0 c, align ;
: $@ r@ dup cell+ swap @ r> dup @ 1+ aligned + cell+ >r ;
: s" parse-quote state @ if postpone $@ dup , zplace
else dup here swap >r >r zplace r> r> then ; immediate
: ." postpone s" state @ if postpone type else type then ; immediate
: z" postpone s" state @ if postpone drop else drop then ; immediate
: r" parse-quote state @ if swap aliteral aliteral then ; immediate
: r| [char] | parse state @ if swap aliteral aliteral then ; immediate
: r~ [char] ~ parse state @ if swap aliteral aliteral then ; immediate
: s>z ( a n -- z ) here >r zplace r> ;
: z>s ( z -- a n ) 0 over begin dup c@ while 1+ swap 1+ swap repeat drop ;
( Better Errors )
: notfound ( a n n -- )
dup if cr ." ERROR: " >r type r> ." NOT FOUND!" cr throw else drop then ;
' notfound 'notfound !
( Abort )
: abort -1 throw ;
: abort" postpone ." postpone cr -2 aliteral postpone throw ; immediate
( Input )
: raw.s depth 0 max for aft sp@ r@ cells - @ . then next ;
variable echo -1 echo ! variable arrow -1 arrow ! 0 value wascr
: *emit ( n -- ) dup 13 = if drop cr else emit then ;
: ?echo ( n -- ) echo @ if *emit else drop then ;
: ?arrow. arrow @ if >r >r raw.s r> r> ." --> " then ;
: *key ( -- n )
begin
key
dup nl = if
drop wascr if 0 else 13 exit then
then
dup 13 = to wascr
dup if exit else drop then
again ;
: eat-till-cr begin *key dup 13 = if ?echo exit else drop then again ;
: accept ( a n -- n ) ?arrow. 0 swap begin 2dup < while
*key
dup 13 = if ?echo drop nip exit then
dup 8 = over 127 = or if
drop over if rot 1- rot 1- rot 8 ?echo bl ?echo 8 ?echo then
else
dup ?echo
>r rot r> over c! 1+ -rot swap 1+ swap
then
repeat drop nip
eat-till-cr
;
200 constant input-limit
: tib ( -- a ) 'tib @ ;
create input-buffer input-limit allot
: tib-setup input-buffer 'tib ! ;
: refill tib-setup tib input-limit accept #tib ! 0 >in ! -1 ;
( Stack Guards )
sp0 'stack-cells @ 2 3 */ cells + constant sp-limit
: ?stack sp@ sp0 < if ." STACK UNDERFLOW " -4 throw then
sp-limit sp@ < if ." STACK OVERFLOW " -3 throw then ;
( REPL )
: prompt ." ok" cr ;
: evaluate-buffer begin >in @ #tib @ < while ?stack +evaluate1 repeat ?stack ;
: evaluate ( a n -- ) 'tib @ >r #tib @ >r >in @ >r
#tib ! 'tib ! 0 >in ! evaluate-buffer
r> >in ! r> #tib ! r> 'tib ! ;
: evaluate&fill
begin >in @ #tib @ >= if prompt refill drop then evaluate-buffer again ;
: quit
#tib @ >in !
begin ['] evaluate&fill catch
if 0 state ! sp0 sp! fp0 fp! rp0 rp! ." ERROR " cr then
again ;
variable boot-prompt
: free. ( nf nu -- ) 2dup swap . ." free + " . ." used = " 2dup + . ." total ("
over + 100 -rot */ n. ." % free)" ;
: raw-ok ." v7.0.7.21 - rev cb5da2542a5132448fba09b0cd640dd715299f4b" cr
boot-prompt @ if boot-prompt @ execute then
." Forth dictionary: " remaining used free. cr
." 3 x Forth stacks: " 'stack-cells @ cells . ." bytes each" cr
quit ;
( Interpret time conditionals )
: DEFINED? ( "name" -- xt|0 )
begin bl parse dup 0= while 2drop refill 0= throw repeat
find state @ if aliteral then ; immediate
defer [SKIP]
: [THEN] ; immediate
: [ELSE] [SKIP] ; immediate
: [IF] 0= if [SKIP] then ; immediate
: [SKIP]' 0 begin postpone defined? dup if
dup ['] [IF] = if swap 1+ swap then
dup ['] [ELSE] = if swap dup 0 <= if 2drop exit then swap then
dup ['] [THEN] = if swap 1- dup 0< if 2drop exit then swap then
then drop again ;
' [SKIP]' is [SKIP]
( Implement Vocabularies )
( normal: link, flags&len, code )
( vocab: link, flags&len, code | link , len=0, voclink )
variable last-vocabulary
: vocabulary ( "name" )
create current @ 2 cells + , 0 , last-vocabulary @ ,
current @ @ last-vocabulary !
does> context ! ;
: definitions context @ current ! ;
vocabulary FORTH
' forth >body @ >link ' forth >body !
forth definitions
( Make it easy to transfer words between vocabularies )
: xt-find& ( xt -- xt& ) context @ begin 2dup @ <> while @ >link& repeat nip ;
: xt-hide ( xt -- ) xt-find& dup @ >link swap ! ;
8 constant BUILTIN_MARK
: xt-transfer ( xt -- ) dup >flags BUILTIN_MARK and if drop exit then
dup xt-hide current @ @ over >link& ! current @ ! ;
: transfer ( "name" ) ' xt-transfer ;
: }transfer ;
: transfer{ begin ' dup ['] }transfer = if drop exit then xt-transfer again ;
( Watered down versions of these )
: only forth 0 context cell+ ! ;
: voc-stack-end ( -- a ) context begin dup @ while cell+ repeat ;
: also context context cell+ voc-stack-end over - 2 cells + cmove> ;
: previous
voc-stack-end context cell+ = throw
context cell+ context voc-stack-end over - cell+ cmove ;
: sealed 0 last-vocabulary @ >body ! ;
( Hide some words in an internals vocabulary )
vocabulary internals internals definitions
( Vocabulary chain for current scope, place at the -1 position )
variable scope scope context cell - !
transfer{
xt-find& xt-hide xt-transfer
voc-stack-end last-vocabulary notfound
*key *emit wascr eat-till-cr
immediate? input-buffer ?echo ?arrow. arrow
evaluate-buffer evaluate&fill aliteral value-bind
leaving( )leaving leaving leaving,
parse-quote digit $@ raw.s
tib-setup input-limit sp-limit ?stack
[SKIP] [SKIP]' raw-ok boot-prompt free.
$place zplace BUILTIN_MARK
nest-depth handler +evaluate1 do-notfound interpret0
}transfer
( Move branching opcodes to separate vocabulary. )
vocabulary internalized internalized definitions
: cleave ' >link xt-transfer ;
cleave begin cleave again cleave until
cleave ahead cleave then cleave if
cleave else cleave while cleave repeat
cleave aft cleave for cleave next
cleave do cleave ?do cleave +loop
cleave loop cleave leave
forth definitions
( Move recognizers to separate vocabulary )
vocabulary recognizers recognizers definitions
transfer{
REC-FIND REC-NUM
RECTYPE: RECTYPE-NONE RECTYPE-WORD RECTYPE-IMM RECTYPE-NUM
SET-RECOGNIZERS GET-RECOGNIZERS
-RECOGNIZER +RECOGNIZER RECSTACK
RECOGNIZE
}transfer
forth definitions
( Make DOES> switch to compile mode when interpreted )
(
forth definitions internals
' does>
: does> state @ if postpone does> exit then
['] constant @ current @ @ dup >r !
here r> cell+ ! postpone ] ; immediate
xt-hide
forth definitions
)
: sf, ( r -- ) here sf! sfloat allot ;
: afliteral ( r -- ) ['] DOFLIT , sf, align ;
: fliteral afliteral ; immediate
: fconstant ( r "name" ) create sf, align does> sf@ ;
: fvariable ( "name" ) create sfloat allot align ;
6 value precision
: set-precision ( n -- ) to precision ;
( Add recognizer for floats. )
also recognizers definitions
: REC-FNUM ( c-addr len -- f addr1 | addr2 )
s>float? if
['] afliteral RECTYPE-NUM
else
RECTYPE-NONE
then
;
' REC-FNUM +RECOGNIZER
previous definitions
internals definitions
: #f+s ( r -- ) fdup precision for aft 10e f* then next
precision for aft fdup f>s 10 mod [char] 0 + hold 0.1e f* then next
[char] . hold fdrop f>s #s ;
forth definitions internals
: #fs ( r -- ) fdup f0< if fnegate #f+s [char] - hold else #f+s then ;
: f. ( r -- ) <# #fs #> type space ;
: f.s ." <" fdepth n. ." > "
fdepth 0 max for aft fp@ r@ sfloats - sf@ f. then next ;
forth definitions
( Vocabulary for building C-style structures )
vocabulary structures structures definitions
variable last-align
variable last-typer
: typer ( xt@ xt! sz "name" -- )
create dup , 1 max cell min , , ,
does> dup last-typer ! dup cell+ @ last-align ! @ ;
: sc@ ( a -- c ) c@ dup 127 > if 256 - then ;
' sc@ ' c! 1 typer i8
' c@ ' c! 1 typer u8
' sw@ ' w! 2 typer i16
' uw@ ' w! 2 typer u16
' sl@ ' l! 4 typer i32
' ul@ ' l! 4 typer u32
' @ ' ! 8 typer i64 ( Wrong on 32-bit! )
' @ ' ! cell typer ptr
long-size cell = [IF]
: long ptr ;
[ELSE]
: long i32 ;
[THEN]
variable last-struct
: struct ( "name" ) 0 0 0 typer latestxt >body last-struct !
1 last-align ! ;
: align-by ( a n -- a ) 1- dup >r + r> invert and ;
: max! ( n a -- ) swap over @ max swap ! ;
: struct-align ( n -- )
dup last-struct @ cell+ max!
last-struct @ @ swap align-by last-struct @ ! ;
: field ( n "name" )
last-align @ struct-align
create last-struct @ @ , last-struct @ +! last-typer @ ,
does> @ + ;
: field-op ( n "name" -- )
>r ' dup >body cell+ @ r> cells + @
state @ if >r , r> , else >r execute r> execute then ;
: !field ( n "name" -- ) 2 field-op ; immediate
: @field ( "name" -- n ) 3 field-op ; immediate
forth definitions
vocabulary web web definitions
: jseval! ( a n index -- ) 0 call ;
r~
(function(sp) {
var slot = i32[sp>>2]; sp -= 4;
var n = i32[sp>>2]; sp -= 4;
var a = i32[sp>>2]; sp -= 4;
var text = GetString(a, n);
var parts = text.split('\\n');
var args = parts[0].split(' ');
var code = '(function(sp) {\\n';
code += 'var results = (function() {\\n';
var params = [];
var results = [];
var at_results = false;
for (var i = 0; i < args.length; ++i) {
if (args[i].length === 0 ||
args[i] === '{' ||
args[i] === '}') {
continue;
}
if (args[i] === '--') {
at_results = true;
continue;
}
if (at_results) {
results.push(args[i]);
} else {
params.push(args[i]);
}
}
for (var i = params.length - 1; i >= 0; --i) {
code += 'var ' + params[i] + ' = i32[sp>>2]; sp -= 4;\\n';
}
code += parts.slice(1).join('\\n');
code += '})();\\n';
if (results.length === 1) {
code += 'sp += 4; i32[sp>>2] = results;\\n';
} else {
for (var i = 0; i < results.length; ++i) {
code += 'sp += 4; i32[sp>>2] = results[' + i + '];\\n';
}
}
code += 'return sp;\\n';
code += '})\\n';
objects[slot] = eval(code);
return sp;
})
~ 1 jseval!
2 value jsslot
: JSWORD: ( "args.." )
create postpone r~ jsslot 1 call jsslot , 1 +to jsslot
does> @ call ;
JSWORD: jseval { a n }
var text = GetString(a, n);
eval(text);
~
r~
globalObj.ueforth = context;
context.inbuffer = [];
context.Update = function() {};
if (!globalObj.write) {
function AddMeta(name, content) {
var meta = document.createElement('meta');
meta.name = name;
meta.content = content;
document.head.appendChild(meta);
}
AddMeta('apple-mobile-web-app-capable', 'yes');
AddMeta('apple-mobile-web-app-status-bar-style', 'black-translucent');
AddMeta('viewport', 'width=device-width, initial-scale=1.0, ' +
'maximum-scale=1.0, user-scalable=no, minimal-ui');
context.screen = document.getElementById('ueforth');
if (context.screen === null) {
context.screen = document.createElement('div');
context.screen.style.width = '100%';
document.body.appendChild(context.screen);
}
context.filler = document.createElement('div');
document.body.insertBefore(context.filler, document.body.firstChild);
context.canvas = document.createElement('canvas');
context.canvas.width = 1000;
context.canvas.height = 1000;
context.canvas.style.width = '1px';
context.canvas.style.height = '1px';
context.canvas.style.top = 0;
context.canvas.style.left = 0;
context.canvas.style.position = 'fixed';
context.canvas.style.backgroundColor = '#000';
context.screen.appendChild(context.canvas);
context.ctx = context.canvas.getContext('2d');
context.mouse_x = 0;
context.mouse_y = 0;
context.mouse_b = 0;
context.canvas.onpointermove = function(e) {
context.mouse_x = e.clientX;
context.mouse_y = e.clientY;
};
context.canvas.onpointerdown = function(e) {
context.mouse_x = e.clientX;
context.mouse_y = e.clientY;
context.mouse_b = 1;
e.target.setPointerCapture(e.pointerId);
};
context.canvas.onpointerup = function(e) {
context.mouse_x = e.clientX;
context.mouse_y = e.clientY;
context.mouse_b = 0;
e.target.releasePointerCapture(e.pointerId);
};
context.cursor = null;
context.cursor_time = new Date().getTime();
setInterval(function() {
if (context.cursor) {
var now = new Date().getTime();
var state = Math.floor((now - context.cursor_time) / 250) % 2;
if (state || context.min_text_portion === 0) {
context.cursor.style.visibility = 'hidden';
} else {
context.cursor.style.visibility = 'visible';
}
}
}, 50);
context.GetRawString = function(data8, addr, len) {
var data = '';
for (var i = 0; i < len; ++i) {
data += String.fromCharCode(data8[addr + i]);
}
return data;
};
context.handles = [];
context.free_handles = [];
context.next_handle = 1;
context.AllotHandle = function() {
if (context.free_handles.length) {
return context.free_handles.pop();
}
return context.next_handle++;
};
context.ReleaseHandle = function(id) {
if (context.handles[id] !== null) {
context.handles[id] = null;
context.free_handles.push(id);
}
};
context.terminal = document.createElement('div');
context.terminal.style.width = '100%';
context.terminal.style.whiteSpace = 'pre-wrap';
context.screen.appendChild(context.terminal);
const DEFAULT_FG = 0x000000;
const DEFAULT_BG = 0xFFFFFF;
context.attrib = [DEFAULT_FG, DEFAULT_BG];
context.lines = [];
context.escaping = [];
context.LineFeed = function() {
var line = document.createElement('pre');
line.style.width = '100%';
line.style.whiteSpace = 'pre-wrap';
line.style.margin = '0px';
if (context.cy < 0) {
context.terminal.appendChild(line);
} else {
context.terminal.insertBefore(line, context.lines[context.cy].nextSibling);
}
context.cx = 0; // implicit cr
if (context.cy >= 0) {
context.dirty[context.cy] = 1;
}
++context.cy;
context.lines.splice(context.cy, 0, [line, []]);
context.dirty[context.cy] = 1;
};
context.toRGB = function(col) {
var r = (col >> 16) & 0xff;
var g = (col >> 8) & 0xff;
var b = col & 0xff;
return 'rgb(' + r + ',' + g + ',' + b + ')';
};
context.ResetTerminal = function() {
// TODO: Make this nicer.
document.body.style.color = context.toRGB(context.attrib[0]);
document.body.style.backgroundColor = context.toRGB(context.attrib[1]);
for (var i = 0; i < context.lines.length; ++i) {
context.terminal.removeChild(context.lines[i][0]);
}
context.lines = [];
context.cx = 0;
context.cy = -1;
context.dirty = {};
context.LineFeed();
};
context.ResetTerminal();
context.TermColor = function(n) {
n = n & 0xff;
if (n < 16) {
var i = n & 8;
var r = (n & 1) ? (i ? 255 : 192) : (i ? 128 : 0);
var g = (n & 2) ? (i ? 255 : 192) : (i ? 128 : 0);
var b = (n & 4) ? (i ? 255 : 192) : (i ? 128 : 0);
return (r << 16) | (g << 8) | b;
} else if (n < 232) {
n -= 16;
var r = Math.round((Math.floor(n / 36) % 6) * 255 / 5);
var g = Math.round((Math.floor(n / 6) % 6) * 255 / 5);
var b = Math.round((n % 6) * 255 / 5);
return (r << 16) | (g << 8) | b;
} else {
n = Math.round((n - 232) * 255 / 23);
return (n << 16) | (n << 8) | n;
}
};
context.EscapeCode = function(code) {
var m;
if (code == '[2J') {
context.ResetTerminal();
} else if (code == '[H') {
context.cx = 0;
context.cy = 0;
} else if (code == '[0m') {
context.attrib = [DEFAULT_FG, DEFAULT_BG];
} else if (m = code.match(/\\[38;5;([0-9]+)m/)) {
context.attrib[0] = context.TermColor(parseInt(m[1]));
} else if (m = code.match(/\\[48;5;([0-9]+)m/)) {
context.attrib[1] = context.TermColor(parseInt(m[1]));
} else {
console.log('Unknown escape code: ' + code);
}
};
context.Emit = function(ch) {
if (ch === 27) {
context.escaping = [27];
return;
}
if (context.escaping.length) {
context.escaping.push(ch);
if ((ch >= 65 && ch <= 90) || (ch >= 97 && ch <= 122)) { // [A-Za-z]
context.EscapeCode(new TextDecoder('utf-8').decode(new Uint8Array(context.escaping)).slice(1));
context.escaping = [];
}
return;
}
if (ch === 12) {
context.ResetTerminal();
context.dirty = {};
return;
} else if (ch == 10) {
context.LineFeed();
return;
}
context.dirty[context.cy] = 1;
if (ch === 8) {
context.cx = Math.max(0, context.cx - 1);
} else if (ch === 13) {
context.lines[context.cy][1].splice(
context.cx++, 1, [context.attrib[0], context.attrib[1]]);
context.cx = 0;
} else {
context.lines[context.cy][1].splice(
context.cx++, 1, [context.attrib[0], context.attrib[1], ch]);
}
};
context.Update = function() {
const CURSOR = String.fromCharCode(0x2592);
var count = 0;
for (var y in context.dirty) {
++count;
var tag = context.lines[y][0];
var line = context.lines[y][1];
var parts = [];
var p = null;
for (var x = 0; x < line.length; ++x) {
if (x == 0 ||
(x == context.cx && y == context.cy) ||
p[0] != line[x][0] || p[1] != line[x][1]) {
parts.push([line[x][0], line[x][1], []]);
p = parts[parts.length - 1];
if (x == context.cx && y == context.cy) {
p[0] |= 0x1000000;
}
}
if (line[x].length >= 2) {
p[2].push(line[x][2]);
}
}
if (x == context.cx && y == context.cy) {
if (parts.length > 0) {
parts.push([parts[parts.length - 1][0] | 0x1000000,
parts[parts.length - 1][1], []]);
} else {
parts.push([context.attrib[0] | 0x1000000,
context.attrib[1], []]);
}
}
var ntag = document.createElement('pre');
ntag.style.width = '100%';
ntag.style.whiteSpace = 'pre-wrap';
ntag.style.margin = '0px';
for (var i = 0; i < parts.length; ++i) {
var span = document.createElement('span');
span.innerText = new TextDecoder('utf-8').decode(new Uint8Array(parts[i][2]));
span.style.color = context.toRGB(parts[i][0]);
span.style.backgroundColor = context.toRGB(parts[i][1]);
if (parts[i][0] & 0x1000000) {
span.style.position = 'relative';
var cursor = document.createElement('span');
cursor.classList.add('cursor');
cursor.innerText = CURSOR;
cursor.style.position = 'absolute';
cursor.style.left = '0px';
cursor.style.backgroundColor = span.style.backgroundColor;
span.appendChild(cursor);
context.cursor = cursor;
context.cursor.style.visibility = 'hidden';
}
ntag.appendChild(span);
if (i === parts.length - 1) {
ntag.style.color = span.style.color;
ntag.style.backgroundColor = span.style.backgroundColor;
}
}
context.terminal.replaceChild(ntag, tag);
context.lines[y][0] = ntag;
}
var newline = count > 1 || context.dirty[context.lines.length - 1];
context.dirty = {};
if (newline) {
window.scrollTo(0, document.body.scrollHeight);
}
};
context.keyboard = document.createElement('div');
context.KEY_HEIGHT = 45;
context.KEYBOARD_HEIGHT = context.KEY_HEIGHT * 4;
const TAB = ['⭾', 9, 45];
const PIPE = [String.fromCharCode(124), 124, 45];
const BACKSLASH = ['\\\\', 92, 45];
const ENTER = ['⏎', 13, 45];
const SHIFT = ['⇧', 1, 45, 0];
const SHIFT2 = ['⬆', 0, 45, 0];
const SHIFT3 = ['=\\\\<', 3, 45, 0];
const NUMS = ['?123', 2, 45, 0];
const ABC = ['ABC', 0, 45, 0];
const BACKSPACE = ['⌫', 8, 45];
const BACKTICK = String.fromCharCode(96);
const TILDE = String.fromCharCode(126);
const PASTE = ['^V', 22, 30];
const G1 = ['Gap', 0, 15];
const KEY_COLOR = 'linear-gradient(to bottom right, #ccc, #999)';
var keymaps = [
AddKeymap([
'q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p', 'Newline',
G1, 'a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l', G1, 'Newline',
SHIFT, 'z', 'x', 'c', 'v', 'b', 'n', 'm', BACKSPACE, 'Newline',
NUMS, '/', [' ', 32, 5 * 30], '.', ENTER,
]),
AddKeymap([
'Q', 'W', 'E', 'R', 'T', 'Y', 'U', 'I', 'O', 'P', 'Newline',
G1, 'A', 'S', 'D', 'F', 'G', 'H', 'J', 'K', 'L', G1, 'Newline',
SHIFT2, 'Z', 'X', 'C', 'V', 'B', 'N', 'M', BACKSPACE, 'Newline',
NUMS, '/', [' ', 32, 5 * 30], '.', ENTER,
]),
AddKeymap([
'1', '2', '3', '4', '5', '6', '7', '8', '9', '0', 'Newline',
PASTE, '@', '$', '_', '&', '-', '+', '(', ')', '/', 'Newline',
SHIFT3, '*', '"', '\\'', ':', ';', '!', '?', BACKSPACE, 'Newline',
ABC, ',', [' ', 32, 5 * 30], '.', ENTER,
]),
AddKeymap([
TILDE, BACKTICK, '3', '4', '5', '^', '7', '8', '9', '0', 'Newline',
'#', '@', '$', '_', '&', '-', '=', '{', '}', '\\\\', 'Newline',
NUMS, '%', '"', '\\'', ':', ';', '[', ']', BACKSPACE, 'Newline',
ABC, '<', [' ', 32, 5 * 30], '>', ENTER,
]),
];
function SwitchKeymap(n) {
for (var i = 0; i < keymaps.length; ++i) {
keymaps[i].style.display = i == n ? '' : 'none';
}
}
context.Inject = function(text) {
var data = new TextEncoder().encode(text);
for (var i = 0; i < data.length; ++i) {
context.inbuffer.push(data[i]);
}
};
context.Paste = function() {
navigator.clipboard.readText().then(function(clipText) {
context.Inject(clipText);
});
};
function AddKey(keymap, item) {
if (item === 'Newline') {
var k = document.createElement('br');
keymap.appendChild(k);
return;
}
var k = document.createElement('button');
k.style.fontFamily = 'monospace';
k.style.verticalAlign = 'middle';
k.style.border = 'none';
k.style.margin = '0';
k.style.padding = '0';
k.style.backgroundImage = KEY_COLOR;
k.style.width = (100 / 10) + '%';
k.style.height = context.KEY_HEIGHT + 'px';
if (item.length > 2) {
k.style.width = (100 / 10 * item[2] / 30) + '%';
}
if (item[0] === 'Gap') {
k.style.backgroundColor = '#444';
k.style.backgroundImage = '';
keymap.appendChild(k);
return;
}
if (item.length > 1) {
var keycode = item[1];
} else {
var keycode = item[0].charCodeAt(0);
}
k.innerHTML = item instanceof Array ? item[0] : item;
k.onclick = function() {
if (item.length > 3) { // SHIFT
SwitchKeymap(item[1]);
} else if (keycode === 22) { // PASTE
context.Paste();
} else {
context.inbuffer.push(keycode);
}
};
keymap.appendChild(k);
}
function AddKeymap(keymap) {
var div = document.createElement('div');
for (var i = 0; i < keymap.length; ++i) {
var item = keymap[i];
AddKey(div, item);
}
context.keyboard.appendChild(div);
return div;
}
SwitchKeymap(0);
context.keyboard.style.position = 'fixed';
context.keyboard.style.width = '100%';
context.keyboard.style.bottom = '0px';
if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) {
context.mobile = -1;
context.tailer = document.createElement('div');
context.tailer.style.width = '1px';
context.tailer.style.height = context.KEYBOARD_HEIGHT + 'px';
context.screen.appendChild(context.tailer);
document.body.appendChild(context.keyboard);
} else {
context.mobile = 0;
}
context.text_fraction = context.mobile ? 3000 : 1667;
context.min_text_portion = 120 + (context.mobile ? context.KEYBOARD_HEIGHT : 0);
context.mode = 1;
function setMode(mode) {
if (context.mode === mode) {
return ;
}
if (mode) {
context.filler.style.display = '';
context.canvas.style.display = '';
} else {
context.filler.style.display = 'none';
context.canvas.style.display = 'none';
}
context.mode = mode;
}
context.setMode = setMode;
function Resize() {
var width = window.innerWidth;
var theight = Math.max(context.min_text_portion,
Math.floor(window.innerHeight *
context.min_text_portion / 10000));
var height = window.innerHeight - theight;
if (width === context.width && height === context.height) {
return;
}
context.canvas.style.width = width + 'px';
context.canvas.style.height = height + 'px';
if (context.text_fraction == 0 &&
context.min_text_portion == 0) {
context.filler.style.width = '1px';
context.filler.style.height = '0px';
} else {
context.filler.style.width = '1px';
context.filler.style.height = height + 'px';
}
context.width = width;