-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathsingeli.bqn
1764 lines (1685 loc) · 72 KB
/
singeli.bqn
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
cpu‿libpaths‿configs‿⟨ShowOut,ErrOut,ErrExit⟩ ← •args
tab‿lf←@+9‿10
dig ← '0'+↕10
alph← "_"∾⥊"aA"+⌜↕26
wc ← dig∾alph∾"." # Word characters
oc ← "!$%&*+-/<=>?\^|~" # Operator characters that can stick together
# Source to list of token strings
Tokenize←{
𝕩+↩𝕩(=×lf⊸-)@+13 # Convert CR to LF
𝕩∾↩lf(≠⥊⊣)¯1↑𝕩 # Trailing newline
# Resolve comments and strings
s‿d‿c‿n←𝕩⊸=¨"'""#"∾lf⋄sd←/¨s‿d
g←⍋q←(¯1↓¨sd)∾⊸∾/c ⋄q↩g⊏q # Open indices
e← g⊏( 1↓¨sd)∾⊸∾-⟜»∘⊏⟜(0∾+`c)⊸//n∾1 # Matching close indices
Se←≠(>/⊢)∾⟜≠{(⊏˜𝕨)𝕊⍟(≠○(¯1⊸⊑))𝕩∾𝕩⊏𝕨}⟨0⟩˙ # Find reachable openings
a‿b←((≠𝕩)↑·/⁼(Se q⍋e)⊸⊏)¨q‿e # Open/close masks
k←»≠`ab←a∨b # Token continuation mask
{⟨⊑/𝕩,"Unclosed quote"⟩!0}⍟(∨´)(s∨d)>k∨a
ign←(𝕩∊" "∾tab)∨≠`ab∧c∨n # Ignored characters
# Other stuff
da←»⊸≠«⊸∨»⊸∧𝕩='.' # >1 dots group alone
k∨↩da<∨´(»⊸∧k<𝕩⊸∊)¨wc‿oc # Group names, numbers, and ops
bt←(⌈`↕∘≠׬)k ⋄ xd←𝕩∊dig
k∨↩»⊸∨(»(bt⊏xd)∧𝕩='e')∧(𝕩='-')∧«xd # Negative exponents 12e-3
ts←(n∧b)∨¬k∨ign # Token start mask
lc←(1+/𝕩=lf){(⊢⋈¨𝕩-⊏⟜(0∾𝕨))𝕨⍋𝕩}/ts # Line/column numbers
⟨𝕩⊔˜1-˜(ign>≠`ab∧s∨d)¬⊸×+`ts, 𝕨 Source 𝕩‿lc⟩
}
# Position handler for error reporting
Source ← { 𝕨 𝕊 src‿lc: file←𝕨⊣""
{ pos 𝕊 disp:
r‿c←<˘⍉>pos⊏lc
ErrOut ∾⟨file, ":", •Repr 1+e←¯1⊑r, ":"⟩
ErrOut src/˜(src=lf)(⊣<+`⊸=)e
Tr ← {
e ← (+`(𝕩≤¯1»𝕨≠⊸+¨𝕩))⊔𝕩⋈¨𝕨
l ← "^"⌾(1⊑¯1⊑⊑) ⌽ "|"⌾(1⊸⊑)¨⊸∾` (1+≠e)↑e
{∾((-⟜»𝕨)∾≠¯1⊑𝕩)↑¨""<⊸∾𝕩}˝∘⍉∘>¨ l
}
ErrOut¨ ¯1↓⍟(∧´' '=⊑) disp Tr○((r=e)⊸/) c
}
}
DispSource ← @⊸≢◶⟨ErrOut¨∘"(unknown position!)"‿"", {𝕎𝕩}´⟩
Err ← { (𝕩≠⊸⥊ErrOut‿DispSource) {𝕎𝕩}¨ 𝕩 ⋄ ErrExit@ }
AsrtGotGen ← {𝕊 disp: {𝔽𝕩 ? 𝕩 ; !∾⟨𝕎𝕩," (got ",Disp𝕩,")"⟩}}
_asrtGotR‿_asrtGotS ← AsrtGotGen¨ •Repr‿{Show𝕩}
# Parameter checks for builtins (_p1 and _p2 to use BQN monad/dyad)
_e1 ← {𝔽⊣"Expected one parameter" 1⊸=_asrtGotR ≠} ⋄ _p1←{𝔽⊑_e1}
_e2 ← {𝔽⊣"Expected two parameters" 2⊸=_asrtGotR ≠} ⋄ _p2←{𝔽´_e2}
_e3 ← {𝔽⊣"Expected three parameters" 3⊸=_asrtGotR ≠}
_v1 ← {𝔽⊣"Expected at least one parameter" 1⊸≤_asrtGotR ≠}
_v2 ← {𝔽⊣"Expected at least two parameters" 2⊸≤_asrtGotR ≠}
# Error messages for generator matching
ErrParams ← { ErrOut 𝕨 ⋄ ! "Parameters: "∾(0<≠)◶⟨"none",ShowMulti⟩ 𝕩 }
_errNoMatch ← { ((∾⟜": "⍟(0<≠)𝕨)⊢⊘∾"No matching "∾𝕗) ErrParams 𝕩 }
numbers ← {kname⇐"number"
f ← •Import "float2.bqn"
NN ← 1≠•Type # Not native number
Is ← kname≡{Kind𝕩}
Wrap ← {
kind⇐kname⋄value⇐𝕩⋄Matches⇐Match⋄Shows⇐FmtLarge∘𝕩
Matchable ⇐ {𝕊:matchable↩(0≠⊢´)◶⊑‿<value} # Matches as hi or <hi‿lo
}
Unwrap ← {
6=•Type𝕩 ? kname≡𝕩.kind ? 𝕩.value ;
(𝕨⊣"Expected constant number") 0 _asrtGotS 𝕩
}
Promote ← NN◶f.To‿Unwrap
GetFloat ⇐ f.From∘Unwrap⍟(NN⊢)
_getter_ ← {(𝕘∾" expected")⊘⊣ 𝔽_asrtGotR GetFloat}
GetBool ⇐ ⊑∘∊⟜0‿1 _getter_ "Boolean"
GetNat ⇐ |∘⌊⊸= _getter_ "Natural number"
GetInt ⇐ ⌊⊸= _getter_ "Integer"
Match ⇐ ∧○Is◶⟨0,≡○Promote⟩
_cn ← {𝔽 ⊣ "Ill-formed number"!·∧´'0'⊸≤∧≤⟜'9'}
Nat ← •ParseFloat _cn
LC ← +⟜(32×1="A["⊸⍋) '_'⊸≠⊸/ # Lowercase, underscores removed
da ← dig∾'a'+↕26
Read ⇐ {
(≠𝕩)>s←⌊´𝕩⊐"bx" ? # Base n with 0x9abc or 31bNUMBER
b ← ('b'=s⊑𝕩)◶⟨16⊣"x can only appear in 0x in a number"!"0"⊸≡,Nat⟩ s↑𝕩
"Invalid base (min 2)" ! 2≤b
(!"Invalid base (max "∾•Repr∾")"˙)⍟(b⊸>) ≠da
d ← b 𝕎 (b↑da) (≠∘⊣(⊢⊣"Invalid digits"!∧´∘>)⊐) (1+s)↓𝕩
E ← b⊸×⊸+˜´⌽∘⊢
EE ← {h‿l←f.To∘E¨𝕨-⊸(↓⋈↑)𝕩⋄Wrap l f.Add (f.To b⋆𝕨)f.Mul h}
(⌊53÷2⋆⁼b) <⟜≠◶E‿EE d
;
_n ← {('-'=⊑)◶⟨𝔽, -∘𝔽 1⊸↓⟩}
pe ← ⊑𝕩⊐'e' ⋄ e ← pe (2⌊-˜⟜≠)◶⟨0,!∘"Empty exponent",Nat _n+⟜1⊸↓⟩ 𝕩
m ← pe↑𝕩 ⋄ m /˜↩ ¬dm←m='.'
(0≠⊢´)◶⟨⊑,Wrap⟩ (e - (≠m)-⊑dm⊐1)⊸f.ParseDec _cn _n 10 𝕎 m
}{
# Pass digit repeater as 𝕎
∨´m←𝕩∊c←"rdw" ? # r repeat; d total digits; w total bits
∨´m>↩∨`𝕩∊"bx" ? # Not part of the digit stream
f ← {(𝕩×≠)⊸Re⊢}‿{𝕩⊸Re}‿{𝕩_wf} ⋄ Re←{𝕨⊸⥊⌾⌽𝕩}
"Empty segment after digit repetition prefix"!¬∨´m∧1«m
p ← 𝕩⊔˜(¬×1+`⊢)m # ⟨codes, ...counts, rest⟩
n ← Nat¨ ¯1↓1↓p # Parsed counts
wfm←"Repetition with w requires the base to be a power of two"
_wf←{b n _𝕣 𝕩: wfm!⌊⊸=l←2⋆⁼b ⋄ (l|n) 2⊸⋆⊸|⌾⊑⍟(≠⟜0) (⌈n÷l) Re 𝕩 }
rep←{∧´0=n ? "0" ; # 𝔽 assumes >0 digits
mm←"Digit repetition prefixes don't agree"
(1<≠)◶⊑‿{(⊑⊣mm!⊣`⊸≡)𝕩{𝕨𝕩{𝕨𝕏𝕗}¨𝕗}} n{𝕎𝕩}¨˜f⊏˜c⊐⊑p
}
rep 𝔽 ⊢´p
;
{⊢} 𝔽 𝕩
}⟜LC⎊{Err⟨•CurrentError@,𝕨⟩}
InRange ← {1=⊑0⍋˜-˜´⟜(⌽𝕨)¨𝕩}
FmtFloat ← ('¯'(⊢+=×'-'-⊣)•Repr){(∞>|)◶⟨"/0"∾˜·𝔽0(<->)⊢,𝔽⟩}
MakeFmt ← {𝕊 Abs‿InRange‿ToSmall‿ToLarge: {
⌊⊸≡𝕩 ? (a←Abs 𝕩) InRange 2⋆48‿64 ? 𝕩 InRange -⌾⊑2⋆63‿64 ?
((𝕩≢a)/"-")∾"0x"∾da⊏˜⌽ 16‿16 f._repr ToLarge a ;
FmtFloat ToSmall 𝕩
}}
FmtSmall‿FmtLarge ← MakeFmt¨ ⟨
⟨|, 1=⊑∘⍋˜, ⊢, f.To⟩
⟨f.Abs, InRange, f.From, ⊢⟩
⟩
Fmt ⇐ FmtSmall
Cast ⇐ {'f'‿l𝕊n:1; q‿l𝕊n: # 1 if valid; error otherwise
n NN◶⋈‿Unwrap↩ ⋄ a←AsrtGotGen {•Repr+´}
"Can't cast float to integer" ⌊⊸≡_a n
"Constant doesn't fit" (n InRange -⟜(1⊸⊑÷2˙)⍟(q='i') ⟨0,2⋆l⟩)_a n
}
_cmp ⇐ {(f.Cmp 𝔽 0˙)○Promote}
builtins ⇐ {
W←Wrap ⋄ P←{𝕊:Promote𝕩 ; 𝕊⁼:W𝕩}
E←f.To 2⋆GetFloat
# B gives ⟨sign, 2's complement bits⟩
Comp←(f.To ¯1)⊸f.Sub ⋄ IsNeg←0>f.Cmp⟜(f.To 0)
B←≠`∘(f.Bits∘{𝕊⁼:𝕨𝕊𝕩;𝕊:Comp⍟𝕨𝕩}`)∘{𝕊⁼:1⊑𝕩;𝕊:⟨IsNeg𝕩,𝕩⟩}∘P
[pr,val] ← ⍉[
({NN◶⟨𝕎,W∘𝕏○Unwrap⟩}´)‿⟨"neg"‿⟨-,f.Neg⟩, "abs"‿⟨|,f.Abs⟩,
"floor"‿⟨⌊,f.Floor⟩, "ceil"‿⟨⌈,f.Ceil⟩⟩
⊢ ‿⟨"not"‿(¬GetBool)⟩
{𝕏⌾P} ‿⟨"add"‿f.Add, "sub"‿f.Sub, "mul"‿f.Mul, "div"‿f.Div, "mod"‿f.Mod⟩
{⊣⍟(𝕏_cmp)}‿⟨"min"‿≤, "max"‿>⟩
{W P⊸𝕏⟜E} ‿⟨"shl"‿f.Mul, "shr"‿(f.Floor f.Div)⟩
{𝕏⌾B} ‿⟨"and"‿∧, "or"‿∨, "xor"‿≠⟩
]
arg ← 2‿4/{𝕏_p1}‿{𝕏_p2}
⍉>∾ (arg {𝕎∘{𝕏⚇0}∘𝕏}¨ pr) {⟨"__"⊸∾,𝕎⟩⊸({𝕎𝕩}¨)¨𝕩}¨ val
}
}
ptrWidth ← cpu.width
architecture ← {
feats‿mat‿FeatInd ← cpu
init ⇐ cpu.baseArch
# Look up a list of symbols
Id ← {𝕨 FeatInd "Expected symbol for architecture feature"⊸symbols.From¨𝕩}
# An architecture is a mask of supported features
New ⇐ { 𝕨 ∨˝ (1 Id 𝕩) ⊏ mat }
Contains ⇐ ∧´≥
Intersect ⇐ ∧ ⋄ Union ⇐ ∨
Has ⇐ ∧´{(0 Id 𝕩)⊏𝕨∾0} # Has all in list 𝕩
List ⇐ /⟜feats
ListExt ⇐ List init⊸<
# Architecture to be used for the next function created
next ← init
SeeNext ⇐ {𝕊:next}
NewFunction ⇐ {𝕊: r←next ⋄ next↩init ⋄ r }
With ⇐ { NewFunction ⊢ (⊑𝕩){𝔽} ⊣ {next↩𝕩}∘(New 1↓𝕩) }_v1
}
MakeStack ← {𝕤
st←@ ⋄ d←0
Push⇐{ st↩𝕩‿st ⋄ d+↩1}
Pop ⇐{𝕤⋄ r‿s←st ⋄ st↩s ⋄ d-↩1 ⋄ r}
Arr ⇐{𝕤⋄ ⊑¨ ⌽ 1⊸⊑⍟(↕d) st}
_while_⇐{Pop ⊢ 𝔽 ⊣ ·Push𝕘˙}
}
MakeStream ← {
len←≠src←𝕩 ⋄ i←0
Pos ⇐ {𝕤⋄i}
Inc ← {𝕤⋄i+↩1}
Rem ⇐ {𝕤⋄i<len}
Peek ⇐ {𝕤⋄i⊑src}
Next ⇐ Inc ⊢ Peek
Dec ⇐ {𝕤⋄i-↩1}
}
Parse ← {𝕊 tokens‿ShowTrace:
sep ← ⟨";", ⥊lf⟩
! ⊑ (¯1⊏tokens) ∊ sep
keywords ← "include"‿"config"‿"local"‿"if"‿"if_inline"‿"else"‿"while"‿"do"‿"match"‿"extend"‿"def"‿"fn"‿"main"‿"oper"‿"in"‿"over"‿"from"‿"to"‿"and"‿"or"‿"not"
kInclude ‿kConfig ‿kLocal ‿kIf ‿kIf_inline ‿kElse ‿kWhile ‿kDo ‿kMatch ‿kExtend ‿kDef ‿kFn ‿kMain ‿kOper ‿kIn ‿kOver ‿kFrom ‿kTo ‿kAnd ‿kOr ‿kNot ← ↕≠keywords
Asrt ← {𝕨𝕊1:@;
[v, k] ← (<"") ∾˘´ {𝕩⊸•ns.Get¨⊸≍ •ns.Keys 𝕩}¨ c‿tc
ShowTrace⟜(v⊸⊐ ⊏ k˙)´ <˘⍉>DumpStack@
ErrOut ""
F ← (⥊lf)⊸≢◶⟨"end of line", =◶⟨"keyword "∾•Repr∘⊑⟜keywords, •Repr⟩⟩
ErrOut {∾"Expected "‿𝕨‿" but saw "‿𝕩}⟜F´⍟(1<≡) 𝕨
ErrExit@
}
MakeTokStream ← {
i←⊐𝕩 ⋄ u←keywords{𝕗⊸⊐⊣⍟(<⟜(≠𝕗))¨⊢}𝕩/˜i>¯1»⌈`i
⟨Inc⇐Next,PeekRaw⇐Peek⟩←⟨Pos,Rem,Back⇐Dec⟩⇐MakeStream i
PeekRaw ↩ PeekRaw ⊣ "File ended unexpectedly" Asrt Rem
Peek ← ⊑⟜u∘PeekRaw
Try ⇐ 1∘Inc⍟⊢ Peek⊸≡
Get ⇐ Inc (•Repr⊸⋈ Asrt 0˙)⍟≢⟜Peek
# Faster tests on raw tokens
_test ⇐ {(𝔽¨u)⊑˜PeekRaw}
first←⊑¨u
_begin_ ⇐ {t←𝔽 first ⋄ Inc ⊢ (⊑⟜u (⊣ ⊣ 𝕘⊸⋈⊸Asrt) ⊑⟜t)∘PeekRaw}
GetS ← ⊢ {Inc (((•Repr𝕨)⋈⊑⟜u) Asrt 0˙)⍟(𝕩⊸≢)∘PeekRaw}¨ u⊸⊐
_seq ⇐ {a←3≠•Type¨𝕗 ⋄ (¬a)/{𝕏@}¨∘(GetS⌾(a⊸/)𝕗) }
_opt_ ⇐ {@_𝕣_𝕘:
t‿c ← (1⌾(¯1⊸⊑)2|↕∘≠)⊸⊔ 𝕘
exp ← "one of "∾∾⟜", "⊸∾´•Repr¨t
(⊑(u⊐t)⊐PeekRaw)◶(c∾⟨(exp⋈Peek) Asrt 0˙⟩)
}
_optGet_ ⇐ {@_opt_({𝕏⊣Inc}¨⌾((2|↕∘≠𝕘)⊸/)𝕘)}
_any ⇐ {⊑(u⊐𝕗)∊˜PeekRaw}
_anyTry ⇐ {1∘Inc⍟⊢∘(𝕗_any)}
}
⟨Get,Try,Rem,Pos,Back,_test,_begin_,_seq,_opt_,_optGet_,_anyTry,_any⟩ ← MakeTokStream tokens
# Node creation and error tracking
c ← nodes ⋄ tc ← targetNodes
⟨_whileParse_⇐_while_, DumpStack⇐Arr⟩ ← MakeStack@
_node_ ← {p←Pos@ ⋄ (ShowTrace○⋈⟜""⊢)‿p 𝔽 𝔾_whileParse_⟨p,𝕗⟩ 𝕩}
AsrtHere ← {𝕨 Asrt _whileParse_ ⟨Pos@,""⟩ 𝕩}
When ← {Test‿Cont: ( ⥊∘< Cont)⍟Test ⟨⟩ }
While ← {Test‿Cont‿init: {(𝕊∾⟜<⟜Cont)⍟Test𝕩} Cont¨↕init}
_ifASCII ← {(@+128)⊸≤∨𝔽}
Name ← ∊⟜alph _begin_ "name"
Oper ← ∊⟜oc _ifASCII _begin_ "operator"
Symbol ← c.symbol _node_ ('''⊸=_begin_"symbol")
IsLogic ← ∊⟜kAnd‿kOr‿kNot
LFs ← {𝕊⍟Try ⟨lf⟩}
Div ← {LFs@ ⋄ 1∘LFs⍟⊢ Try 𝕩} # Divider, allowing surrounding newlines
TrySep ← sep _anyTry
Seps ← {Rem@ ? TrySep@ ? 𝕊𝕩⋄1 ; 0}
_decl_ ← { 𝔽"Declaration" ⋄ Declare 𝔾 𝕩 }
_exprStmt ← {AsrtStmt _𝕣: @_opt_⟨
kIf, { StIf 𝕩 }
kWhile, { StWhile 𝕩 }
kDo, { DoWhile 𝕩 }
kMatch, { Options 𝕩 }
"@", { For 𝕩 }
kExtend, { Extend 𝕩 }
kDef, { Define 𝕩 } ⊣ AsrtStmt∘"def"
kFn, { DefFun 𝕩 } ⊣ AsrtStmt∘"fn"
kMain, { DefMain𝕩 } ⊣ AsrtStmt∘"main"
kOper, { OpDef 𝕩 } ⊣ AsrtStmt∘"oper"
"{", @_optGet_⟨"=>", c.lambda _node_ (⋈⟜{Block𝕩})
":", AsrtStmt _decl_ ⊢ ⟩ {Params𝕩}
{ AsrtStmt _decl_ ToId⍟(Try":") SimpExpr 𝕩 }
⟩}
Expr ← (∾⟜" must appear on its own line" Asrt 0˙) _exprStmt
Stmt ← ⊢ _exprStmt
Vec ← c.run _node_ (c.consts.vec ⋈ "["‿Expr‿"]"‿{Callable𝕩} _seq)
ParEx ← ⊑ "("‿Expr‿")" _seq
EWord ← c.token _node_ (⊑⟜keywords⍟(¬=) (IsLogic∨∊⟜('''∾wc∾oc)_ifASCII) _begin_ "expression")
Expr0 ← @_opt_⟨"[",Vec, "(",ParEx, EWord⟩
_spreadable ← {<∘⊢⍟⊣⟜𝔽∘Try∘"..."}
_args ← {𝕗 _argsFn_ (Expr _spreadable)}
_divList ← {Div∘"," _and_ (𝕗⊸≢_test)}
_argsFn_ ← {𝕤
Get ⊑𝕗
LFs@
Try 1⊑𝕗 ? ⟨⟩ ;
a ← While ⟨(1⊑𝕗)_divList, 𝔾, 1⟩
Get 1⊑𝕗
a
}
NoPar ← (sep∾","‿"}")_any
ParC ← {𝕤 # Parameter in call
s ← Try "..."
p ← s◶⟨Try∘".", NoPar⟩ @ # Partial application
<⍟s Expr⍟(¬p) @
}
err_ex_gather ← "At most one variable-length parameter allowed"
ParCs ← ⊢ ⋈ · (err_ex_gather Asrt 1≥·+´(<@)⊸≡¨)⊸⊢ "{"‿"}"_argsFn_ ParC
AddParams ← @_opt_⟨"{", {AddParams∘(c.run _node_ ParCs ) 𝕩}, ⊢⟩
AddArgs ← @_opt_⟨"(", { (c.call _node_ (⊢⋈"("‿")"_args)) 𝕩}, ⊢⟩
Callable ← AddParams∘Expr0
CanCall ← (¬ =◶⟨IsLogic⌾<, ∨´(oc∾"[")=⊏⟩) _test
StartsOp ← =◶⟨IsLogic⌾<, ⊑∘∊⟜oc _ifASCII∘⊑⟩ _test
Call ← { c←CanCall @ ⋄ AddArgs⍟c Callable𝕩 }
ExprFromEnd ← {𝕊 endTok:
End ← (endTok∾sep∾⥊¨",:)}]")_any
{
o ← StartsOp 𝕩
Cont ← {p←o ⋄ p∨o↩StartsOp 𝕩}_and_(¬End)
c.phrase _node_ (While∘⟨Cont, Call, 1⟩) 𝕩
}
}
SimpExpr‿TypeExpr ← ExprFromEnd¨ ⟨⟩‿⟨"="⟩
# 𝕩 is the expression preceding ":"
Declare ← c.declare _node_ {
n ← 𝕩
t ← When ⟨¬Try"=", Get∘"=" ⊢ TypeExpr⟩
⟨n,t,Expr@⟩
}
ToId ← {"Unexpected "":"""AsrtHere@≢𝕩 ⋄ 𝕩.IsDef@⋄𝕩} c.PhraseTryWord
_lines_ ← { Line _𝕣_ Cont 𝕩:
Seps @ ⋄ s ← 1
SepLine ← {"Expected separator" AsrtHere s ⋄ l←Line𝕩 ⋄ s↩Seps@ ⋄ l}
While ⟨Cont, SepLine, 0⟩
}
_blockLines ← { ⊑ ⟨"{", 𝔽 _lines_ (¬Try∘"}")⟩_seq }
Body ← Stmt _blockLines
Block ← @_opt_⟨"{",c.body _node_ Body, Expr⟩
AnyIf ← ⟨kIf, kIf_inline⟩_anyTry
_if ← {
TrySeps ← {s←Seps@ ⋄ Back⊸⊢⍟(s>⊢) Rem◶0‿Try 𝕩}
1↓ AnyIf‿"("‿Expr‿")"‿𝔽‿(When∘⟨TrySeps∘kElse,𝔽⟩)_seq
}
StIf ← c.if _node_ (Block _if)
StWhile ← c.while _node_ (1 ∾ kWhile‿"("‿Expr‿")"‿Block _seq)
DoWhile ← c.while _node_ (0 ∾⟜⌽ kDo‿Block‿kWhile‿"("‿Expr‿")" _seq)
Options ← c.options _node_ {𝕤
Get kMatch
a ← @_opt_⟨"(", ⋈"("‿")"_args, ⟨⟩⟩ @
m ← c.lambda _node_ (Params‿"=>"‿Block _seq) _blockLines @
a‿m
}
For ← c.for _node_ {𝕤
OA← "@for: pointers must be followed by ""over"""⊸AsrtHere
OW← •Out∘"@for: pointer without ""over"" is deprecated"⍟¬
TA← "@for: ""from"" missing ""to"""⊸Asrt
NA← "@for: loop variable must be a name"⊸Asrt
Get "@"
f ← Callable@
Get "(" ⋄ LFs@
to← Expr@
NE← {𝕤⋄ n←⋈∘{NA@≢𝕩⋄𝕩}∘c.PhraseTryName⍟𝕩 to ⋄ to↩Expr@ ⋄ n}
{Div kIn? to↩⟨⊑NE 1,to⟩; @}
pe← While ⟨Div∘",", Div∘kIn◶⟨⋈,⋈⟜Expr⟩ Name, 0⟩
ps← {Div kOver?(<NE 0==to)∾𝕩; OA 0=≠𝕩⋄OW 0==to⋄⟨⟩} pe # Pointers
fr← When ⟨Div kFrom, Expr⟩ # Start index
i ← {¬Div kTo?TA 0=≠fr⋄⟨⟩; 0<=to?ps∾↩<NE 0⋄⟨⟩; NE 1} # Index variable
LFs@ ⋄ Get ")"
b ← Block@
⟨f,ps,i,fr,to,b⟩
}
# 𝕩 indicates if preceding token was =
Result ← c.body _node_ (@_opt_⟨
"{", Body
"@", ⋈For
⋈∘Expr "Missing = before body?"Asrt⊢
⟩)
TargetList ← tc.list _node_ {𝕤
Get "{"
LFs@
a ← {
∊⟜"}"‿kIf⌾<_test@ ? 0⥊<↕2 ;
Param ← ⟨Try∘"...", TargetElem⟩_seq
a ← While ⟨"}"_divList, Param, 1⟩ ⋄ err_ex_gather Asrt 1≥+´⊑¨a ⋄ a
}
c ← When ⟨Try∘kIf, Expr⟩
Get "}"
a‿c
}
# Target operations * : = == are all right-associative
# 𝕩≡0 indicates = should not be parsed
TargetElem ← =◶⟨0, ∧´'*'⊸=⟩_test◶⟨ # Multiple *s group as one token
{ (𝕩≡0)◶FinishTarget‿FinishDefTarget TargetAtom 𝕩 }
tc.pointer _node_ {𝕤
a ← '*'⊸=_begin_"" @
tc.pointer⍟(1-˜≠a) TargetElem 𝕩
}
⟩
TargetAtom ← @_opt_⟨
"(", tc.constant _node_ ParEx
"[", tc.vector _node_ {"["‿TargetElem‿"]"‿(TargetElem∘𝕩) _seq @}
"{", TargetList
=◶⟨0, ⊑⊏∊(dig∾''')˙⟩_test◶⟨tc.name _node_ Name, tc.constant _node_ EWord⟩
⟩
noDestruct ← "Type destructuring would shadow primitive type; add parentheses to use as constant"
TypeTarget ← TargetElem ⊣ noDestruct Asrt ¬∘∊⟜(types.primTypes≠⊸↑builtins.names)⌾<_test
_tAdd_ ← {@_opt_(⟨⊢⟩∾˜⥊{s‿n‿P: ⟨s, n _node_ (⋈⟜P ⊣ Get∘s)⟩}˘∘‿3⥊𝕘)}
FinishTarget ← @_tAdd_⟨kIf, tc.conds, Expr⟩ @_tAdd_⟨
":", tc.typed, TypeTarget
"=", tc.same, TargetElem
"==", tc.equals, Expr
⟩
# Can't handle = or expressions containing it; don't allow == out of caution
FinishDefTarget ← @_tAdd_⟨kIf, tc.conds, TypeExpr⟩ @_tAdd_⟨
":", tc.typed, TypeTarget∘0
⟩
Params ← c.target _node_ TargetList
_withParams ← {
Rec ← @_opt_⟨"{",c.lambda _node_ (Params‿{Rec𝕩} _seq), 𝔽⟩
}
IdTarget ← c.newId _node_ Name
Target ← c.target _node_ (TargetElem∘0)
Arg ← c.arg _node_ ((Try∘"...")‿Name‿":"‿Expr _seq)
Function ← c.function _node_ {𝕤
a ← "("‿")" _argsFn_ Arg @
r ← When ⟨Try":", TypeExpr⟩
b ← Result Try"="
⟨a,r,b⟩
} _withParams
DefFun ← c.define _node_ (kFn‿IdTarget‿Function _seq)
DefMain ← c.main _node_ {𝕤
Get kMain
a ← @_opt_⟨"(","("‿")" _argsFn_ Name, ⟨⟩⟩ @
"Main function can have at most two arguments" Asrt 2≥≠a
RT ← "Main result must be void or i32" AsrtHere ∊⟜"void"‿"i32"⌾<
r ← When ⟨Try":", RT⊸⊢ Name⟩
b ← Result Try"="
⟨a,r,b⟩
}
ExtPar ← "{"‿"}" _argsFn_ Name
Extender ← c.extender _node_ (ExtPar‿"="‿Body _seq)
Extend ← c.extend _node_ (kExtend‿Expr0‿ExtPar _seq)
GenRes ← ⊑⟨"=",Result∘1⟩_seq
Value ← @_opt_⟨"=",GenRes, @⟩
Generator ← @_opt_⟨"{",GenRes _withParams, Value⟩
# Decide how to parse definition value based on what's after def
Valuator ← @_optGet_⟨kExtend,Extender˙, @_opt_⟨"{",Value˙,"_",Value˙,Generator˙⟩⟩
Define ← c.define _node_ {𝕤
Get kDef
v ← Valuator @
⟨Target, V⟩_seq @
}
confName‿confVal ← (⊑¨⋈1⊸⊑¨)configs
Config ← c.define _node_ {
Get kConfig
t‿r ← ⟨IdTarget, "=", Result∘1⟩_seq 𝕩
n ← t.name
t‿{ (≠confName) > i←confName⊸⊐⌾<n ? ("config "∾n) ast.Build i⊑confVal ; r }
}
OpType ← @_optGet_⟨
"prefix", 'p'
"infix", @_optGet_(⟨'n'⟩∾˜∾⋈⟜⊑¨"none"‿"left"‿"right")
⟩
Number ← c.number _node_ (∊⟜dig _begin_ "number")
OpName ← @_opt_⟨"(",ParEx, Name⟩
OpDef ← c.opDef _node_ (kOper‿Oper‿OpName‿OpType‿Number _seq)
Include ← c.include _node_ (kInclude‿Symbol _seq)
MultiLine ← {Line𝕩} _blockLines
TopIf ← c.topif _node_ (∾⌾(¯1⊸⊑) @_opt_⟨"{",MultiLine, ⋈{Line𝕩}⟩ _if)
SubLine ← @_opt_⟨kInclude,Include, kIf_inline,TopIf, kConfig,Config, Stmt⟩
LocLine ← @_opt_⟨kIf_inline,"localizable line"‿kIf_inline AsrtHere 0˙, kIf,StIf, SubLine⟩
Line ← @_optGet_⟨
kLocal, @_opt_⟨"{",c.body _node_ MultiLine, LocLine⟩
{𝕩.NonLocal@⋄𝕩}∘SubLine
⟩
Program ← c.body _node_ (Line _lines_ Rem)
Program @
}
operator ← {
Parse ⇐ {
⟨op⟩ 𝕊 ⟨v⟩: v⊣´{𝕩.V v.pos}¨@⊸≢¨⊸/op.left‿op.null ;
ops 𝕊 val:
Peek‿Next‿Rem ← st ← MakeStream ops {null‿left‿bind‿R⇐𝕨 ⋄ value⇐𝕩}¨ val
E ← {𝕊test: {𝕊∘{𝕩 LeD Next@}⍟(Test Peek)⍟Rem 𝕩} NuD Rem◶Mis‿Next@ }
Run ← nodes.Run ⋄ P ← {𝕩.value.pos}
NuD ← { 𝕩.null ≢⟜@◶{𝕩.value}‿{pos←P𝕩 ⋄ pos Run ⟨𝕩.R 𝕨.V pos, ⟨E 𝕨.t⟩⟩} 𝕩 }
LeD ← { @≢l←𝕩.left ? pos←P𝕩 ⋄ pos Run ⟨𝕩.R l.V pos, ⟨𝕨, E l.t⟩⟩ ; Unk 𝕩.value }
IsOp ← {"cond_oper"≡𝕩.node?1; "word"≡𝕩.node?∊⟜oc⌾<⊑𝕩.name?1; 0}
Unk ← {
¬IsOp 𝕩 ? st.Dec⍟2@ ⋄ Err "Unknown prefix operator"‿(Next@).value.pos ;
Rem@ ? Err "Unknown infix operator"‿𝕩.pos ; Mis@
}
Mis ← {𝕊: Err "Missing right operand"‿(¯1⊑val).pos }
E 1
}
Run ⇐ {𝕨𝕊⟨op,params⟩:
Par ← 𝕨 nodes.Run ⋈⟜params
null‿left ⇐ {⟨T⟩⇐𝕩 ⋄ V⇐Par∘𝕩.V}⍟(@⊸≢)¨ op.null‿op.left
bind‿R⇐op
}
Compose ← {pre𝕊in: ⟨null⟩⇐pre ⋄ left‿bind⇐in ⋄ R⇐⊢ }
nil ⇐ { null⇐left⇐@ ⋄ bind⇐¯∞ ⋄ R⇐⊢ }
Tab ⇐ { par 𝕊 new:
p←n←o←⟨⟩ # pos, name, output
Ind ← { n⊸⊐⌾<𝕩 }
Add ⇐ {
i ← Ind 1⊑𝕩
i<≠n ? Err⟨"Duplicate operator definition:",⊑𝕩,"Previously defined here:",i⊑p⟩ ;
p‿n‿o ∾⟜<¨↩ r←(1⊑𝕩)⊸New⌾(2⊸⊑)𝕩 ⋄ 2⊑r
}
Get ⇐ { i←Ind𝕩 ⋄ (i=≠n)◶⟨i⊑o˙,par.Get⟩ 𝕩 }
}
NewScope ⇐ {
parent ⇐ 𝕩
Op ← {name 𝕊 V‿p‿c‿a: V⇐
AC ← { Err ("Associativity for operator "∾name∾" must be disambiguated")‿𝕨.value.pos }⍟(0⊸>)
T ⇐ (p C {𝕩.bind}){{⊣AC𝕏}⍟a𝕗}
}
tabs ⇐ nul‿lef ← parent.tabs Tab¨ ⟨
{𝕨𝕊⟨value, prec⟩: null ⇐ 𝕨 Op ⟨value, prec, <, 0⟩ }
{𝕨𝕊⟨value, prec, assoc⟩:
bind ⇐ prec
left ⇐ 𝕨 Op ⟨value, prec, ("lrn"⊸⊐⌾<assoc)⊑⟨<,≤,<-=⟩, 'n'=assoc⟩
}
⟩
Add ⇐ {𝕨𝕊type‿name‿value‿prec:
l←type≠'p'
(l⊑tabs).Add ⟨𝕨, name, value‿prec∾l⥊type⟩
}
Lookup ⇐ nul.Get Compose lef.Get
# include statements also resolved in the operator pass
includes←⟨⟩ ⋄ AlreadyIncluded⇐{∊⟜includes⌾<𝕩 ? 1 ; includes∾↩<𝕩⋄0}
}
nilScope ⇐ { tabs ⇐ 2⥊{Get⇐nil˙} } # Lookup ⇐ nil˙
}
# Runtime
# Kinds are:
# - BQN values tuple (list), number, generator (function)
# - Classes symbols, types, registers, constants, functions, blocks
_and_ ← { 𝔽◶⟨0,𝔾⟩ }
IsTup ← 0=•Type
IsGen ← 3=•Type
_tsel ← {•Type∘⊣◶(¯1((↓»(6⥊⟨!∘"Unhandled kind"⟩)˙)∾↑)𝕗)}
Kind ← ⟨"tuple","number",@,"generator",{𝕩.kind}⟩_tsel
Match ← {𝕨 ⟨≡○≢◶⟨0,∧´𝕊¨⟩, numbers.Match,≡,≡, {𝕨𝕨.Matches𝕩}⟩_tsel 𝕩}
# p Matches q if and only if p ≡○GetMatchable q
GetMatchable ← ⟨{GetMatchable¨ 𝕩}, ⊢,!,⊢, {⟨M⇐Matchable⟩:M@; !{≡}≡𝕩.matches⋄𝕩}⟩_tsel
IsTyped←∊⟜"register"‿"constant"‿"function"⌾< Kind
HasType ← IsTyped∘⊣ _and_ ({𝕩.type}⊸Match)
TypeOf← {⟨types.Tup 𝕊¨, {𝕩.Type@}⟩_tsel 𝕩}
Show‿Repr ← {
UnEsc ← ⊢-128×(' '+128)⊸= # Non-breaking space to space
FmtTup ← "tup{"∾"}"∾˜1↓·∾","⊸∾¨
FmtFn ← {(𝕏˜@).name}⎊"(generator)"
ReprObj ← {𝕩.Shows@}
ObjType ← IsTyped◶0‿{𝕩.fmtType}◶""‿{":"∾Repr TypeOf𝕩}
_ko ← {𝔽≡{𝕩.kind}}
ShowSub ← "type"_ko◶ReprObj‿{𝕩.TypeShow@}∾ObjType
ShowObj ← ShowSub⎊("error"_ko⎊0◶("("∾")"∾˜Kind⎊"unknown")‿ReprObj)
EChar ← "(char "∾•Repr∘-⟜@∾", probably bug)"˙
_disp_ ← {R←⟨FmtTup {R𝕩}¨, numbers.Fmt, 𝔾, FmtFn, 𝔽⟩_tsel}
Show ⇐ UnEsc ShowObj _disp_ EChar
Repr ⇐ ReprObj _disp_ !
}
ShowMulti ← 2↓·∾·", "⊸∾¨Show¨
_genNamed_ ← {N←{n↩𝕩}∘{name⇐𝕩}∘𝔾⋄𝔽⊘{𝕨N𝕩}}
types ← {kname⇐"type"
New ← {k𝕊d:
kind⇐kname
typeKind‿dat⇐𝕨‿𝕩
Shows‿TypeShow⇐{𝕏∘dat}¨typeKind⊑dispfns
Matches⇐{𝕨Is∘⊢◶0‿Equiv𝕩}
Matchable⇐{𝕊:matchable↩<⟨'t',TypeShow@⟩}
}
tVOID‿tPRIM‿tVEC‿tPTR‿tFUN‿tTUP ← ↕6
TypeKind⇐{
ReqTyp 𝕩
𝕩.typeKind⊑"void"‿"primitive"‿"vector"‿"pointer"‿"function"‿"tuple"
}
dispfns ← {
_v ← {{∾"["‿𝕨‿"]"‿𝕩}○𝔽´} # Vector
_t ← {1↓·∾(","⊸∾⍟(0<≠)𝔽)¨} # Type tuple, bare
_tt← {"tuptype{"∾"}"∾˜𝔽_t} # and for display
_f ← {("("∾")"∾˜𝔽_t)⊸{∾𝕨‿"->"‿𝕩}⟜𝔽´} # Function args
{Repr‿Show{d←𝕩⋄𝕨_d}⍟(4=•Type∘⊢)¨𝕩}¨ ⟨
<"void" # Void: void
∾⟜•Repr´ # Primitive: qual‿len u8
_v # Vector: count‿t [4]…
{"*"∾𝔽} # Pointer: t *…
_f # Function: ⟨q‿r‿s, t⟩ (…,…,…) -> …
_t‿_tt # Tuple: q‿r‿s …,…,… / tuptype{…,…,…}
⟩
}
IsVoid ⇐ {tVOID≡𝕩.typeKind}
void ⇐ tVOID New ⟨⟩
primTypes ⇐ void ∾ tPRIM New¨ qw ← ∾⋈¨¨˝⍉ ∘‿2⥊⟨
'u', 2⋆0∾3+↕4 # 1/8/16/32/64
'i', 2⋆ 3+↕4 # 8/16/32/64
'f', 2⋆ 5+↕2 # 32/64
⟩
_getPrim ← {{𝕏@} (⟨!∘𝕗⟩«primTypes) ⊑˜ qw⊸⊐⌾<}
Is ← kname≡Kind
ReqTyp ⇐ {"Expected type";𝕨∾" type wasn't type"˙} Is _asrtGotS ⊢
Vec ← {n𝕊t:
l ← "Vector size should be a constant integer" numbers.GetNat n
"Vector" ReqTyp t
tVEC New ⟨l,t⟩
}
Ptr ⇐ { 𝕊t: "Pointer" ReqTyp t ⋄ tPTR New t}
Tup ⇐ { 𝕊t: !IsTup t ⋄ ReqTyp¨ t ⋄ tTUP New t}
Fun ⇐ tFUN New ⋈
_get⇐ {IsTup 𝕩 ? Tup 𝕊¨𝕩 ; 𝕗 ReqTyp 𝕩}
_cases ← {
Kind←{𝕩.typeKind} ⋄ Dat←{𝕩.dat}
c ← ⌊‿2⥊𝕗
k ← ⊏˘c
d ← (1⊏˘c) ∾ ((≠⥊c)↓𝕗)»⟨!"Unhandled type "∾Repr⟩
(k⊸⊐⌾< ⊢⊘(≠◶⊢‿¯1)○Kind)◶({𝕏○Dat}¨⌾((≠k)⊸↑)d) ⊣ @○ReqTyp
}
TypeErr ← {!∾⟨𝕨," (type was ",Repr 𝕩,")"⟩}
Quality ← ⟨tPRIM,{symbols.New ⋈⊑𝕩}, "Expected primitive type"⊸TypeErr⟩_cases
_isQual ← {⟨tPRIM,𝔽⊑,0⟩_cases TypeOf⍟IsTyped⍟(¬Is)}
IsInt ⇐ ⊑∘∊⟜"iu"_isQual
Unpack ⇐ ⟨tTUP,{Unpack¨𝕩},⊢⟩_cases
Ungather ⇐ ⟨tTUP,⊢,"Gathered argument must have a tuple type"⊸TypeErr⟩_cases
Deref ⇐ { Is 𝕩 ? tPTR=𝕩.typeKind ? 𝕩.dat ; "Expected pointer" TypeErr 𝕩 }
TupFrom ⇐ { Is _and_ (tTUP≡{𝕩.typeKind}) _asrtGotS⟜(𝕩˙) 𝕨 ⋄ 𝕩.dat }
UnFun ⇐ { m←"Expected function type"
m Is _and_ (tFUN≡{𝕩.typeKind}) _asrtGotS 𝕩 ⋄ ∾⟜<´ 𝕩.dat }
TupTry ⇐ { Is 𝕩 ? tTUP≡𝕩.typeKind ? 𝕩.dat ; 𝕩 }
Merge ⇐ {
l ← (tTUP≡{𝕩.typeKind})◶<‿TupFrom¨ 𝕩 # Assume 𝕩 all types
"Type parameters must include a tuple type" ! 0<⌈´=¨l
Tup ∾ l
}
Width ← ⟨
tPRIM, 1⊸⊑
tVEC, ×⟜{Width𝕩}´
tTUP, +´{Width𝕩}¨
tPTR, ptrWidth
{!∾⟨"Can't find width of ",TypeKind𝕩," type ",Repr𝕩⟩}
⟩_cases
VCount ← ⟨ tVEC,⊑, 1 ⟩ _cases
VType ← ⟨ tVEC,1⊸⊑, tPTR,⊢ ⟩ _cases
vecDecompParams ⇐ ⟨Is _and_ {tVEC≡𝕩.typeKind}, {𝕩.dat}⟩
ptrDecompParams ⇐ ⟨Is _and_ {tPTR≡𝕩.typeKind}, {𝕩.dat}⟩
FnCast ⇐ {
args‿ret ← ⟨tFUN,⊢, "Calling non-function"⊸TypeErr⟩_cases 𝕨
args (!"Expected "∾⊣∾" arguments, got "∾⊢)○•Repr⍟≢○≠ 𝕩
⟨args Cast¨ 𝕩, ret⟩
}
_typeRel_ ← {
𝕨 ⟨
tVOID, 1
tPRIM, 𝔽
tVEC, =○⊑ _and_ (𝕊○(¯1⊸⊑))
tPTR, (@≢𝕘)⊑𝕊‿𝕘
tTUP, MTup ← =○≠ _and_ (∧´𝕊¨)
tFUN, 𝕊○(1⊸⊑) _and_ (MTup○⊑)
0
⟩ _cases 𝕩
}
_cmpPrim ← {
L←¯1⊸⊑ ⋄ ≠○⊑◶⟨𝔽○L, ('f'≠⊑∘⊣)_and_(<○L)⟩
}
Equiv ← ≡ _typeRel_ @
Subtype ⇐ ≤ _cmpPrim _typeRel_ 1
SSubtype ⇐ < _cmpPrim _typeRel_ 0
_asCast ← {
"Cast" ReqTyp 𝕨
Fail ← {!∾⟨"Can't cast ",Kind𝕩," to ",Repr𝕨⟩}
Num ← {t𝕊n:
⟨ tPRIM,numbers.Cast⟜n, Fail⟜n ⟩ _cases t
t constants.New n
}
Cast ← 𝕊
Tup ← {
ptr ← 0
c ← ⟨ tTUP,⊢, tPTR,{ptr↩1⋄𝕩}, Fail⟜𝕩 ⟩_cases⍟(0≠•Type) 𝕨
𝕨 functions.Array⍟ptr c Cast¨ 𝕩
}
Obj ← ("number"≢{𝕩.kind})◶⟨Num,IsTyped∘⊢◶⟨Fail˜,𝔽⟩⟩
# _tsel selects on 𝕨; swap to use 𝕩
𝕨 ⟨Tup˜, Num˜, Fail˜, Fail˜, Obj˜⟩_tsel˜ 𝕩
}
_cc ← { Test‿Conv‿Fail _𝕣:
(Conv ⊣ Fail○Repr⍟(¬Test˜)⟜TypeOf)⍟(¬Equiv⟜TypeOf)_asCast
}
Cast ⇐ ⟨
0, !
{!∾⟨"Explicit conversion required to change ",𝕩," to ",𝕨⟩}
⟩_cc
Promote ← ⟨
Subtype, {functions.Emit⟨𝕨, symbols.New "^promote", 𝕨, 𝕩⟩}
{!∾⟨"Can't promote from type ",𝕩," to non-superset ",𝕨⟩}
⟩_cc
Reinterpret ← ⟨
≡○Width, {functions.Emit⟨𝕨, symbols.New "^bitcast", 𝕨, TypeOf 𝕩, 𝕩⟩}
{!∾⟨"Can't reinterpret type ",𝕩," as different-width type ",𝕨⟩}
⟩_cc
IsBool ⇐ (tPRIM New 'u'‿1)⊸Equiv
GetWidth ← "Type width must be a natural number"⊘⊣ numbers.GetNat ⊢
IncWidth ← {
n←"First parameter must be a type or natural number" GetWidth 𝕨
t←TypeOf 𝕩
(1 + n ×∘- Width t)◶⟨
!∘"Can't decrease width in promotion"
⊢
⟨
tPRIM, "Invalid width"_getPrim 𝕨⌾(1⊸⊑)
!∘"Can't increase width of non-primitive type"
⟩_cases∘t⊸Promote
⟩ 𝕩
}
GetQual ← {
e ← "Quality must be 'i', 'u', or 'f'"
n ← e symbols.From 𝕩 ⋄ e!1=≠n
⊑n
}
PrimType ← "Invalid primitive type specification"_getPrim GetQual‿GetWidth {𝕎𝕩}¨ ⊢
builtins ⇐ ∾˘⍉∘‿2⥊⟨
⟨"cast" , "promote" ,"reinterpret"⟩
⟨ Cast _p2,Is∘⊣◶IncWidth‿Promote _p2, Reinterpret _p2⟩
⟨"eltype" ,"vcount" ,"width" ,"__vec" ,"__pnt"⟩
⟨ VType _p1 , VCount _p1, Width _p1, Vec _p2, Ptr _p1⟩
⟨"primtype" ,"quality","isfloat","issigned","isint"⟩
⟨ PrimType _e2, Quality _p1⟩∾{𝕩_isQual _p1}¨⟨'f'⊸≡ ⋄ 'i'⊸≡ ⋄ ⊑∘∊⟜"iu"⟩
⟩
pp_u8 ⇐ Ptr⍟2 @_getPrim 'u'‿8 # **u8, for main
}
registers ← {kname⇐"register"
Is ← kname ≡ Kind
Transient ⇐ {
owner⇐functions.current ⋄ labc⇐owner.labc
kind⇐kname ⋄ shows⇐"(temp)" ⋄ type⇐𝕩 ⋄ fmtType⇐1 ⋄ Matches⇐≡
name←⟨⟩ ⋄ AddName⇐{name∾↩<𝕩}
mut⇐0 ⋄ ref⇐0 ⋄ Use⇐{𝕤⋄ref+↩1} ⋄ SetMut⇐!
ShowReg⇐{showReg↩∾⟨𝕏@⟩∾"_"⊸∾¨(ref=1)/name}
}
Declare ⇐ { name 𝕊 type‿val:
owner⇐functions.current ⋄ labc⇐owner.labc
kind⇐kname ⋄ shows⇐name ⋄ type⇐ ⋄ fmtType⇐1 ⋄ Matches⇐≡
addName⇐@ ⋄ {𝕩.AddName name}⍟Is val
mut⇐0 ⋄ ref⇐0 ⋄ Use⇐{𝕤⋄ref+↩1}
SetMut⇐{𝕤⋄mut↩1} # Changed (for blocks, and transient elimination)
ShowReg⇐{showReg↩𝕩}∘{
Is val? ¬val.mut? (¬mut)∨1=val.ref? labc=val.labc?
ref+↩val.ref-1 ⋄ val.ShowReg𝕩 ;
∾⟨𝕏@,"_",name⟩
}
}
Mutable ⇐ { Is 𝕩 ? {!}≢𝕩.setMut ; 0 }
Mutated ⇐ { Is 𝕩 ? 𝕩.mut ; 0 }
MarkUse ⇐ {𝕩.Use@}⍟Is
CheckAppend ⇐ { "Register used outside its owning function"!𝕨≡𝕩.owner }⍟(Is⊢)
}
constants ← {kname⇐"constant"
New ⇐ {
kind⇐kname ⋄ type⇐𝕨 ⋄ value⇐𝕩
shows⇐∾"!:"∾¨Repr¨𝕩‿𝕨 ⋄ fmtType⇐0 ⋄ Matches⇐≡
}
Static ⇐ {
kind⇐kname ⋄ type‿handle⇐𝕩
shows⇐"$c"∾(("_"∾𝕨)⊣"")∾˜•Repr handle ⋄ fmtType⇐1 ⋄ Matches⇐≡
}
Undefined ⇐ {
kind⇐kname ⋄ type⇐𝕨⊢⊘(types.Ptr⊢)𝕩 ⋄ fmtType⇐0 ⋄ Matches⇐≡
shows⇐∾⟨"?",(•Repr𝕨)⊣"",":",Repr type⟩
}
Exportable ⇐ (kname‿"function"⊸⊐⌾< Kind)◶{"?:"≢2↑𝕩.shows}‿1‿0
}
labels ← {kname⇐"label"
New ⇐ { kind⇐kname ⋄ shows⇐"l"∾•Repr𝕩 ⋄ Matches⇐≡ }
}
symbols ← {kname⇐"symbol"
Is ← kname ≡ Kind
From ⇐ {Is _asrtGotS⟜(𝕩˙) 𝕨 ⋄ 𝕩.symstr}
M ← Is∘⊢_and_(≡○From)
Enc ← "'"(∾∾⊣)⊢+128×' '⊸= # Space to non-breaking space
New ⇐ {
kind⇐kname ⋄ symstr⇐𝕩 ⋄ Shows⇐Enc∘symstr
Matches⇐M ⋄ Matchable⇐{𝕊:matchable↩<symstr}
}
}
functions ← {kname⇐"function"
current⇐nofn←{
Append⇐NextLabel⇐Return⇐SetArch⇐!∘"No function active"
arch⇐architecture.init ⋄ labc⇐0
}
New ← {𝕤
kind⇐kname ⋄ Matches⇐≡ ⋄ Type⇐!∘"Explicit function result type needed"
id⇐𝕩 ⋄ shows⇐("$f"∾(•Repr id)∾"_"⊸∾⍟(0<≠)𝕨)⊣"$main"
arch⇐architecture.NewFunction@ ⋄ SetArch⇐{arch↩𝕩}
label←¯1 ⋄ slabel←⟨⟩ ⋄ args←atypes←ctypes←⟨⟩ ⋄ rType⇐@
labc⇐0 ⋄ IncLab⇐{𝕊:labc+↩1} # Labels set: don't alias through label
NextLabel⇐{𝕤⋄ labels.New label+↩1 }
UseSymLabel⇐{
∊⟜slabel⌾<𝕩 ? !∾"Label "‿𝕩‿" used in this function already" ;
slabel∾↩<𝕩 ⋄ 𝕩
}
NextArg⇐{ name‿gather 𝕊 type:
a ← (name registers.Declare ⋈⟜@)⚇0 types.Unpack type
atypes∾↩<type ⋄ ctypes∾↩gather◶<‿types.Ungather type ⋄ args∾↩<a
a
}
⟨Push,Arr⟩←MakeStack@
Instrs⇐Arr
Append⇐{ current registers.CheckAppend¨ 1↓𝕩 ⋄ Push𝕩 ⋄ @ }
SetRType⇐{
SetRType↩!∘0 ⋄ "Result" types.ReqTyp rType↩𝕩
type ↩ ctypes types.Fun rType
}
_ret_←{
Void ← types.IsVoid
r ← rType ≢⟜@◶⟨𝔽∘⊢, Void∘⊣◶⟨types.Cast,⊑types.primTypes˙⟩⟩ 𝕩
𝕘◶⟨¬Void,1⟩ rType ? Append ⟨"ret", r⟩ ; @
}
Return⇐{
A ← !∘"Early return from function with no explicit result type"
A _ret_ 1 @⊣´𝕩
{Shows⇐!∘"Can't use return result as value"⋄kind⇐"error"}
}
Finish⇐{
e ← "Explicit function result type needed, as result is untyped"
e IsTyped _asrtGotS 𝕩
SetRtype TypeOf 𝕩⋄𝕩
} _ret_ 0
Prot⇐{𝕊 showReg:
ext ← (0<≠)◶⟨⟩‿(⋈·'+'⌾⊑·∾','⊸∾¨) architecture.ListExt arch
at ← ∾ args {IsTup𝕨 ? ∾𝕨𝕊¨𝕩 ; ⋈⟨ShowReg𝕨,Repr𝕩⟩}⟜types.Unpack¨ atypes
1↓∾" "⊸∾¨⟨1↓shows,Repr rType⟩∾((<∘•Repr∘≠∾∾)at)∾ext
}
}
_with_ ⇐ {
# 𝕨 passed in by nodes.Define if not main, pretty hacky
fs←current
f←current↩(1⊑𝕨) program.AddFunction new
{(⊑𝕩).Set f} 𝕨
f (f.Finish 𝔽)program._trace_ 𝕘 𝕩
current↩fs
f
}
NextArg ⇐ { 𝕨 current.NextArg 𝕩 }
Label ⇐ { current.NextLabel 𝕩 }
UseSymLabel ⇐ { current.UseSymLabel 𝕩 }
Append ← { current.Append 𝕩 }
_appendReg ← { (1⊸⊑⊣Append) ⟨"new",𝔽𝕨⟩∾{kind⇐@⋄shows⇐𝕩}⌾⊑𝕩 }
AppendNew ← registers.Transient _appendReg
Return ⇐ { current.Return 𝕩 }
GetArch ← {𝕊: current.arch }
SetArch ← { current.SetArch 𝕩 }
Emit ⇐ { (⊑𝕩) AppendNew "emit" <⊸∾ 𝕩 }
Array ⇐ {
¬∨´("register"≡Kind)¨𝕩 ? 𝕨 constants.New 𝕩 ;
𝕨 AppendNew "array"‿𝕨 ∾ 𝕩
}
Declare ⇐ {
current≡nofn ? 𝕨 program.AddConstant 𝕩 ;
t←TypeOf𝕩 ⋄ 𝕨 registers.Declare⟜t‿𝕩 _appendReg "val"‿t‿𝕩
}
_destructure ← {
0≠•Type𝕩 ? 𝕨𝔽⚇0𝕩;
"Single assignment target but multiple values" ! 0=•Type𝕨
"Assignment tuple length mismatch" ! 𝕨 ≡○≢ 𝕩
𝕨𝕊¨𝕩
}
Mut ⇐ {
"Can't assign to non-register" registers.Mutable _asrtGotS 𝕨
Append "mut"‿𝕨‿(𝕨.type types.Cast 𝕩)
𝕨.SetMut@
𝕨
}_destructure
Call ⇐ {
f ← ⊑𝕩
"Calling non-function" IsTyped _asrtGotS f
a‿t ← (TypeOf f) types.FnCast 1↓𝕩
t AppendNew ⟨"call",t,f⟩ ∾ ≠⊸∾ {IsTup𝕩 ? ∾𝕊¨𝕩 ; ⟨𝕩⟩} a
}
_instr ← { Append (𝕨𝔽𝕩)<⊸∾𝕨⋈𝕩 ⋄ 𝕩 }
SetLabel ⇐ "lbl"_instr ⊣ { current.IncLab 𝕩 }
Goto ⇐ "goto"⊘"gotoT"_instr
GotoF ⇐ "gotoF"_instr
ReadLabel ← {
l ← "Label or symbol expected" symbols.From 𝕩
symbols.New "l_" ∾ UseSymLabel⍟𝕨 l
}⍟("label"≢Kind∘⊢)
builtins ⇐ ⍉> ⟨
⟨"call",Call _v1⟩, ⟨"emit",Emit _v2⟩, ⟨"return",Return⟩
⟨"makelabel",Label⟩, ⟨"goto",(Goto 0⊸ReadLabel) _p1⟩
⟨"setlabel",(SetLabel 1⊸ReadLabel) _p1 ⋈∘Label⍟(0=≠)⟩
⟩ ∾ { New‿Union‿Has‿List ← architecture ⋄ S←SetArch ⋄ G←GetArch ⋄ ⟨
⟨"setarch",S New⟩
⟨"addarch",S G Union New⟩
⟨"hasarch",G⊸Has⟩
⟨"listarch",symbols.New¨List∘G⟩
⟩}
}
blocks ← {
asrtEq ← {𝕊a:≡´_a} AsrtGotGen {∾⟜", needed "⊸∾˜○•Repr´}
New ⇐ {𝕊 ind‿ptrs‿body‿ls‿e:
AsrtNP ← AsrtEq⟜((≠ptrs)⋈≠)
EG ← "Expected generator for @for load or store" IsGen _asrtGotS ⊢
LenLS ← "Wrong number of @for load or store generators"⊸AsrtNP
CheckLS ← IsTup◶⟨EG, EG¨⊣LenLS⟩
{
"Expected two to four parameters" (2⊸≤∧≤⟜4)_asrtGotR ≠𝕩
"Wrong number of pointer arguments to @for body" AsrtNP 1⊑𝕩
CheckLS¨ xls ← 2↓𝕩
r ← body.Eval be ← ⟨≠ind, xls(⊣∾≠⊸↓)ls, 2↑𝕩, ptrs⟩ env.Block e
be.Stores @
r
}
}
}
hashMap ← •BQN∘⊣⎊⊢´ "•HashMap"‿{
keys 𝕊 vals:
Set ⇐ { keys∾↩<𝕨 ⋄ vals∾↩<𝕩 }
Get ⇐ { i←keys⊸⊐⌾<𝕩 ⋄ i<≠keys? i⊑vals ; 𝕨 }
}
MemoMap ← {𝕤
AN←architecture.SeeNext
resmap ← HashMap˜⟨⟩
MemoArg ⇐ { ⟨GetMatchable 𝕩, AN@⟩ }
SetRes ⇐ { 𝕨 resmap.Set 𝕩 ⋄ 𝕩 }
GetCached ⇐ resmap.Get⟜MemoArg
_cached ⇐ {
r ← (none←{⇐}) GetCached 𝕩
none ≢ r ? r ; 𝔽𝕩
}
_memoize ⇐ { (𝔽 SetRes˜ MemoArg) _cached }
}
builtins ← {
# Parameter checking
_exp_ ← {
Il ← 1↓·⥊<⊸(≍˘)
num ← 𝕗⊏"zero"‿"one"‿"two"‿"three"
err ← ∾" " Il "Expected" <⊸∾ ("or" Il num) ∾⟜< "parameters"
𝔾⊣ err ({𝕎∨𝕏}´{𝕏⊸=}¨𝕗)_asrtGotR ≠
}
AsTup ← { # Returns tuple and a function to go back to original kind
IsTup 𝕩 ? 𝕩‿⊢ ;
"type" ≡ Kind 𝕩 ? ⟨𝕨 types.TupFrom 𝕩, types.Tup⟩ ;
⟨𝕨 symbols.From 𝕩, symbols.New⟩
}
MustBe ← ∾⟜"arameter must be a "⊸∾
_req_ ← {(𝕩 MustBe 𝕘) 𝔽 _asrtGotS ⊢}
AsTupP‿AsTup0 ← {(𝕩 MustBe "tuple or symbol")⊸AsTup}¨ "P"‿"First p"
⟨RT0⟩ ← ("type"≡Kind)_req_"type"¨ ⟨"First p"⟩
RGP‿RG0‿RGL ← IsGen _req_"generator"¨ "P"‿"First p"‿"Last p"
⟨RL1⟩ ← IsTup _req_"tuple"¨ ⟨"Second p"⟩
⟨Sym⇐New,FromSym⇐From⟩ ← symbols
SymP ← ("P" MustBe "symbol")⊸FromSym
ReqSym ← "Expected symbol"⊸FromSym
RTT ← ("Parameters other than the first must be tuples" IsTup _asrtGotS ⊢)¨
Kinds ← {
E ← "Unhandled type" ! 0˙
(e{k‿o←𝕨⋄∧○(k≡⊢)◶⟨𝕏,O˙⟩}´𝕩){o←𝕨𝔽○Kind𝕩⋄𝕨O𝕩}
}
Ty2 ← {𝕏⚇0 _p2}∘Kinds ⊣∾⟜(<·"symbol"⌾⊑⊢´)∘⊢⍟(⊑∊⟜=‿≠)"number"‿"type"⋈¨{𝕏numbers._cmp}⊸⋈
Merge ← {
0<(0=≠𝕩)⌈´=¨𝕩 ? ∾𝕩 ;
∧´("type"≡Kind)¨𝕩 ? types.Merge 𝕩 ;
m←"Parameters must include a tuple, or be all types or all symbols"
Sym ∾ m⊸FromSym¨𝕩
}
Slice ← 2‿3 _exp_ {
l‿Ret ← AsTup0 ⊑𝕩