/
compiler.lu
1558 lines (1477 loc) · 40.3 KB
/
compiler.lu
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
export Compiler, Grammar, Context
class Scope {
has entries = { }
has resolve = { }
has hoists = [ ]
has inner = [ ]
has outer
method init(outer) {
.outer = outer
if outer {
outer.inner.push(self)
}
}
method lookup(name, pos, orig) {
orig ||= self
if .entries[name] {
return .entries[name]
}
else if .outer {
return .outer.lookup(name, pos, orig)
}
orig.resolve[name] = pos
}
method define(name, info) {
.entries[name] = info || { }
}
method unhoist(sep) {
var code = .hoists.concat(sep)
if .hoists.len > 0 {
.hoists = [ ]
}
return code
}
}
class Context {
has scope = Scope.new
has exports = { }
has source = ''
method init(source = '') {
.source = source
}
method enter() {
.scope = Scope.new(.scope)
}
method leave() {
if .scope.hoists.len > 0 {
error("unhoisted code: ${.scope.hoists}", 2)
}
var outer = .scope.outer
if outer != nil {
.scope = outer
return outer
}
Error raise "no outer scope"
}
method define(name, info) {
.scope.define(name, info)
}
method lookup(name, pos) {
.scope.lookup(name, pos)
}
}
object Grammar {
function error_line(src, pos) {
var line = 1
var index, limit = 1, pos
while index <= limit {
var s, e = src.find("\n", index, true)
if s == nil || e > limit { break }
index = e + 1
line = line + 1
}
return line
}
function error_near(src, pos) {
if (src.len < pos + 20) {
return src.sub(pos)
}
else {
return src.sub(pos, pos + 20)+"..."
}
}
function syntax_error(m) {
return function(src, pos) {
var line, near = error_line(src, pos), error_near(src, pos)
error("SyntaxError: ${m||''} on line ${line} near '${near}'")
}
}
function expect(p,m) {
if !m { m = p }
return / p | <{ syntax_error("expected '"+m+"'") }> /
}
var id_counter = 9
function genid() {
id_counter += 1
return '_'+id_counter
}
function define(name, ctx, base, type, expr) {
if name is Array {
for i=1, name.len {
ctx.define(name[i], { base = base, type = type, expr = expr })
}
}
else {
ctx.define(name, { base = base, type = type, expr = expr })
}
return name
}
function static_define(name, ctx, ...a) {
ctx.define(name, ...a)
return
}
function enter(ctx) {
ctx.enter()
return
}
function leave(ctx) {
ctx.leave()
return
}
function lookup(pos, name, ctx) {
var info = ctx.lookup(name, pos)
if info {
if info['base'] {
if info['base'] == 'self' {
return 'self:%s()'.format(name)
}
return info['base']+'.'+name
}
return name
}
return '__env.'+name
}
function update(pos, name, ctx) {
var info = ctx.lookup(name, pos)
if !info {
return '__env.'+name+'=%s'
}
if info['base'] {
if info['base'] == 'self' {
return info['base']+':'+name+mangle('=')+'(%s)'
}
return info['base']+'.'+name+'=%s'
}
return name+"=%s"
}
function hoist(lvl) {
lvl ||= 1
return function(ctx, expr) {
var curr = ctx.scope
for i=1, lvl {
curr = curr.outer
}
var tyid = genid()
curr.hoists.push('local %s=%s;'.format(tyid, expr))
return tyid
}
}
function quote(c) { return "%q".format(c) }
var nl = / "\n" /
var line_comment = /
((!nl %s)* ("//" -> '--') (!nl .)* nl)
/
var long_comment = /
("/*" -> '--[=[') (']=]' -> ']\=]' | !"*/" .)* ("*/" -> ']=]')
/
var comment = / {~ line_comment | long_comment ~} /
var idsafe = / !(%alnum | "_") /
var s = / (comment | %s)* /
var S = / (comment | %s)+ /
var hs = / !nl %s /
var udigit = / %digit {~ "_" -> "" ~}? /
var digits = / %digit udigit* /
var word = / ((%alpha | "_") (%alnum | "_")*) /
var keyword = / (
| "var" | "function" | "class" | "with" | "in" | "our"
| "nil" | "true" | "false" | "return" | "static"
| "for" | "throw" | "method" | "has" | "from" | "break" | "guard"
| "switch" | "case" | "default" | "do" | "while" | "needs"
| "continue" | "import" | "export" | "try" | "catch" | "super"
| "default" | "finally" | "if" | "else" | "rule" | "enum"
) idsafe /
var unrops = {
["!"] = "not(%s)",
}
var binops = {
['can'] = false,
['is'] = false,
['as'] = false,
['does'] = false,
["==="] = "(%s)==(%s)",
["!=="] = "(%s)~=(%s)",
["&&"] = "(%s)and(%s)",
["||"] = "(%s)or(%s)",
}
var mangles = {
["["] = "_Z2lb",
["]"] = "_Z2rb",
["$"] = "_Z2do",
["_"] = "_Z2us",
["~"] = "_Z2ti",
["@"] = "_Z2at",
["#"] = "_Z2po",
["*"] = "_Z2st",
["/"] = "_Z2sl",
["%"] = "_Z2pe",
["+"] = "_Z2pl",
["-"] = "_Z2mi",
[":"] = "_Z2co",
['?'] = "_Z2qm",
["!"] = "_Z2ba",
["="] = "_Z2eq",
[">"] = "_Z2gt",
["<"] = "_Z2lt",
["&"] = "_Z2am",
["^"] = "_Z2ca",
["|"] = "_Z2pi",
}
var demangles = { } as nil
for k,v in mangles { demangles#[v] = k }
function demangle(name) {
return tostring(name).gsub('(_Z2%w%w)', function(o) {
if demangles#[o] {
return demangles#[o]
}
else {
return o
}
})
}
function mangle(name) {
return name.gsub('(%W)', function(o,w) {
return mangles[o]
})
}
function make_binop_bind(ctx, a1, a2, o, b) {
a1 = Grammar.expr.match(a1, nil, ctx)
var info = ctx.lookup(a1)
var oper
if binops[o] {
oper = binops[o]
}
else {
oper = '%s:'+mangle(o)+'(%s)'
}
if info && info['type'] {
var type = info['type']
oper = (type+':coerce(%s)').format(oper)
}
return a2.format(oper.format(a1,b))
}
var name_patt = / "__env." ? { (%alnum | "_")+ } hs* "=" /
function make_bind_expr(ctx, l, s1, s2, r) {
var hoist = ctx.scope.unhoist()
if l.len == 1 {
var name = name_patt.match(l[1])
if name {
var info = ctx.lookup(name)
if info && info['type'] {
var type = info['type']
r[1] = (type+':coerce(%s)').format(r[1])
}
}
return hoist+l[1].format(s2 + r.concat(','))
}
var t = [ ]
for i = 1, l.len {
t.push(genid())
var name = name_patt.match(l[i])
if name {
var info = ctx.lookup(name)
if info && info['type'] {
var type = info['type']
t[i] = (type+':coerce(%s)').format(t[i])
}
}
l[i] = l[i].format(t[i])
}
var b = [ ]
b.push('%slocal %s%s=%s%s;'.format(hoist,t.concat(','), s1, s2, r.concat(',')))
b.push(l.concat(';'))
return b.concat()
}
var punct = /
'$'|'~'|'@'|'#'|'*'|'/'|'%'|'+'|'-'|':'|'!'|'>'|'<'|'&'|'^'|'|'|'='|'_'|'?'
/
function fold_prefix(o,e) {
if o == '...' {
return '%s:unpack()'.format(e)
}
else if unrops[o] {
return unrops[o].format(e)
}
var m = mangle(o + '_')
return '%s:%s()'.format(e, m)
}
function fold_bind_prefix(o,e) {
if o == '...' {
return '%s:unpack(%%s)'.format(e)
}
var m = mangle(o + '_=')
return '%s:%s(%%s)'.format(e, m)
}
var cmpops = {
["=="] = true,
["!="] = true,
[">"] = true,
["<"] = true,
[">="] = true,
["<="] = true,
}
function fold_infix(a,o,b) {
if binops[o] {
return binops[o].format(a, b)
}
else if cmpops[o] {
return "%s:${mangle(o)}(%s)".format(a, b)
}
else if o.match('.=$') {
var m = mangle(o.match('^(.-)=$'))
return "%s=%s:%s(%s)".format(a, a, m, b)
}
else {
var m = mangle(o)
return "%s:%s(%s)".format(a,m,b)
}
}
function make_infix_expr(oper, term) {
/ (({~ term (&(hs+ oper) s)? ~} {: hs* {oper} {~ s term ~} :}*) ~> fold_infix) /
}
function make_var_decl(ctx, kind, lhs, rhs) {
rhs = rhs || [ ]
var tmp = [ ]
var buf = [ ]
var hoist = ctx.scope.unhoist()
if rhs.len == 0 {
if kind == nil {
return '%slocal %s'.format(hoist, lhs.concat(','))
}
else {
for i=1, lhs.len {
lhs[i] = '__env.'+lhs[i]+'=nil'
}
return '%s%s'.format(hoist,lhs.concat(';'))
}
}
if lhs.len == 1 {
var info = ctx.lookup(lhs[1])
if info['type'] {
var type = info['type']
rhs[1] = (type+':coerce(%s)').format(rhs[1] || '')
}
if kind == nil {
return "%slocal %s=%s;".format(hoist, lhs[1], rhs[1] || 'nil')
}
else {
return "%s__env.%s=%s;".format(hoist, lhs[1], rhs[1] || 'nil')
}
}
for i = 1, lhs.len {
tmp.push(genid())
}
if rhs.len > 0 {
buf.push('%slocal %s=%s'.format(hoist, tmp.concat(','), rhs.concat(',')))
}
var head = ''
if kind == nil {
head = 'local '
}
for i=1, lhs.len {
var info = ctx.lookup(lhs[i])
if info['type'] {
var type = info['type']
tmp[i] = (type+':coerce(%s)').format(tmp[i])
}
if kind != nil {
lhs[i] = '__env.'+lhs[i]
}
}
buf.push('%s%s=%s;'.format(head, lhs.concat(','), tmp.concat(',')))
return buf.concat(';')
}
function make_has_decl(ctx, name, type, body, scope, attr) {
define(name, ctx, nil, type, body)
type ||= 'nil'
return '__env.has(self,"%s",%s,function(self) return %s end,%s);'.format(name,type,body,attr)
}
function make_params(ctx, list) {
var head = [ ]
if list.len > 0 {
for i=1, list.len {
var name = list[i]
if !name.find('...', 1, true) {
name = name.match('^%s*([^%s]+)%s*$')
var info = ctx.lookup(name)
if info['expr'] {
head.push('if %s==nil then %s=%s else %s=%s end'.format(
name, name, info['expr'], name, name
))
}
if info['type'] {
var type = info['type']
head.push('%s=%s:coerce(%s)'.format(name,type,name))
}
}
}
if list[list.len].find('...', 1, true) {
var last = list[list.len]
var name = last.match('^%.%.%.(.+)$')
list[list.len] = "..."
if name {
var info = ctx.lookup(name)
if info['type'] {
var type = info['type']
head.push('local %s=__env.Array:new(...):inject(function(...) return %s:coerce(...) end)'.format(name,type))
}
else {
head.push("local %s=__env.Array:new(...)".format(name))
}
}
}
}
return list.concat(","), head.concat(';')
}
function make_for_in_stmt(ctx, name_list, expr, body) {
var list, head = make_params(ctx, name_list)
var hoist = ctx.scope.unhoist()
return '%sfor %s in __env._each(%s) do %s%s end'.format(hoist, list, expr, head, body)
}
function make_for_stmt(ctx, name, init, last, step, body) {
var list, head = make_params(ctx, [ name ])
var hoist = ctx.scope.unhoist()
return '%sfor %s=%s,%s,%s do %s%s end'.format(hoist, name, init, last, step, head, body)
}
function make_return_stmt(ctx, is_lex, expr_list, ...type_list) {
expr_list = expr_list || [ ]
if type_list {
for i=1, type_list.len {
var type = type_list[i]
var expr = expr_list[i] || ''
expr_list[i] = (type+":coerce(%s)".format(expr))
}
}
var e = expr_list.concat(',')
if is_lex {
return "do _return = {%s}; return end ".format(e)
}
return "do return %s end".format(e)
}
function make_func(c,p,b) {
var p, h = make_params(c, p)
var t = c.scope.unhoist()
if t != '' {
return "(function()%s return function(%s) %s%s end end)()".format(t,p,h,b)
}
else {
return 'function(%s) %s%s end'.format(p,h,b)
}
}
function make_func_decl(c,n,p,b,s) {
var p, h = make_params(c, p)
var t = c.scope.outer.unhoist()
if s == 'lexical' {
c.scope.outer.define(n)
return "%slocal function %s(%s)%s %s end".format(t,n,p,h,b)
}
else {
c.scope.outer.define(n, { base = '__env' })
return "%sfunction __env.%s(%s)%s %s end".format(t,n,p,h,b)
}
}
function make_enum_decl(c,n,b,s) {
var decl = '__env.enum(%q,{%s});'
if s == 'lexical' {
c.define(n, { type = 'Enum' })
decl = 'local %s='+decl
}
else {
c.define(n, { type = 'Enum', base = '__env' })
decl = '__env.%s='+decl
}
return decl.format(n,n,b)
}
function make_with_decl(w) {
return "__env.with(self,{%s})".format(w)
}
function make_meth_decl(c,n,p,b,s,a) {
p = [ 'self', ...p ]
var p, h = make_params(c,p)
var t = c.scope.outer.unhoist()
return "%s__env.method(self,%q,function(%s)%s %s end,%s);".format(t,n,p,h,b,a)
}
function make_class_decl(c,n,f,w,b,s) {
var decl = '__env.class(__env,%q,%s,{%s},function(__env,self,super) %s end);'
if s == 'lexical' {
c.define(n, { type = 'Class' })
decl = 'local %s='+decl
}
else {
c.define(n, { type = 'Class', base = '__env' })
decl = "__env.%s="+decl
}
return decl.format(n,n,f,w,b)
}
function make_obj_decl(c,n,f,w,b,s) {
var decl = '__env.object(__env,%q,%s,{%s},function(__env,self,super) %s end);'
if s == 'lexical' {
c.define(n, { type = n })
decl = 'local %s='+decl
}
else {
c.define(n, { type = n, base = '__env' })
decl = "__env.%s="+decl
}
return decl.format(n,n,f,w,b)
}
function make_obj(c,f,w,b,s) {
var decl = '__env.object(__env,%q,%s,{%s},function(__env,self,super) %s end)'
return decl.format("object${genid()}",f,w,b)
}
function make_trait_decl(c,n,p,w,b) {
var decl = '__env.trait(__env,%q,{%s},%s,function(__env,self,%s)%s end);'
var a = '...'
if p.len > 0 {
a = p.concat(',')
}
if s == 'lexical' {
c.scope.outer.define(n, { type = 'Trait' })
decl = 'local %s='+decl
}
else {
c.scope.outer.define(n, { type = 'Trait', base = '__env' })
decl = "__env.%s="+decl
}
return decl.format(n,n,w,p.len,a,b)
}
function make_guard_decl(c,n,p,b,s) {
p = [ 'self', ...p ]
var p, h = make_params(c, p)
var decl = '__env.guard(%q,function(%s)%s %s end)'
var hoist = c.scope.outer.unhoist()
if s == 'lexical' {
c.scope.outer.define(n)
decl = "%slocal %s="+decl
}
else {
c.scope.outer.define(n, { base = '__env' })
decl = "%s__env.%s="+decl
}
return decl.format(hoist,n,n,p,h,b)
}
function make_try_stmt(s,ctx, try_body, catch_blocks, loopy) {
var args = [ ]
if loopy {
args.push("function() repeat ${try_body} until true end")
}
else {
args.push("function() ${try_body} end")
}
for i=1, catch_blocks.len {
args.push(catch_blocks[i])
}
var stmt = [ ]
stmt.push("do${s}")
stmt.push("local _return;__env.try(${args.concat(',')});")
stmt.push('if _return then return __env.unpack(_return) end')
if loopy {
stmt.push('if _break then break end')
}
stmt.push('end')
return stmt.concat(' ')
}
function make_catch_stmt(ctx, s1, s2, head, s3, body, loopy) {
var head = head || '__err'
var name = head.match('^%s*([^%s]+)%s*$')
var info = ctx.lookup(name)
var type = info['type']
if loopy {
return "{body=${s1}function(${s2}${name}) ${s3} repeat ${body} until true end, type=${type}}"
}
else {
return "{body=${s1}function(${s2}${name}) ${s3} ${body} end, type=${type}}"
}
}
function make_import_decl(ctx, names, path, dest) {
var qnames = [ ]
if names == nil { names = [ ] }
if dest {
ctx.define(dest, { base = '__env' })
dest = quote(dest)
for i=1, names.len {
qnames[i] = quote(names[i])
}
}
else {
// XXX: import from <dotted_path> (i.e. no names, no dest)
dest = 'nil'
for i=1, names.len {
ctx.define(names[i], { base = '__env' })
qnames[i] = quote(names[i])
}
}
return "__env:import(%q,{%s},%s);".format(path, qnames.concat(','), dest)
}
function make_export_decl(c,n) {
var b = [ ]
for i=1, n.len {
c.exports[n[i]] = true
}
return ''
}
method match(...a) {
self.script.match(...a)
}
rule script {
{~ <unit> ~} (!. | <{syntax_error("invalid syntax")}>)
}
rule verify {
<ctx> -> function(ctx) {
var stack = [ ctx.scope ]
while stack.len > 0 {
var curr = stack.pop
for k,v in curr.resolve {
var info = curr.lookup(k)
if !(info && info['base'] == '__env') {
SyntaxError.raise(
"symbol '${k}' was never defined on"+
" line: ${error_line(ctx.source,v)}"+
" near: ${error_near(ctx.source,v)}",
2)
}
}
for i=1, curr.inner.len {
stack.push(curr.inner[i])
}
}
}
}
rule preamble {
{:set_return: {`false`} :}
{:type_list: {`nil`} :}
{:scope: {`'__env'`} :}
{:loopy: {`false`} :}
}
rule unit {
<preamble>
{ %s* '#!' (!nl .)* %s* }?
<enter>
({`'__env'`} <ctx> -> static_define)
{`'local __env=require("lupa.predef").environ();'`}
s <stmt_list>? s
<verify>
(<ctx> -> function(ctx) {
var buf = [ ]
for k,v in ctx.exports {
if !ctx.lookup(k) {
SyntaxError.raise("export '${k}' was never defined", 2)
}
buf.push('{%q,%s}'.format(k,lookup(0, k, ctx)))
}
return " return __env:export(${buf.concat(',')});"
})
<leave>
}
rule eval {
{~
{:set_return: {`false`} :}
{:type_list: {`nil`} :}
{:scope: {`'lexical'`} :}
{:loopy: {`false`} :}
{`'local __env=...;'`}
<enter>
({`'__env'`} <ctx> -> static_define)
{~ s <func_body> s ~}
<leave>
~} (!. | <{syntax_error("invalid syntax")}>)
}
rule ctx { %1 }
rule enter { <ctx> -> enter }
rule leave { <ctx> -> leave }
rule sep {
long_comment? ("\n" | ";" | &"}" | line_comment) | [\t ] <sep>
}
rule decl_stmt {
| <var_decl>
| <enum_decl>
| <func_decl>
| <class_decl>
| <trait_decl>
| <guard_decl>
| <object_decl>
| <import_decl>
| <export_decl>
}
rule stmt {
| <if_stmt>
| <switch_stmt>
| <throw_stmt>
| <break_stmt>
| <continue_stmt>
| <for_stmt>
| <for_in_stmt>
| <do_while_stmt>
| <while_stmt>
| <try_stmt>
| <decl_stmt>
| <bind_stmt>
| <expr_stmt>
| <block_stmt>
| <return_stmt>
}
rule stmt_list {
{~ <stmt> (<sep> s <stmt>)* <sep>? ~}
}
rule return_stmt {
{~ "return" -> '' idsafe s (
<ctx>
=set_return ((<expr> (s "," s <expr>)*)? -> [ ])
=type_list
-> make_return_stmt)
~}
}
rule block_stmt {
{~ <block> -> 'do %1 end' ~}
}
rule block_expr {
{~ <func_body> -> '(function() %1 end)()' ~}
}
rule block {
'{' <block_body> <{ expect("}") }> -> '%1'
}
rule block_body {
{~ (
{:scope: {`'lexical'`} :}
{~ s <enter> <stmt_list>? <leave> s ~}
) -> '%2' ~}
}
rule loop_block {
{~ ('{'
{:scope: {`'lexical'`} :}
{:loopy: {`true`} :}
{~ s <enter> <stmt_list>? <leave> s ~}
'}') -> 'local _break; repeat %3 until true; if _break then break end' ~}
}
rule import_decl {
{~ (
"import" idsafe s
<ctx> ((<name> (s "," s <name>)*)? -> [ ]) s
"from" idsafe s {~ <name> ("." <name>)* ~}
(s "in" idsafe s <name>)?
) -> make_import_decl ~}
}
rule export_decl {
{~ "export" idsafe s <ctx>
(<name> (s "," s <name>)* -> [ ]) -> make_export_decl
~}
}
rule for_name {
<name> <ctx> {`nil`} (s <ctx> <type_expr> -> hoist(0))? -> define
}
rule for_in_stmt {
{~ "for" idsafe s <enter> <ctx>
(<for_name> (s "," s <for_name>)* -> [ ]) s
"in" idsafe s <expr> s
<loop_block> -> make_for_in_stmt <leave>
~}
}
rule for_stmt {
{~ "for" idsafe s <enter> <ctx> <for_name> s "=" s <expr> s "," s <expr>
(s "," s <expr> | {`1`}) s <loop_block> -> make_for_stmt <leave>
~}
}
rule while_stmt {
{~ "while" idsafe s <expr> {~ s <loop_block> ~}
-> 'while %1 do %2 end' ~}
}
rule do_while_stmt {
{~
"do" idsafe {~ s <loop_block> s ~}
"while" idsafe {~ s <expr> ~} -> 'repeat %1 until not(%2)'
~}
}
rule if_stmt {
{~ "if" idsafe s <expr> s {`" then "`} s <block> (
(s ({"else" idsafe s "if" idsafe} -> " elseif") s
<expr> {`" then "`} s <block>
)*
(s "else" idsafe s <block> {`" end "`} | {`" end "`})
) ~}
}
rule switch_stmt {
{~
"switch" idsafe s {~ <expr> ~} s
<{ expect("{") }> {:loopy: {`true`} :}
{~ (s <case_stmt>)* (s <default_stmt>)? s ~}
<{ expect("}") }> -> "do local _switch,_break=(%1);repeat %3 until true end"
~}
}
rule case_stmt {
{~
"case" idsafe {~ hs* <expr> s ~} <{ expect(":") }>
{~ s <case_body>? ~}
-> " if __env.case(_switch,%1) then %2 end "
~}
}
rule case_body {
{~ <case_body_stmt> (<sep> s <case_body_stmt>)* <sep>? ~}
}
rule case_body_stmt {
{~ !(("case" | "default") idsafe) <stmt> ~}
}
rule default_stmt {
{~ "default" idsafe hs* ":" {~ s <stmt_list>? ~} -> "%1" ~}
}
rule throw_stmt {
"throw" idsafe {~ s <expr> ~} -> '__env.throw(%1)'
}
rule break_stmt {
{~ { "break" idsafe } (
=loopy => function(s,o,l) {
if !l {
syntax_error("no loop to break")(s,o)
}
return o
}) -> "do _break=true; break end"
~}
}
rule continue_stmt {
{~ { "continue" idsafe } -> "do break end" ~}
}
rule try_stmt {
{~
"try" idsafe {s} <ctx> <enter>
"{" {~ s <lambda_body> s ~} <{ expect("}") }>
({~ s <catch_stmt> ~}* -> [ ]) =loopy
-> make_try_stmt <leave>
~}
}
rule catch_stmt {
{~
"catch" idsafe <ctx> <enter> {s}
"(" {s} (<name> <ctx> {`nil`} (hs* <type_expr> | {`nil`}) -> define)
")" {s} "{" {~ s <lambda_body> s ~} "}"
=loopy -> make_catch_stmt <leave>
~}
}
rule lambda_body {
{:set_return: {`true`} :}
<block_body>
}
rule name_list {
<name> (hs* "," s <name>)*
}
rule type_term {
<expr>
}
rule type_term_list {
<type_term> (hs* "," s <type_term>)*
}
rule type_expr {
":" hs* <type_term>
}
rule type_list {
":" hs* {:type_list: <hoist_type_term> (s "," s <hoist_type_term>)* :}
}
rule hoist_type_term {
{~ <ctx> <type_term> -> hoist(1) ~}
}
rule var_decl {
{:kind: ("var" {`nil`} | "our" {`'__env'`}) idsafe :} hs* {:
<ctx> =kind (<var_list> -> [ ])
(hs* "=" ({~ s <expr> ~} {~ s ("," -> '') s <expr> ~}* -> [ ]))?
:} -> make_var_decl
}
rule var_list {
(<name> <ctx> =kind (s (<ctx> <type_expr> -> hoist(0)))? -> define)
(hs* "," s (<name> <ctx> =kind (s (<ctx> <type_expr> -> hoist(0)))? -> define))*
}
rule attr {
{:attr: {~ "static" idsafe hs* -> 'true' ~} | {`'false'`} :}
}
rule has_decl {
{~ (<attr> "has" idsafe s <ctx> <name>
(s <type_expr> | {`nil`})
(s "=" s <expr> | {`""`})
=scope =attr
) -> make_has_decl ~}
}
rule needs_decl {
{~
<attr> "needs" idsafe hs* <meth_name> =attr -> '__env.needs(self,"%2",%3)'
~}
}
rule meth_name {
{~ {"_[]=" | "_[]"} -> mangle ~} | {~ <opname> ("=" -> mangle)? ~}
}
rule meth_decl {
{~ (<attr> "method" idsafe hs* <ctx> <meth_name> s
<enter>
({`'self'`} <ctx> -> static_define)
("(" s <param_list> s <{ expect(")") }> s | {`[]`})
<type_list>? s
"{" {~ s <func_body> s ~} <{ expect("}") }>
=scope =attr) -> make_meth_decl ~} <leave>
}
rule func_decl {
{~ ("function" idsafe <ctx> s <name> s
<enter>
("(" s <param_list> s <{ expect(")") }> s | {`[]`})
<type_list>? s
"{" {~ s <func_body> s ~} <{ expect("}") }>
) -> make_func_decl ~} <leave>
}
rule func_body {
{~ {:scope: {`'lexical'`} :} {:loopy: {`false`} :} <func_stmt_list>? ~}
}
rule func_stmt_list {
{~ <func_stmt> (<sep> s <func_stmt>)* <sep>? ~}
}
rule func_stmt {
| ((&(<expr> s "}") <ctx> // last expr implies return
=set_return (<expr> -> [ ])
=type_list) -> make_return_stmt)
| <stmt>
}
rule func {
{~ (
"function" idsafe s <enter>
"(" s <ctx> <param_list> s <{ expect(")") }> (s <type_list>)? s "{"
{~ s <func_body> s ~}
<{ expect("}") }>
) -> make_func ~} <leave>
}
rule short_func {
{~ (
("(" s <enter> <ctx> <param_list> s ")" (s <type_list>)? s
| <enter> <ctx> (({`"${mangle('_')}"`} <ctx> -> define) -> [ ]))
'=>' s (
| "{" {~ s <func_body> s ~} <{ expect("}") }>
| {~ (
<ctx>
=set_return (<expr_stmt> -> [ ])
=type_list -> make_return_stmt
) (s <sep>)? ~}