-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathwok.rb
2195 lines (1937 loc) · 43.3 KB
/
wok.rb
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
# wok.rb -- bootstrapping implementation of the compiler
# Copyright (C) 2019, 2020, 2021 Wolfgang Jährling
#
# ISC License
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#require 'byebug'
class Token
def initialize(type, text, filename, line)
@type = type
@text = text
@filename = filename
@line = line
end
def special?(kind)
@type == :special && @text == kind
end
def key?(kind)
@type == :key && @text == kind
end
def id?(kind)
@type == :id && @text == kind
end
def eof?
@type == :eof
end
def str?
@type == :str
end
def type
@type
end
def text
@text
end
def pos
"#{@filename}:#{@line}"
end
def to_s
"#{@type} #{@text}"
end
end
class Lexer
def initialize(filename)
@filename = filename
@line = 1
@src = File.open(filename)
@ahead = []
end
def line
@line
end
def next_token
if @ahead.empty?
read_token()
else
@ahead.shift()
end
end
def peek_token
res = next_token()
@ahead.unshift(res)
res
end
def insert_tokens(tokens)
@ahead = tokens + @ahead
end
private
def getc
res = @src.getc()
if res == "\n"
@line = @line + 1
end
res
end
def peekc
res = @src.getc()
@src.ungetc(res) if res
res
end
def first_relevant
loop do
c = getc() # may be nil
return c unless irrelevant_char?(c)
if c == ';'
while c != "\n" # ignores possible eof
c = getc()
end
end
end
end
def special_token_char?(c)
['@', '^', '(', ')', '[', ']', '{', '}', '$', "'"].include?(c)
end
def irrelevant_char?(c)
[" ", "\t", "\n", ";"].include?(c)
end
def identifier_char?(c)
!special_token_char?(c) && !irrelevant_char?(c) &&
!['#', '%', '&', '|', '"', ':', ',', '\\', '.'].include?(c)
end
def read_token
c = first_relevant()
case c
when ->(c) { special_token_char?(c) }
return Token.new(:special, c, @filename, @line)
when '"'
text = ''
loop do
c = getc()
break if c == '"'
if c == '\\'
c = getc()
case c
when 'n' then c = "\n"
when 't' then c = "\t"
end
end
text += c
end
return Token.new(:str, text, @filename, @line)
when ':'
c = getc()
raise "#{@filename}:#{@line}: single colon found" if c != ':'
return Token.new(:special, '::', @filename, @line)
when '~'
c = getc()
if c == '\\'
c = getc()
case c
when 'n'
return Token.new(:int, '10', @filename, @line)
when 't'
return Token.new(:int, '8', @filename, @line)
else
raise "#{@filename}:#{@line}: unknown character literal: ~\\#{c}"
end
else
return Token.new(:int, c.ord.to_s, @filename, @line)
end
when nil
return Token.new(:eof, '', @filename, @line)
else
tok = c
while identifier_char?(peekc())
tok = tok + getc()
end
if tok[/^-?\d+$/]
return Token.new(:int, tok, @filename, @line)
end
if tok[/^-?0[xX][0-9a-fA-F]+$/]
return Token.new(:int, tok.to_i(16), @filename, @line)
end
if peekc() == ':'
getc() # read the colon
if peekc() != ':'
return Token.new(:key, tok, @filename, @line)
else
getc() # read second colon
@ahead.unshift(Token.new(:special, '::', @filename, @line))
end
end
return Token.new(:id, tok, @filename, @line)
end
end
end
class Parser
def initialize(filename, mod)
@filename = filename
@lex = Lexer.new(filename)
@mod = mod # need module for looking up macros
end
def next_toplevel
tok = initial() # returns nil or id-token
return nil if tok == nil
case tok.text
when 'the'
return parse_variable()
when 'dec'
return parse_declaration()
when 'def'
return parse_definition()
when 'for'
return parse_macro()
when 'private'
# TODO
when 'public'
# TODO
when 'class'
return parse_class()
when 'opt'
# TODO
when 'use'
# TODO
when 'type'
return parse_primitive_type()
else
raise "#{tok.pos}: unknown toplevel command #{tok.text}"
end
end
private
def initial
tok = next_token()
return nil if tok.eof?
if tok.type != :id
raise "#{tok.pos}: unexpected token #{tok} at toplevel"
end
tok
end
def next_token
tok = @lex.next_token()
if tok.type == :id
mac = @mod.lookup(tok.text)
if mac.is_a?(WokFor)
@lex.insert_tokens(mac.tokens)
return next_token()
end
end
tok
end
def parse_primitive_type
name = next_token()
if name.type != :key
raise "#{name.pos}: expected `typename:` after 'type', found #{name.text}"
end
old_name = next_token()
if old_name.type != :id
raise "#{name.pos}: expected typename identifier as type reference, found #{old_name.text}"
end
TypeDef.new(name.text, name.pos, old_name.text)
end
def parse_variable
name = next_token()
if name.type != :key
raise "#{name.pos}: expected 'varname:' after def, found #{name.text}"
end
type = parse_type()
if type.is_a?(WokAdr)
raise "#{name.pos}: @address not allowed as toplevel or attribute definition"
end
WokVar.new(name.text, type, name.pos)
end
def parse_macro
name = next_token()
if name.type != :id
raise "#{name.pos}: expected identifier after for, found #{name.text}"
end
curly = next_token()
if !curly.special?('{')
raise "#{name.pos}: expected opening curly brace, found #{curly}"
end
tokens = []
curly = 0
loop do
tok = next_token()
if tok.eof?
# using the name pos might actually be a good idea here in
# case the user forgets to close a macro
raise "#{name.pos}: eof in macro definition"
end
if tok.special?('}')
if curly == 0
break
else
curly -= 1
end
end
if tok.special?('{')
curly += 1
end
tokens << tok
end
WokFor.new(name.text, tokens, name.pos)
end
def parse_declaration
name = next_token()
if name.type != :id
raise "#{name.pos}: expected identifier after dec, found #{name.text}"
end
parse_opening_paren()
effect = parse_effect()
WokDec.new(name.text, effect, name.pos)
end
def parse_definition
name = next_token()
if name.type != :id
raise "#{name.pos}: expected identifier after def, found #{name.text}"
end
parse_opening_paren()
effect = parse_effect()
code = parse_block()
WokDef.new(name.text, effect, code, name.pos)
end
def parse_opening_paren
tok = next_token()
if !tok.special?('(')
raise "#{tok.pos}: expected '(', found #{tok}"
end
end
def parse_effect # does not parse opening paren
from = []
loop do
tok = @lex.peek_token # TODO: ignores macros
if tok.special?('::')
tok = @lex.next_token # skip past the '::'
break
end
if tok.special?(')')
break # leave the ')' here
end
type = parse_type()
from << type
end
to = []
noreturn = false
loop do
tok = @lex.peek_token # TODO: ignores macros
if tok.special?(')')
@lex.next_token # skip past the ')'
break
end
if tok.id?('_noreturn_')
@lex.next_token # drop the '_noreturn_'
noreturn = true
else
type = parse_type()
to << type
end
end
Effect.new(from, to, noreturn: noreturn)
end
def parse_block
tok = next_token()
if !tok.special?('[')
raise "#{tok.pos}: expected '[', found #{tok}"
end
code = []
loop do
tok = next_token()
break if tok.special?(']')
case tok.type
when :id
if tok.text == '_srcpos_'
code << OpPushStr.new("#{@filename}:#{@lex.line}")
else
code << OpCall.new(tok.text, tok.pos)
end
when :special
case tok.text
when '@'
code << OpCall.new('@', tok.pos)
when '('
code << OpCast.new(parse_effect(), tok.pos)
when '$'
name = next_token()
if name.type != :id
raise "#{name.pos}: expected identifier after $, found #{name}"
end
code << OpPushRef.new(name.text, name.pos)
when "'"
name = next_token()
if name.type != :id
raise "#{name.pos}: expected identifier after ' but found #{name}"
end
code << OpMsg.new(name.text, name.pos)
else
raise "#{tok.pos}: expected code, found #{tok}"
end
when :int
code << OpPushInt.new(tok.text.to_i)
when :str
code << OpPushStr.new(tok.text)
when :key
case tok.text
when 'if'
code << parse_if(tok.pos)
when 'with'
code << parse_with(tok.pos)
when 'loop'
code << parse_loop(tok.pos)
when 'new'
# TODO
when 'is'
# TODO
else
raise "#{tok.pos}: expected code, found #{tok}"
end
else
raise "#{tok.pos}: expected code, found #{tok}"
end
end
code
end
def parse_type
tok = next_token
case tok.type
when :id
return WokTypeName.new(tok.text, tok.pos)
when :special
case tok.text
when '@'
return WokAdr.new(parse_type())
when '^'
return WokPtr.new(parse_type())
when '['
len = parse_int()
tok = next_token()
if !tok.special?(']')
raise "#{tok.pos}: expected ']', found #{tok}"
end
return WokAry.new(len, parse_type())
when '('
return WokRef.new(parse_effect())
else
raise "#{tok.pos}: syntax error: expected type, found #{tok}"
end
else
raise "#{tok.pos}: syntax error: expected type, found #{tok}"
end
end
def parse_with(pos)
then_branch = parse_block()
tok = @lex.peek_token() # TODO: ignores macros
if tok.key?('else')
tok = next_token()
else_branch = parse_block()
OpWith.new(then_branch, else_branch, pos)
else
OpWith.new(then_branch, [], pos)
end
end
def parse_if(pos)
then_branch = parse_block()
tok = @lex.peek_token() # TODO: ignores macros
if tok.key?('else')
tok = next_token()
else_branch = parse_block()
OpIfElse.new(then_branch, else_branch, pos)
else
OpIf.new(then_branch, pos)
end
end
def parse_loop(pos)
code = parse_block()
OpLoop.new(code, pos)
end
def parse_int # TODO: 'const:'
tok = next_token()
if tok.type != :int
raise "#{tok.pos}: expected int literal, found #{tok}"
end
tok.text.to_i
end
def parse_class
name = next_token()
if name.type != :id
raise "#{name.pos}: expected identifier after 'class', found #{name}"
end
tok = next_token()
if !tok.special?('{')
raise "#{tok.pos}: expected '{', found #{tok}"
end
content = []
loop do
tok = next_token()
break if tok.special?('}')
if tok.type != :id
raise "#{tok.pos}: unexpected token in class: #{tok}"
end
case tok.text
when 'the'
content << parse_variable()
when 'dec'
# TODO
when 'def'
content << parse_definition()
when 'private'
# TODO
when 'public'
# TODO
else
raise "#{tok.pos}: unknown identifier in class: #{tok.text}"
end
end
WokParsedClass.new(name.text, content, name.pos)
end
end
class WokVar
def initialize(name, type, pos)
@name = name
@type = type
@pos = pos
end
def name
@name
end
def type
@type
end
def pos
@pos
end
def set_offset(m64, m32)
@offset = [m64, m32]
end
def offset
@offset
end
end
class WokDec
def initialize(name, effect, pos)
@name = name
@effect = effect
@pos = pos
end
def name
@name
end
def effect
@effect
end
def pos
@pos
end
end
class WokDef
def initialize(name, effect, code, pos)
@name = name
@effect = effect
@code = code
@pos = pos
end
def name
@name
end
def effect
@effect
end
def code
@code
end
def pos
@pos
end
end
class WokFor
def initialize(name, tokens, pos)
@name = name
@tokens = tokens
@pos = pos
end
def name
@name
end
def tokens
@tokens
end
def pos
@pos
end
end
class WokAdr
def initialize(type)
@type = type
end
def type
@type
end
def to_s
"@#{@type}"
end
end
class WokPtr
def initialize(type)
@type = type
end
def type
@type
end
def to_s
"^#{@type}"
end
end
class WokRef
def initialize(effect)
@effect = effect
end
def effect
@effect
end
def to_s
effect.to_s
end
end
class WokAry
def initialize(len, type)
if type.is_a?(WokAry)
raise "#{'TODO'}: arrays of arrays or not permitted"
end
@len = len
@type = type
end
def len
@len
end
def type
@type
end
def to_s
"[#{len}]#{type}"
end
end
class WokTypeName
def initialize(name, pos)
@name = name
@pos = pos
end
def name
@name
end
def pos
@pos
end
def to_s
name()
end
end
class Effect
# from and to are arrays of WokType
def initialize(from, to, noreturn: false)
if noreturn && to.size != 0
raise "#{'TODO'}: _noreturn_ word has results specified: #{@to.map(&:to_s).join(' ')}"
end
@from = from.freeze
@to = to.freeze
@noreturn = noreturn
end
def from
@from
end
def to
if noreturn?
raise 'internal error: asking for result stack of _noreturn_ word'
end
@to
end
def noreturn?
@noreturn
end
def to_s
if noreturn?
to = '_noreturn_'
else
to = @to.map(&:to_s).join(' ')
end
"(#{@from.map(&:to_s).join(' ')} :: #{to})"
end
end
class OpCall # TODO: not the best name for this
def initialize(name, pos)
@name = name
@pos = pos
end
def name
@name
end
def pos
@pos
end
end
class OpIfElse
def initialize(then_code, else_code, pos)
@then_code = then_code
@else_code = else_code
@pos = pos
end
def then_code
@then_code
end
def else_code
@else_code
end
def pos
@pos
end
end
class OpIf
def initialize(then_code, pos)
@then_code = then_code
@pos = pos
end
def then_code
@then_code
end
def pos
@pos
end
end
class OpWith
def initialize(then_code, else_code, pos)
@then_code = then_code
@else_code = else_code
@pos = pos
end
def then_code
@then_code
end
def else_code
@else_code
end
def pos
@pos
end
end
class OpLoop
def initialize(code, pos)
@code = code
@pos = pos
end
def code
@code
end
def pos
@pos
end
end
class OpPushInt
def initialize(i)
@i = i
end
def i
@i
end
end
class OpPushStr
def initialize(text)
@text = text
end
def text
@text
end
end
class OpPushRef
def initialize(name, pos)
@name = name
@pos = pos
end
def name
@name
end
def pos
@pos
end
end
class Compiler
def initialize(module_name)
@module_name = module_name
@current_module = WokModule.new()
@parser = Parser.new(module_name + '.wok', @current_module)
@next_label_nr = 0
@types = Types.new()
builtin_type('any')
builtin_type('int')
builtin_type('bool')
builtin_type('s32', size: [4,4], signed: true)
builtin_type('s16', size: [2,2], signed: true)
builtin_type('s8', size: [1,2], signed: true)
builtin_type('u32', size: [4,4], signed: false)
builtin_type('u16', size: [2,2], signed: false)
builtin_type('u8', size: [1,1], signed: false)
@loop_end_labels = []
@loop_end_stacks = []
end
def compile
emit('%include "../../runtime/wok-codes.asm"')
loop do
toplevel = @parser.next_toplevel
break if toplevel == nil
case toplevel
when WokVar
verify_type(toplevel.type)
register(toplevel)
emit_var(toplevel)
when WokDec
verify_effect_types(toplevel.effect)
register(toplevel)
# TODO: only for declarations from interface files:
emit_dec(toplevel)
when WokDef
verify_effect_types(toplevel.effect)
register(toplevel)
emit_def(toplevel)
when WokFor
register(toplevel)
when TypeDef
old = @types.lookup(toplevel.old)
if old == nil
raise "#{toplevel.pos}: unknown type #{toplevel.old}"
end
@types.register(toplevel.name, PrimitiveType.new(toplevel.name, toplevel.pos, old.size, old.signed))
when WokParsedClass
wok_class = create_class(toplevel)
@types.register(wok_class.name, wok_class)
emit_class(wok_class)
end
end
end
private
def register(toplevel_entry)
# can be WokVar, WokDec, WokDef, WokFor
@current_module.register(toplevel_entry.name, toplevel_entry)
end
def builtin_type(name, size: [8,4], signed: true)
@types.register(name, PrimitiveType.new(name, '(builtin)', size, signed))
end
def emit_dec(dec)
emit('extern ' + mangle(dec.name))
end
def emit_var(var)
elements = 1
vartype = var.type
if vartype.is_a?(WokAry)
elements = vartype.len
vartype = vartype.type
if elements <= 0
raise "#{var.pos}: number of array elements must be positive"
end
end
if vartype.is_a?(WokTypeName)
vartype = @types.lookup(vartype.name)
end
# TODO: I think this can be simplified now, need no special case for class
if vartype.is_a?(WokClass)
m64, m32 = vartype.size
if m64 != 0 || m32 != 0
emit("wok_the #{mangle(var.name)}, #{m64}, #{m32}, #{elements}")
else
emit("wok_theempty #{mangle(var.name)}")
end
else
m64, m32 = var_size(vartype)
emit("wok_the #{mangle(var.name)}, #{m64}, #{m32}, #{elements}")
end
end
def var_size(var)
size = [8,4]
if var.is_a?(WokTypeName)
type = @types.lookup(var.name)
size = type.size
end
size
end
def emit_def(wok_def, klass: nil)
@stack = WokStack.new(wok_def.effect.from.dup, @types)
if wok_def.effect.noreturn?
@result_stack = :noreturn
else
@result_stack = WokStack.new(wok_def.effect.to, @types) # for 'ok'
end
emit('wok_def ' + mangle(wok_def.name))
emit_codeblock(wok_def.code)
emit('wok_ok')
if @result_stack != :noreturn &&
!@stack.can_use_stack?(as: wok_def.effect.to)
raise "#{wok_def.pos}: code results in #{@stack}, should be #{@result_stack}"
end
@result_stack = nil
@stack = nil
end
def emit_codeblock(code)
code.each do |element|
case element
when OpCall then emit_id(element)