-
Notifications
You must be signed in to change notification settings - Fork 0
/
foundation.clvr
802 lines (691 loc) · 13.8 KB
/
foundation.clvr
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
9 constant: '\t'
10 constant: '\n'
27 constant: '\e'
: end-of-comment? '\n' eq? ;
: -- #immediate ' end-of-comment? scan drop ;
-- now we have comments. Yay!
: c: #immediate
-- compile a (possibly multi-byte) char
word
1 cell + @
compile-literal
;
: spc 'spc' putc ;
: before - ;
: after + ;
-1 constant: true
0 constant: false
: cells cell ;
: kiB 10 bits-up ;
: MiB 20 bits-up ;
: GiB 30 bits-up ;
: div divmod drop ;
: mod divmod nip ;
: prev-cell here 1 cell before ;
: next-cell here 1 cell after ;
: exception: #immediate
create-variable
;
: compile-jump , here 0 , ; -- instr -- addr
: compile-unconditional-jump ' branch compile-jump ;
: compile-conditional-jump ' zbranch compile-jump ;
: jump-target dup here swap - swap ! ;
variable: if-nesting-depth
: if compile-conditional-jump if-nesting-depth inc-var ; #immediate
: else #immediate
compile-unconditional-jump push
jump-target
pop
;
: endif jump-target if-nesting-depth dec-var ; #immediate
-- convert between string types
: s->z -- str -- zstr len
dup 1 cell after
swap @
;
exception: ZStringTransformationNotImplemented
: z->s -- zstr len -- str
swap stash
1 cell before @
matches? if
pop 1 cell before
else
trash ZStringTransformationNotImplemented raise
endif
;
-- TODO: modify c: to use Unicode code points instead of raw UTF-8
-- TODO: modify putc to support multibyte chars
: debug
WordBuffer puts spc
stash putn
spc
'(' putc
'0' putc
'x' putc
peek putx
-- peek toEntry dup if
-- endif
peek 31 128 between? if
spc
''' putc
peek putc
''' putc
endif
')' putc
pop
report
;
-- macro: : -- replace with debugging version
-- word words
-- here debug drop
-- define
-- ;
: while-word -- S ( word -> bool ) -> T
-- consume words until the passed function
-- returns false
push
word peek call if
pop
tail: while-word
else
trash
endif
;
: _nested-comment -- n word -- n bool
1 cell after @
stash ')' eq? if
1 -
trash
else
pop '(' eq? if 1 + endif
endif
dup bool
;
: ( #immediate
1 -- track the depth of the nesting
' _nested-comment while-word
drop
;
: scratchpad
scratchpad-addr @
;
-- let's implement pattern matching
variable: pattern-match-depth
variable: rs-usage
: unbalanced-rs-error
current-def @ .label
UnbalancedRSInBranch 2 warning
;
: -> #immediate
' matches? ,
compile-conditional-jump
rs-usage @
pattern-match-depth inc-var
;
: ;; #immediate
' return ,
rs-usage @ if unbalanced-rs-error endif
rs-usage !
jump-target
pattern-match-depth dec-var
;
-- macro: _ ' dup , ;
: _ #immediate
word drop -- consume ->
scratchpad -- somewhere for jump-target to write to
-- this is the last part of the match, so we don't keep rs-usage. Doing so
-- would generate spurious unbalanced-rs-error exceptions
0 -- rs-usage @
pattern-match-depth inc-var -- because we've dumped the ->
;
( : base-literal ( n -> n )
word swap base
true -> drop ;;
false ->
drop drop
WordBuffer
NumParse 2 compile-error
;;
;
: bin: 2 base-literal compile-literal ; #immediate
: oct: 8 base-literal compile-literal ; #immediate
: hex: 16 base-literal compile-literal ; #immediate
)
: nextEntry @ ;
variable: stringTerminator
: handleStringEsc ( c -- )
'e' -> drop '\e' ;;
'n' -> drop '\n' ;;
't' -> drop '\t' ;;
'0' -> drop 0 ;;
stringTerminator @
-> ;;
'\' -> ;;
_ -> -- Invalid escape. TODO: proper error handling!
-- s" \\x" dup 1 cell after 1+ ! -- addr of x in preceding string
WordBuffer InvalidEsc 2 compile-error
;;
;
: _string ( char bool -- )
-- boolean indicates whether the next character is
-- escaped
if ( escape chars. )
key handleStringEsc ,c false _string
else
key
stringTerminator @ -> drop ;;
'\' -> drop true _string ;;
_ -> ,c false _string ;;
endif
;
: compileZString ( char -- zstr )
stringTerminator !
here
false _string
here 1+ align
0 , 0 ,
dp!
;
: compileString ( char -- str )
here push
0 ,
compileZString
lenz peek !
pop
;
: compileInlineString ( char -- )
compile-unconditional-jump
swap compileString
swap jump-target
compile-literal
;
: s" #immediate
'"' compileInlineString
;
: z" #immediate
compile-unconditional-jump
'"' compileZString
swap jump-target
compile-literal
;
-- empty-string constant
: "" s" " ;
-- dictionary accessor convenience functions
: cfa->entry ( cfa -- entry )
3 cells before
;
: cfa->label ( cfa -- str )
2 cells before
;
: cfa->pfa 1 cell after ;
-- Compile-time execution support
variable: close-bracket-behaviour
: unmatchedBracket s" Unmatched ]" 1 compile-error ;
: startImmedCodeBlock ( -- addr )
here
anon-code-area-addr @ dp!
DoAddr ,
;
: endImmedCodeBlock ( oldDp -- ?? )
' return ,
dp! anon-code-area-addr @ call
;
: #[ ( -- oldDp prevBehav ) #immediate
close-bracket-behaviour @
' endImmedCodeBlock close-bracket-behaviour !
startImmedCodeBlock swap
-- report
;
-- anonymous function support
: endAnonCodeBlock ( lambda jaddr -- )
' return ,
jump-target
compile-literal
;
: again #immediate
anon-code-area-addr @ call
;
: [ ( -- lambda jaddr prevBehav ) #immediate
-- s" [ " puts report
compile-unconditional-jump
here swap
DoAddr ,
close-bracket-behaviour @
' endAnonCodeBlock close-bracket-behaviour !
-- report
;
-- generic code block closing function
: ] ( prevBehav -- ) #immediate
-- report
close-bracket-behaviour @ push
close-bracket-behaviour !
pop call
-- report c: ] putc nl nl
;
: [] [ ] ;
' unmatchedBracket close-bracket-behaviour !
: times #immediate
' push ,
here
' peek ,
compile-conditional-jump
' pop ,
' 1- ,
' push ,
swap
;
: forever #immediate
-1 compile-literal
' push ,
here
' peek , -- ' debug ,
compile-conditional-jump
swap
;
: repeat #immediate
next-cell -
compile-unconditional-jump
!
jump-target
' trash ,
;
(
: seeEntry ( entry -- )
'(' putc .label puts ')' putc nl return
findWord dup if
':' putc spc 'spc'
else
'(' putc ')'
endif
pop .label puts
putc nl
;
: seeWords words ' seeEntry each ;
: seeMacros macros ' seeEntry each ;
: see ( cfa -- )
cfa->entry seeEntry
;
)
: allot ( n -- )
here + align dp!
;
: not-imlemented
s" declared but not implemented."
peek 5 cells before .label
2 compile-error
;
: declare: #immediate
-- allow forward declarations. Provide an implementation
-- using 'implements:'
create-word
' not-imlemented ,
' return ,
done-compiling
;
: implements
-- Warning: complex behaviour! takes the CFA at its return address
-- and re-writes the PF with the function in ToS
pop dup 1 cell after push -- skip the next compiled word
@ 1 cell after stash !
' return pop 1 cell after ! --
;
: prior: #immediate
-- compile a word, ignoring the currently in-progress definition
word dup current-def @ find
0 -> drop NotFound 2 compile-error ;;
_ -> .cfa , drop ;;
;
: suppress-macro: #immediate
word dup words find
0 -> drop NotFound 2 compile-error ;;
_ -> .cfa , drop ;;
;
: close ( fh -- )
prior: close
0 -> drop ;;
_ -> drop s" Closing file failed" 1 error ;;
;
-- RS safety checks ------------------------------------------
: stash #immediate
rs-usage inc-var
' suppress-macro: stash ,
;
: push #immediate
rs-usage inc-var
' suppress-macro: push ,
;
: pop #immediate
rs-usage dec-var
' suppress-macro: pop ,
;
: trash #immediate
rs-usage dec-var
' suppress-macro: trash ,
;
: _done
-- this gives us some static error checking on RS usage and nesting of conditionals
rs-usage @ if
current-def @ .label
s" Possibly unbalanced RS use in definition of " 2 warning
0 rs-usage !
endif
if-nesting-depth @ if
current-def @ .label
s" Unmatched if or endif in definition of " 2 warning
0 if-nesting-depth !
endif
pattern-match-depth @ if
current-def @ .label
s" Unmatched -> or ;; in definition of " 2 warning
0 pattern-match-depth !
endif
tail: compile-;
;
: ; tail: _done ; #immediate
-- structures
: struct: #immediate
create-word
' here ,
' lit ,
here push 0 ,
' allot ,
compile-;
pop
0
-- s" struct: " puts
-- dup putn
;
: end #immediate
-- s" link" findWord putx
-- dup putn spc
-- nl
align swap !
;
: _field ( n1 n2 -- n )
create-word
swap dup compile-literal
' + ,
compile-;
+
-- spc dup putn
;
: cell: ( tot n -- tot' ) #immediate
1 cell _field
;
: field: _field ; #immediate
: sizeof: ( -- n ) #immediate
word findWord .pfa 2 cells after @ align compile-literal
;
: _see-data-stack
s" ds(" puts
dsp@ push
ds0 @
dup
pop - CellBits bits-down
dup putn
s" ): " puts
times
1 cell before
stash @ stash putn
s" [36m0x" puts
peek putx
peek 32 128 between? if
spc s" [35m'" puts
peek putc
''' putc
endif
s" [0m " puts
spc
trash pop
repeat
drop
nl
;
: see-data-stack #immediate
current-def @ .label compile-literal
' puts ,
':' compile-literal
' putc ,
here current-def @ .pfa - CellBits bits-down compile-literal
' putn ,
' spc ,
' _see-data-stack ,
;
: cons ( elem list -- )
-- Warning: this presumes the first cell of elem
-- is reserved for a list pointer
stash @ ( list-head ) swap stash ! -- store prev head in link fld of elem
pop ( elem ) pop ( list ) ! -- store addr of elem in list
;
: uncons ( list -- elem )
-- Destructively remove the first elem of list
dup @ ( list elem )
push ( list )
dup @ @ swap !
pop
;
-- Date, time and decimal output functions
: leading-zero
9 le? if '0' putc endif
;
: explode-time ( t -- h m s )
60 divmod push
60 divmod push
pop pop
;
: puttime ( t -- )
explode-time
push push
dup leading-zero putn ':' putc
pop dup leading-zero putn ':' putc
pop dup leading-zero putn
;
146097 constant: 4Centuries
36524 constant: 1Century
1461 constant: 4Years
365 constant: 1Year
153 constant: 5Months
1600 constant: BaseDate
: _make-year ( 4cs 1c 4ys 1y 5ms -- ys )
2 eq? if 1+ endif
swap 4 * +
swap 100 * +
swap 400 * +
BaseDate +
;
: _make-month-and-day ( ds -- ms ds )
stash 31 + 5 * 5Months div 2 +
pop over 1+ 5Months * 5 div - 123 +
push
dup 13 ge? if
12 -
endif
pop
;
: explode-date ( date -- y m d )
LilianCorrection 1+ -
4Centuries divmod
4Centuries 1- -> -- Date is Feb 29th of a 400th year
drop 1+ 400 * BaseDate +
2 29
;;
1Century divmod
4Years divmod -- stack: 4cs 1cs 4ys r
4Years 1- -> -- Date is Feb 29th of a 4th year
drop
1+ 4 *
swap 100 * + swap 400 * + BaseDate +
2 29
;;
1Year divmod -- ds: 4cs 1c 4ys 1y r
stash
5Months divmod -- ds: 4cs 1c 4ys 1y 5ms r
drop _make-year pop _make-month-and-day
;
: putdate ( date -- )
explode-date
push push putn '-' putc
pop dup leading-zero putn '-' putc
pop dup leading-zero putn
;
: putd ( decimal -- )
-- TODO: discard low-order zeroes for neatness
putsign
decimal-places @ times
10 divmod swap
repeat
putn
'.' putc
decimal-places @ times
'0' + putc
repeat
;
: pi ( -- d )
s" 3.1415926535898" number drop
;
60 60 24 * * constant: SecondsInADay
1970-01-01 constant: UnixEpoch
3600 constant: Hour
variable: tz
: hour Hour * ;
: GMT ;
: BST 1 hour + ;
' BST tz !
: now ( -- date time )
-- WARNING: time is UTC.
0 SysTime syscall1
tz @ call
SecondsInADay divmod push UnixEpoch + pop
;
: today ( -- date ) now drop ;
: time ( -- time ) now nip ;
: decimal-scaling-factor s" 1.0" number drop ;
: decimal-places
prior: decimal-places !
;
: *d ( n d -- n )
-- multiply a number by a decimal, rescaling
-- the result to the same number of decimal
-- places as n
decimal-scaling-factor */
;
: /d ( n d -- n )
-- ...same for division
decimal-scaling-factor swap */
;
2 decimal-places ;
exception: CouldNotSleep
: nsleep ( s ns -- )
-- sleep for s seconds and ns nanoseconds
push push
0 rsp@ SysNanosleep syscall2
trash trash
if raise CouldNotSleep endif
;
: sleep ( n -- )
-- Sleep for n seconds
0 nsleep
;
: dump-dicts
[ .label puts spc ] push
words peek each
macros pop each
;
: _find-word-for-addr ( addr dict -- entry )
0 -> swap drop ;;
@ push
dup peek gt? if
-- macro suppression to prevent spurious return stack
-- usage warning. TODO remove suppression when if
-- blocks perform correct return-stack counting
-- gymnastics!
drop suppress-macro: pop return
else
pop tail: _find-word-for-addr
endif
;
: find-word-for-addr ( addr -- entry? )
words _find-word-for-addr
;
: trace-line ( addr -- )
stash putx spc
s" in " puts
peek is-anon? if
s" <anonymous area>" puts
else
peek find-word-for-addr
dup putx spc
.label puts
endif
trash nl
;
: backtrace
rsp@
rs-depth times
peek putn spc
dup @ trace-line
1 cell after
repeat
;
( The following macros are wrappers that combine the behaviour of the output
functions (put*) with forcing execution of the immediate code area, based on
the observation that the most common use-case in the repl is evaluating an
expression )
: = ( n -- ) #immediate
-- output a base 10 number
' putn , go
;
: =h ( n -- ) #immediate
-- same for hex
' putx , go
;
: =o ( n -- ) #immediate
-- and octal
8 compile-literal
' putnumber , go
;
: =b ( n -- ) #immediate
-- and binary
2 compile-literal
' putnumber , go
;
: =d ( d -- ) #immediate
-- output a decimal
' putd , go
;
: =date ( date -- ) #immediate
' putdate , go
;
: =time ( time -- ) #immediate
' puttime , go
;
: =z ( zstr -- ) #immediate
' putz , go
;
: =s ( str -- ) #immediate
' puts , go
;
: cancel #immediate
ds0 @ dsp!
reset
;
1 constant: TypeNum
2 constant: TypeXt
3 constant: TypeAddr
4 constant: TypeStr
5 constant: TypeZStr
: is-dict-addr? ( n -- bool )
heap-base-addr here between?
;
: is-type-xt?
dup is-dict-addr? not if drop false return endif
dup @
DoAddr -> drop drop true ;;
DoDoesAddr -> drop drop true ;;
DoConstAddr -> drop drop true ;;
_ -> 1 cell before eq? ;;
;
: get-type
-- heuristically determine the type of value on ToS
;
-- vim:ft=cantilever