forked from teal-language/tl
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtl.tl
6279 lines (5838 loc) · 198 KB
/
tl.tl
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
local Env = record
globals: {string:Variable}
modules: {string:Type}
skip_compat53: boolean
end
local TypeCheckOptions = record
lax: boolean
filename: string
skip_compat53: boolean
env: Env
result: Result
end
local tl = {
process: function(string, Env, Result, {string}): (Result, string) = nil,
type_check: function(Node, TypeCheckOptions): ({Error}, {Error}, Type) = nil,
init_env: function(boolean, boolean): Env = nil,
}
--------------------------------------------------------------------------------
-- Lexer
--------------------------------------------------------------------------------
--local inspect: function(any):string = require "inspect"
local inspect = function(x: any):string
return tostring(x)
end
local keywords: {string:boolean} = {
["and"] = true,
["break"] = true,
["do"] = true,
["else"] = true,
["elseif"] = true,
["end"] = true,
["false"] = true,
["for"] = true,
["function"] = true,
["goto"] = true,
["if"] = true,
["in"] = true,
["local"] = true,
["nil"] = true,
["not"] = true,
["or"] = true,
["repeat"] = true,
["return"] = true,
["then"] = true,
["true"] = true,
["until"] = true,
["while"] = true,
-- ["global"] = true,
}
local TokenKind = enum
"keyword"
"op"
"string"
"[" "]" "(" ")" "{" "}" "," ":" "#" "`" "." ";"
"::"
"..."
"identifier"
"number"
"$invalid$"
"$EOF$"
end
local Token = record
x: number
y: number
i: number
tk: string
kind: TokenKind
end
local lex_word_start: {string:boolean} = {}
for c = string.byte("a"), string.byte("z") do
lex_word_start[string.char(c)] = true
end
for c = string.byte("A"), string.byte("Z") do
lex_word_start[string.char(c)] = true
end
lex_word_start["_"] = true
local lex_word: {string:boolean} = {}
for c = string.byte("a"), string.byte("z") do
lex_word[string.char(c)] = true
end
for c = string.byte("A"), string.byte("Z") do
lex_word[string.char(c)] = true
end
for c = string.byte("0"), string.byte("9") do
lex_word[string.char(c)] = true
end
lex_word["_"] = true
local lex_decimal_start: {string:boolean} = {}
for c = string.byte("1"), string.byte("9") do
lex_decimal_start[string.char(c)] = true
end
local lex_decimals: {string:boolean} = {}
for c = string.byte("0"), string.byte("9") do
lex_decimals[string.char(c)] = true
end
local lex_hexadecimals: {string:boolean} = {}
for c = string.byte("0"), string.byte("9") do
lex_hexadecimals[string.char(c)] = true
end
for c = string.byte("a"), string.byte("f") do
lex_hexadecimals[string.char(c)] = true
end
for c = string.byte("A"), string.byte("F") do
lex_hexadecimals[string.char(c)] = true
end
local lex_char_symbols: {string:boolean} = {}
for _, c in ipairs({"[", "]", "(", ")", "{", "}", ",", "#", "`", ";"}) do
lex_char_symbols[c] = true
end
local lex_op_start: {string:boolean} = {}
for _, c in ipairs({"+", "*", "/", "|", "&", "%", "^"}) do
lex_op_start[c] = true
end
local lex_space: {string:boolean} = {}
for _, c in ipairs({" ", "\t", "\v", "\n", "\r"}) do
lex_space[c] = true
end
local LexState = enum
"start"
"any"
"identifier"
"maybecomment"
"maybecomment2"
"maybedotdot"
"maybedotdotdot"
"decimal_number"
"decimal_or_hex"
"decimal_float"
"power"
"power_sign"
"hex_number"
"hex_float"
"lt"
"gt"
"colon"
"maybeequals"
"maybelongstring"
"dblquote_string"
"singlequote_string"
"escape_dblquote_string"
"escape_singlequote_string"
"comment"
"longcomment"
"maybelongcomment"
"maybelongcommentend"
"longstring"
"maybelongstring"
"maybelongstringend"
end
function tl.lex(input: string): {Token}, {Token}
local tokens: {Token} = {}
local state: LexState = "start"
local fwd = true
local y = 1
local x = 0
local i = 0
local lc_open_lvl = 0
local lc_close_lvl = 0
local ls_open_lvl = 0
local ls_close_lvl = 0
local errs: {Token} = {}
local tx: number
local ty: number
local ti: number
local in_token = false
local function begin_token()
tx = x
ty = y
ti = i
in_token = true
end
local function end_token(kind: TokenKind, last: number, t: string)
local tk = t or input:sub(ti, last or i) or ""
if keywords[tk] then
kind = "keyword"
end
table.insert(tokens, {
x = tx,
y = ty,
i = ti,
tk = tk,
kind = kind,
})
in_token = false
end
local function drop_token()
in_token = false
end
while i <= #input do
if fwd then
i = i + 1
if i > #input then
break
end
end
local c: string = input:sub(i, i)
if fwd then
if c == "\n" then
y = y + 1
x = 0
else
x = x + 1
end
else
fwd = true
end
if state == "start" then
if input:sub(1,2) == "#!" then
i = input:find("\n")
if not i then
break
end
c = "\n"
y = 2
x = 0
end
state = "any"
end
if state == "any" then
if c == "-" then
state = "maybecomment"
begin_token()
elseif c == "." then
state = "maybedotdot"
begin_token()
elseif c == "\"" then
state = "dblquote_string"
begin_token()
elseif c == "'" then
state = "singlequote_string"
begin_token()
elseif lex_word_start[c] then
state = "identifier"
begin_token()
elseif c == "0" then
state = "decimal_or_hex"
begin_token()
elseif lex_decimal_start[c] then
state = "decimal_number"
begin_token()
elseif c == "<" then
state = "lt"
begin_token()
elseif c == ":" then
state = "colon"
begin_token()
elseif c == ">" then
state = "gt"
begin_token()
elseif c == "=" or c == "~" then
state = "maybeequals"
begin_token()
elseif c == "[" then
state = "maybelongstring"
begin_token()
elseif lex_char_symbols[c] then
begin_token()
end_token(c as TokenKind)
elseif lex_op_start[c] then
begin_token()
end_token("op")
elseif lex_space[c] then
-- continue
else
begin_token()
end_token("$invalid$")
table.insert(errs, tokens[#tokens])
end
elseif state == "maybecomment" then
if c == "-" then
state = "maybecomment2"
else
end_token("op", nil, "-")
fwd = false
state = "any"
end
elseif state == "maybecomment2" then
if c == "[" then
state = "maybelongcomment"
else
fwd = false
state = "comment"
drop_token()
end
elseif state == "maybelongcomment" then
if c == "[" then
state = "longcomment"
elseif c == "=" then
lc_open_lvl = lc_open_lvl + 1
else
fwd = false
state = "comment"
drop_token()
lc_open_lvl = 0
end
elseif state == "longcomment" then
if c == "]" then
state = "maybelongcommentend"
end
elseif state == "maybelongcommentend" then
if c == "]" and lc_close_lvl == lc_open_lvl then
drop_token()
state = "any"
lc_open_lvl = 0
lc_close_lvl = 0
elseif c == "=" then
lc_close_lvl = lc_close_lvl + 1
else
state = "longcomment"
lc_close_lvl = 0
end
elseif state == "dblquote_string" then
if c == "\\" then
state = "escape_dblquote_string"
elseif c == "\"" then
end_token("string")
state = "any"
end
elseif state == "escape_dblquote_string" then
state = "dblquote_string"
elseif state == "singlequote_string" then
if c == "\\" then
state = "escape_singlequote_string"
elseif c == "'" then
end_token("string")
state = "any"
end
elseif state == "escape_singlequote_string" then
state = "singlequote_string"
elseif state == "maybeequals" then
if c == "=" then
end_token("op")
state = "any"
else
end_token("op", i - 1)
fwd = false
state = "any"
end
elseif state == "lt" then
if c == "=" or c == "<" then
end_token("op")
state = "any"
else
end_token("op", i - 1)
fwd = false
state = "any"
end
elseif state == "colon" then
if c == ":" then
end_token("::")
state = "any"
else
end_token(":", i - 1)
fwd = false
state = "any"
end
elseif state == "gt" then
if c == "=" or c == ">" then
end_token("op")
state = "any"
else
end_token("op", i - 1)
fwd = false
state = "any"
end
elseif state == "maybelongstring" then
if c == "[" then
state = "longstring"
elseif c == "=" then
ls_open_lvl = ls_open_lvl + 1
else
end_token("[", i - 1)
fwd = false
state = "any"
ls_open_lvl = 0
end
elseif state == "longstring" then
if c == "]" then
state = "maybelongstringend"
end
elseif state == "maybelongstringend" then
if c == "]" then
if ls_close_lvl == ls_open_lvl then
end_token("string")
state = "any"
ls_open_lvl = 0
ls_close_lvl = 0
end
elseif c == "=" then
ls_close_lvl = ls_close_lvl + 1
else
state = "longstring"
ls_close_lvl = 0
end
elseif state == "maybedotdot" then
if c == "." then
state = "maybedotdotdot"
elseif lex_decimals[c] then
state = "decimal_float"
else
end_token(".", i - 1)
fwd = false
state = "any"
end
elseif state == "maybedotdotdot" then
if c == "." then
end_token("...")
state = "any"
else
end_token("op", i - 1)
fwd = false
state = "any"
end
elseif state == "comment" then
if c == "\n" then
state = "any"
end
elseif state == "identifier" then
if not lex_word[c] then
end_token("identifier", i - 1)
fwd = false
state = "any"
end
elseif state == "decimal_or_hex" then
if c == "x" or c == "X" then
state = "hex_number"
elseif c == "e" or c == "E" then
state = "power_sign"
elseif lex_decimals[c] then
state = "decimal_number"
elseif c == "." then
state = "decimal_float"
else
end_token("number", i - 1)
fwd = false
state = "any"
end
elseif state == "hex_number" then
if c == "." then
state = "hex_float"
elseif c == "p" or c == "P" then
state = "power_sign"
elseif not lex_hexadecimals[c] then
end_token("number", i - 1)
fwd = false
state = "any"
end
elseif state == "hex_float" then
if c == "p" or c == "P" then
state = "power_sign"
elseif not lex_hexadecimals[c] then
end_token("number", i - 1)
fwd = false
state = "any"
end
elseif state == "decimal_number" then
if c == "." then
state = "decimal_float"
elseif c == "e" or c == "E" then
state = "power_sign"
elseif not lex_decimals[c] then
end_token("number", i - 1)
fwd = false
state = "any"
end
elseif state == "decimal_float" then
if c == "e" or c == "E" then
state = "power_sign"
elseif not lex_decimals[c] then
end_token("number", i - 1)
fwd = false
state = "any"
end
elseif state == "power_sign" then
if c == "-" or c == "+" then
state = "power"
elseif lex_decimals[c] then
state = "power"
else
end_token("$invalid$")
table.insert(errs, tokens[#tokens])
state = "any" -- FIXME report malformed number
end
elseif state == "power" then
if not lex_decimals[c] then
end_token("number", i - 1)
fwd = false
state = "any"
end
end
end
local terminals: {LexState:TokenKind} = {
["identifier"] = "identifier",
["decimal_or_hex"] = "number",
["decimal_number"] = "number",
["decimal_float"] = "number",
["hex_number"] = "number",
["hex_float"] = "number",
["power"] = "number",
}
if in_token then
if terminals[state] then
end_token(terminals[state], i - 1)
else
drop_token()
end
end
return tokens, (#errs > 0) and errs
end
--------------------------------------------------------------------------------
-- Pretty-print tokens
--------------------------------------------------------------------------------
local add_space: {string:boolean} = {
["word:keyword"] = true,
["word:word"] = true,
["word:string"] = true,
["word:="] = true,
["word:op"] = true,
["keyword:word"] = true,
["keyword:keyword"] = true,
["keyword:string"] = true,
["keyword:number"] = true,
["keyword:="] = true,
["keyword:op"] = true,
["keyword:{"] = true,
["keyword:("] = true,
["keyword:#"] = true,
["=:word"] = true,
["=:keyword"] = true,
["=:string"] = true,
["=:number"] = true,
["=:{"] = true,
["=:("] = true,
["op:("] = true,
["op:{"] = true,
["op:#"] = true,
[",:word"] = true,
[",:keyword"] = true,
[",:string"] = true,
[",:{"] = true,
["):op"] = true,
["):word"] = true,
["):keyword"] = true,
["op:string"] = true,
["op:number"] = true,
["op:word"] = true,
["op:keyword"] = true,
["]:word"] = true,
["]:keyword"] = true,
["]:="] = true,
["]:op"] = true,
["string:op"] = true,
["string:word"] = true,
["string:keyword"] = true,
["number:word"] = true,
["number:keyword"] = true,
}
local should_unindent: {string:boolean} = {
["end"] = true,
["elseif"] = true,
["else"] = true,
["}"] = true,
}
local should_indent: {string:boolean} = {
["{"] = true,
["for"] = true,
["if"] = true,
["while"] = true,
["elseif"] = true,
["else"] = true,
["function"] = true,
}
function tl.pretty_print_tokens(tokens: {Token}): string
local y = 1
local out = {}
local indent = 0
local newline = false
local kind: string = ""
for _, t in ipairs(tokens) do
while t.y > y do
table.insert(out, "\n")
y = y + 1
newline = true
kind = ""
end
if should_unindent[t.tk] then
indent = indent - 1
if indent < 0 then
indent = 0
end
end
if newline then
for _ = 1, indent do
table.insert(out, " ")
end
newline = false
end
if should_indent[t.tk] then
indent = indent + 1
end
if add_space[(kind or "") .. ":" .. t.kind] then
table.insert(out, " ")
end
table.insert(out, t.tk)
kind = t.kind or ""
end
return table.concat(out)
end
--------------------------------------------------------------------------------
-- Recursive descent parser
--------------------------------------------------------------------------------
local last_typeid = 0
local function new_typeid(): number
last_typeid = last_typeid + 1
return last_typeid
end
local ParseError = record
y: number
x: number
msg: string
filename: string
end
local TypeName = enum
"typetype"
"nestedtype"
"typevar"
"typearg"
"function"
"array"
"map"
"arrayrecord"
"record"
"enum"
"boolean"
"string"
"nil"
"number"
"union"
"nominal"
"bad_nominal"
"emptytable"
"table_item"
"unknown_emptytable_value"
"tuple"
"poly" -- intersection types, currently restricted to polymorphic functions defined inside records
"any"
"unknown"
"invalid"
"unresolved"
"none"
end
local table_types: {TypeName:boolean} = {
["array"] = true,
["map"] = true,
["arrayrecord"] = true,
["record"] = true,
["emptytable"] = true,
}
local Type = record
{Type}
y: number
x: number
filename: string
typename: TypeName
tk: string
closed: boolean
yend: number
-- Lua compatibilty
needs_compat53: boolean
-- vararg
is_va: boolean
-- poly, union
types: {Type}
-- typetype
def: Type
-- map
keys: Type
values: Type
-- records
typeargs: {Type}
fields: {string: Type}
field_order: {string}
-- array
elements: Type
-- function
is_method: boolean
args: Type
rets: Type
typeid: number
-- nominal
names: {string}
typevals: Type
resolved: Type
-- typevar
typevar: string
-- typearg
typearg: string
-- table items
kname: string
ktype: Type
vtype: Type
-- emptytable
declared_at: Node
assigned_to: string
keys_inferred_at: Node
keys_inferred_at_file: string
inferred_at: Node
inferred_at_file: string
emptytable_type: Type
-- enum
enumset: {string:boolean}
-- unresolved items
labels: {string:{Node}}
nominals: {string:{Type}}
end
local Operator = record
y: number
x: number
arity: number
op: string
prec: number
end
local NodeKind = enum
"op"
"nil"
"string"
"number"
"boolean"
"table_literal"
"table_item"
"function"
"expression_list"
"enum_item"
"if"
"elseif"
"else"
"while"
"fornum"
"forin"
"goto"
"label"
"repeat"
"do"
"break"
"return"
"values"
"newtype"
"argument"
"variable"
"variables"
"statements"
"assignment"
"argument_list"
"local_function"
"global_function"
"record_function"
"local_declaration"
"global_declaration"
"identifier"
"cast"
"..."
"paren"
end
local FactType = enum
"is"
end
local Fact = record
fact: FactType
var: string
typ: Type
end
local KeyParsed = enum
"short"
"long"
"implicit"
end
local Node = record
{Node}
y: number
x: number
tk: string
kind: NodeKind
yend: number
facts: {Fact}
key: Node
value: Node
key_parsed: KeyParsed
typeargs: Type
args: Node
rets: Type
body: Node
name: Node
-- local
is_const: boolean
fn_owner: Node
is_method: boolean
exp: Node
parent_if: Node
thenpart: Node
elseifs: Node
elseif_n: number
elsepart: Node
-- fornum
var: Node
from: Node
to: Node
step: Node
-- forin
vars: Node
exps: Node
-- newtype
newtype: Type
-- expressions
op: Operator
e1: Node
e2: Node
constnum: number
conststr: string
-- goto
label: string
casttype: Type
typename: string
type: Type
decltype: Type
end
local function is_array_type(t:Type): boolean
return t.typename == "array" or t.typename == "arrayrecord"
end
local function is_record_type(t:Type): boolean
return t.typename == "record" or t.typename == "arrayrecord"
end
local ParseState = record
tokens: {Token}
errs: {ParseError}
filename: string
end
local parse_expression: function(ParseState, number): number, Node, number
local parse_statements: function(ParseState, number, string): number, Node
local parse_type_list: function(ParseState, number, string): number, Type
local parse_argument_list: function(ParseState, number): number, Node
local parse_argument_type_list: function(ParseState, number): number, Type
local parse_type: function(ParseState, number): number, Type, number
local parse_newtype: function(ps: ParseState, i: number): number, Node
local function fail(ps: ParseState, i: number, msg: string): number
if not ps.tokens[i] then
local eof = ps.tokens[#ps.tokens]
table.insert(ps.errs, { y = eof.y, x = eof.x, msg = msg or "unexpected end of file" })
return #ps.tokens
end
table.insert(ps.errs, { y = ps.tokens[i].y, x = ps.tokens[i].x, msg = msg or "syntax error" })
return math.min(#ps.tokens, i + 1)
end
local function verify_tk(ps: ParseState, i: number, tk: string): number
if ps.tokens[i].tk == tk then
return i + 1
end
return fail(ps, i, "syntax error, expected '" .. tk .. "'")
end
local function new_node(tokens: {Token}, i: number, kind: NodeKind): Node
local t = tokens[i]
return { y = t.y, x = t.x, tk = t.tk, kind = kind or t.kind }
end
local function a_type(t: Type): Type
t.typeid = new_typeid()
return t
end
local function new_type(ps: ParseState, i: number, typename: TypeName): Type
local token = ps.tokens[i]
return a_type {
typename = assert(typename),
filename = ps.filename,
y = token.y,
x = token.x,
tk = token.tk
}
end
local function verify_kind(ps: ParseState, i: number, kind: TokenKind, node_kind: NodeKind): number, Node
if ps.tokens[i].kind == kind then
return i + 1, new_node(ps.tokens, i, node_kind)
end
return fail(ps, i, "syntax error, expected " .. kind)
end
local is_newtype: {string:boolean} = {
["enum"] = true,
["record"] = true,
["functiontype"] = true,
}
local function parse_table_value(ps: ParseState, i: number): number, Node
if is_newtype[ps.tokens[i].tk] then
return parse_newtype(ps, i)
else
local i, node, _ = parse_expression(ps, i)
return i, node
end
end