forked from richardhundt/shine
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtransformer.lua
790 lines (724 loc) · 21.1 KB
/
transformer.lua
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
local B = require('builder')
local util = require('util')
local Scope = { }
Scope.__index = Scope
function Scope.new(outer)
local self = {
outer = outer;
entries = { };
}
return setmetatable(self, Scope)
end
function Scope:define(name, info)
self.entries[name] = info
end
function Scope:lookup(name)
if self.entries[name] then
return self.entries[name]
elseif self.outer then
return self.outer:lookup(name)
else
return nil
end
end
local Context = { }
Context.__index = Context
function Context.new()
local self = {
scope = Scope.new()
}
return setmetatable(self, Context)
end
function Context:enter()
self.scope = Scope.new(self.scope)
end
function Context:leave()
self.scope = self.scope.outer
end
function Context:define(name, info)
info = info or { }
self.scope:define(name, info)
return info
end
function Context:lookup(name)
local info = self.scope:lookup(name)
return info
end
local match = { }
function match:Chunk(node)
self.hoist = { }
self.scope = { }
local export = B.identifier('export')
self.scope[#self.scope + 1] = B.localDeclaration({ export }, { B.table({}) })
for i=1, #node.body do
local stmt = self:get(node.body[i])
self.scope[#self.scope + 1] = stmt
end
for i=#self.hoist, 1, -1 do
table.insert(self.scope, 1, self.hoist[i])
end
self.scope[#self.scope + 1] = B.returnStatement({ export })
return B.chunk(self.scope)
end
function match:ImportStatement(node)
local args = { B.literal(node.from) }
for i=1, #node.names do
args[#args + 1] = B.literal(node.names[i].name)
end
return B.localDeclaration(self:list(node.names), {
B.callExpression(B.identifier('import'), args)
})
end
function match:ModuleDeclaration(node)
local name = self:get(node.id)
self.hoist[#self.hoist + 1] = B.localDeclaration({ name }, { })
local outer_scope = self.scope
local outer_hoist = self.hoist
self.scope = { }
self.hoist = { }
local export = B.identifier('export')
self.scope[#self.scope + 1] = B.localDeclaration({ export }, { B.table({}) })
for i=1, #node.body do
local stmt = self:get(node.body[i])
self.scope[#self.scope + 1] = stmt
end
for i=#self.hoist, 1, -1 do
table.insert(self.scope, 1, self.hoist[i])
end
local body = self.scope
self.scope = outer_scope
self.hoist = outer_hoist
body[#body + 1] = B.returnStatement({ export })
local init = B.callExpression(
B.parenExpression{
B.functionExpression({ }, B.blockStatement(body))
}, { }
)
if node.export then
local expr = B.memberExpression(B.identifier('export'), name)
self.scope[#self.scope + 1] = B.assignmentExpression(
{ expr }, { init }
)
init = expr
end
return B.assignmentExpression({ name }, { init })
end
function match:Literal(node)
return B.literal(node.value)
end
function match:Identifier(node)
return B.identifier(node.name)
end
function match:VariableDeclaration(node)
local inits = node.inits and self:list(node.inits) or { }
if node.export then
for i=1, #node.names do
local expr = B.memberExpression(
B.identifier('export'), self:get(node.names[i])
)
self.scope[#self.scope + 1] = B.assignmentExpression(
{ expr }, { inits[i] }
)
inits[i] = expr
end
end
for i=1, #node.names do
local n = node.names[i]
if n.type == 'Identifier' and not self.ctx:lookup(n.name) then
self.ctx:define(n.name)
end
end
return B.localDeclaration(self:list(node.names), inits)
end
function match:AssignmentExpression(node)
local body = { }
local decl = { }
for i=1, #node.left do
local n = node.left[i]
if n.type == 'Identifier' and not self.ctx:lookup(n.name) then
self.ctx:define(n.name)
decl[#decl + 1] = self:get(n)
end
end
if #decl > 0 then
body[#body + 1] = B.localDeclaration(decl, { })
end
body[#body + 1] = B.assignmentExpression(
self:list(node.left), self:list(node.right)
)
return B.blockStatement(body)
end
function match:UpdateExpression(node)
local oper = string.sub(node.operator, 1, 1)
return B.assignmentExpression({
self:get(node.left)
}, {
B.binaryExpression(oper, self:get(node.left), self:get(node.right))
})
end
function match:MemberExpression(node)
return B.memberExpression(
self:get(node.object), self:get(node.property), node.computed
)
end
function match:SelfExpression(node)
return B.identifier('self')
end
function match:SuperExpression(node)
return B.identifier('super')
end
function match:ThrowStatement(node)
return B.expressionStatement(
B.callExpression(B.identifier('throw'), { self:get(node.argument) })
)
end
function match:ReturnStatement(node)
if self.retsig then
return B.doStatement(
B.blockStatement{
B.assignmentExpression(
{ self.retsig }, { B.literal(true) }
);
B.assignmentExpression(
{ self.retval }, self:list(node.arguments)
);
B.returnStatement{ self.retval }
}
)
end
return B.returnStatement(self:list(node.arguments))
end
function match:YieldStatement(node)
return B.expressionStatement(
B.callExpression(
B.memberExpression(B.identifier('coroutine'), B.identifier('yield')),
self:list(node.arguments)
)
)
end
function match:IfStatement(node)
local test, cons, altn = self:get(node.test)
if node.consequent then
cons = self:get(node.consequent)
end
if node.alternate then
altn = self:get(node.alternate)
end
local stmt = B.ifStatement(test, cons, altn)
return stmt
end
function match:TryStatement(node)
local oldret = self.retsig
local oldval = self.retval
self.retsig = B.tempnam()
self.retval = B.tempnam()
local try = B.functionExpression({ }, self:get(node.body))
local finally
if node.finalizer then
finally = B.functionExpression({ }, self:get(node.finalizer))
end
local exit = util.genid()
local clauses = { }
for i=#node.guardedHandlers, 1, -1 do
local clause = node.guardedHandlers[i]
local cons = self:get(clause.body)
local head = B.localDeclaration(
{ self:get(clause.param) }, { B.vararg() }
)
cons.body[#cons.body + 1] = B.gotoStatement(B.identifier(exit))
clauses[#clauses + 1] = head
clauses[#clauses + 1] = B.ifStatement(self:get(clause.guard), cons)
end
if node.handler then
local clause = node.handler
local cons = self:get(clause.body)
local head = B.localDeclaration(
{ self:get(clause.param) }, { B.vararg() }
)
cons.body[#cons.body + 1] = B.gotoStatement(B.identifier(exit))
clauses[#clauses + 1] = head
clauses[#clauses + 1] = B.doStatement(cons)
end
clauses[#clauses + 1] = B.labelStatement(B.identifier(exit))
local catch = B.functionExpression(
{ B.vararg() }, B.blockStatement(clauses)
)
local expr = B.callExpression(B.identifier('try'), { try, catch, finally })
local temp = self.retval
local rets = self.retsig
self.retsig = oldret
self.retval = oldval
return B.doStatement(
B.blockStatement{
B.localDeclaration({ rets }, { B.literal(false) });
B.localDeclaration({ temp }, { B.literal(nil) });
B.expressionStatement(expr);
B.ifStatement(
rets, B.blockStatement{ B.returnStatement{ temp } }
)
}
)
end
function match:BreakStatement(node)
return B.breakStatement()
end
function match:ContinueStatement(node)
return B.gotoStatement(self.loop)
end
function match:LogicalExpression(node)
return B.logicalExpression(
node.operator, self:get(node.left), self:get(node.right)
)
end
local bitop = {
[">>"] = 'rshift',
[">>>"] = 'arshift',
["<<"] = 'lshift',
["|"] = 'bor',
["&"] = 'band',
["^"] = 'bxor',
}
function match:BinaryExpression(node)
local o = node.operator
if bitop[o] then
local call = B.memberExpression(
B.identifier('bit'),
B.identifier(bitop[o])
)
local args = { self:get(node.left), self:get(node.right) }
return B.callExpression(call, args)
end
if o == 'is' then
return B.callExpression(B.identifier('__is__'), {
self:get(node.left), self:get(node.right)
})
end
if o == '..' then
return B.callExpression(B.identifier('__range__'), {
self:get(node.left), self:get(node.right)
})
end
if o == '**' then o = '^' end
if o == '~' then o = '..' end
if o == '!=' then o = '~=' end
return B.binaryExpression(o, self:get(node.left), self:get(node.right))
end
function match:UnaryExpression(node)
local o = node.operator
local a = self:get(node.argument)
if o == 'typeof' then
return B.callExpression(B.identifier('__typeof__'), { a })
end
return B.unaryExpression(o, a)
end
function match:FunctionDeclaration(node)
local name
if not node.expression then
name = self:get(node.id[1])
end
local params = { }
local prelude = { }
local vararg = false
for i=1, #node.params do
params[#params + 1] = self:get(node.params[i])
if node.defaults[i] then
local name = self:get(node.params[i])
local test = B.binaryExpression("==", name, B.literal(nil))
local expr = self:get(node.defaults[i])
local cons = B.blockStatement{
B.assignmentExpression({ name }, { expr })
}
prelude[#prelude + 1] = B.ifStatement(test, cons)
end
end
if node.rest then
params[#params + 1] = B.vararg()
prelude[#prelude + 1] = B.localDeclaration(
{ B.identifier(node.rest.name) },
{ B.callExpression(B.identifier('Array'), { B.vararg() }) }
)
end
local body = self:get(node.body)
for i=#prelude, 1, -1 do
table.insert(body.body, 1, prelude[i])
end
local func
if node.generator then
local inner = B.functionExpression({ }, body, vararg)
func = B.functionExpression(params, B.blockStatement{
B.returnStatement{
B.callExpression(
B.memberExpression(B.identifier("coroutine"), B.identifier("wrap")),
{ inner }
)
}
}, vararg)
else
func = B.functionExpression(params, body, vararg)
end
if node.expression then
return func
end
if node.export then
local expr = B.memberExpression(
B.identifier('export'), name
)
self.scope[#self.scope + 1] = B.assignmentExpression(
{ expr }, { func }
)
end
return B.localDeclaration({ name }, { func })
end
--[[
local Point = class("Point", function(this, super)
Object:defineProperties(this, {
move = {
value = function(self, x, y)
end,
}
})
end)
]]
function match:ClassDeclaration(node)
local name = self:get(node.id)
local base = node.base and self:get(node.base) or B.identifier('Object')
local properties = { }
local body = { }
for i=1, #node.body do
if node.body[i].type == "PropertyDefinition" then
local prop = node.body[i]
local desc = properties[prop.key.name] or { }
if prop.kind == 'get' then
desc.get = self:get(prop)
elseif prop.kind == 'set' then
desc.set = self:get(prop)
else
desc.value = self:get(prop)
end
if desc.static then
if desc.static.value ~= prop.static then
error("property "..prop.key.name.." already defined as static")
end
end
desc.static = B.literal(prop.static)
properties[prop.key.name] = desc
if desc.get then
-- self.__getters__[key] = desc.get
body[#body + 1] = B.assignmentExpression(
{ B.memberExpression(
B.memberExpression(B.identifier("self"), B.identifier("__getters__")),
B.identifier(prop.key.name)
) },
{ desc.get }
)
elseif desc.set then
-- self.__setters__[key] = desc.set
body[#body + 1] = B.assignmentExpression(
{ B.memberExpression(
B.memberExpression(B.identifier("self"), B.identifier("__setters__")),
B.identifier(prop.key.name)
) },
{ desc.set }
)
else
-- self.__members__[key] = desc.value
local base
if prop.static then
base = B.identifier("self")
else
base = B.memberExpression(
B.identifier("self"), B.identifier("__members__")
)
end
body[#body + 1] = B.assignmentExpression(
{ B.memberExpression(base, B.identifier(prop.key.name)) },
{ desc.value }
)
end
else
body[#body + 1] = self:get(node.body[i])
end
end
self.hoist[#self.hoist + 1] = B.localDeclaration({ name }, { })
local init = B.callExpression(
B.identifier('class'), {
B.literal(node.id.name), base,
B.functionExpression(
{ B.identifier('self'), B.identifier('super') },
B.blockStatement(body)
)
}
)
if node.export then
local expr = B.memberExpression(B.identifier('export'), name)
self.scope[#self.scope + 1] = B.assignmentExpression(
{ expr }, { init }
)
init = expr
end
return B.assignmentExpression(
{ name }, { init }
)
end
function match:SpreadExpression(node)
return B.callExpression(
B.identifier('__spread__'), { self:get(node.argument) }
)
end
function match:NilExpression(node)
return B.literal(nil)
end
function match:PropertyDefinition(node)
node.value.generator = node.generator
return self:get(node.value)
end
function match:BlockStatement(node)
return B.blockStatement(self:list(node.body))
end
function match:ExpressionStatement(node)
return B.expressionStatement(self:get(node.expression))
end
function match:CallExpression(node)
local callee = node.callee
if callee.type == 'MemberExpression' and not callee.computed then
if callee.object.type == 'SuperExpression' then
local args = self:list(node.arguments)
local recv = B.memberExpression(
B.identifier('super'),
self:get(callee.property)
)
table.insert(args, 1, B.identifier('self'))
return B.callExpression(recv, args)
else
if callee.namespace then
return B.callExpression(self:get(callee), self:list(node.arguments))
else
local recv = self:get(callee.object)
local prop = self:get(callee.property)
return B.sendExpression(recv, prop, self:list(node.arguments))
end
end
else
if callee.type == 'SuperExpression' then
local args = self:list(node.arguments)
local recv = B.memberExpression(
B.identifier('super'),
B.identifier('self')
)
table.insert(args, 1, B.identifier('self'))
return B.callExpression(recv, args)
else
local args = self:list(node.arguments)
--table.insert(args, 1, B.literal(nil))
return B.callExpression(self:get(callee), args)
end
end
end
function match:NewExpression(node)
return B.callExpression(B.identifier('new'), {
self:get(node.callee), unpack(self:list(node.arguments))
})
end
function match:WhileStatement(node)
local loop = B.identifier(util.genid())
local save = self.loop
self.loop = loop
local body = B.blockStatement{
self:get(node.body);
B.labelStatement(loop);
}
self.loop = save
return B.whileStatement(self:get(node.test), body)
end
function match:ForStatement(node)
local loop = B.identifier(util.genid())
local save = self.loop
self.loop = loop
local name = self:get(node.name)
local init = self:get(node.init)
local last = self:get(node.last)
local step = B.literal(node.step)
local body = B.blockStatement{
self:get(node.body);
B.labelStatement(loop)
}
self.loop = save
return B.forStatement(B.forInit(name, init), last, step, body)
end
function match:ForInStatement(node)
local loop = B.identifier(util.genid())
local save = self.loop
self.loop = loop
local none = B.tempnam()
local temp = B.tempnam()
local iter = B.callExpression(B.identifier('__each__'), { self:get(node.right) })
local left = { }
for i=1, #node.left do
left[i] = self:get(node.left[i])
end
local body = B.blockStatement{
self:get(node.body);
B.labelStatement(loop);
}
self.loop = save
return B.forInStatement(B.forNames(left), iter, body)
end
function match:RegExp(node)
return B.callExpression(
B.identifier('RegExp'), {
B.literal(node.pattern),
B.literal(node.flags)
}
)
end
function match:RangeExpression(node)
return B.callExpression(B.identifier('__range__'), {
self:get(node.min), self:get(node.max)
})
end
function match:ArrayPattern(node)
print(util.dump(node))
end
function match:ArrayExpression(node)
return B.callExpression(B.identifier('Array'), self:list(node.elements))
end
function match:TableExpression(node)
local properties = { }
for i=1, #node.members do
local prop = node.members[i]
local key, val
if prop.key then
if prop.key.type == 'Identifier' then
key = prop.key.name
elseif prop.key.type == "Literal" then
key = prop.key.value
end
else
assert(prop.type == "Identifier")
key = prop.name
end
local desc = properties[key] or { }
if prop.kind == 'get' then
desc.get = self:get(prop.value)
elseif prop.kind == 'set' then
desc.set = self:get(prop.value)
elseif prop.value then
desc.value = self:get(prop.value)
else
desc.value = B.identifier(key)
end
properties[key] = desc
end
for k,v in pairs(properties) do
properties[k] = B.table(v)
end
return B.sendExpression(
B.identifier('Object'), B.identifier("create"), {
B.literal(nil);
B.table(properties);
}
)
end
function match:RawString(node)
local list = { }
local tostring = B.identifier('tostring')
for i=1, #node.expressions do
local expr = node.expressions[i]
if type(expr) == 'string' then
list[#list + 1] = B.literal(expr)
else
list[#list + 1] = B.callExpression(tostring, { self:get(expr.expression) })
end
end
return B.listExpression('..', list)
end
function match:ArrayComprehension(node)
local temp = B.tempnam()
local body = B.blockStatement{
B.localDeclaration({ temp }, {
B.callExpression(B.identifier('Array'), { })
})
}
local last = body
for i=1, #node.blocks do
local loop = self:get(node.blocks[i])
local test = node.blocks[i].filter
if test then
local body = loop.body
local cond = B.ifStatement(self:get(test), body)
loop.body = B.blockStatement{ cond }
last.body[#last.body + 1] = loop
last = body
else
last.body[#last.body + 1] = loop
last = loop.body
end
end
last.body[#last.body + 1] = B.assignmentExpression({
B.memberExpression(temp, B.unaryExpression('#', temp), true)
}, {
self:get(node.body)
})
body.body[#body.body + 1] = B.returnStatement{ temp }
return B.callExpression(
B.parenExpression{
B.functionExpression({ }, body)
}, { }
)
end
function match:ComprehensionBlock(node)
local iter = B.callExpression(
B.identifier('__each__'), { self:get(node.right) }
)
local left = self:list(node.left)
local body = { }
return B.forInStatement(B.forNames(left), iter, B.blockStatement(body))
end
local function countln(src, pos, idx)
local line = 0
local index, limit = idx or 1, pos
while index <= limit do
local s, e = string.find(src, "\n", index, true)
if s == nil or e > limit then
break
end
index = e + 1
line = line + 1
end
return line
end
local function transform(tree, src)
local self = { }
self.line = 1
self.pos = 0
self.ctx = Context.new()
function self:sync(node)
local pos = node.pos
if pos ~= nil and pos > self.pos then
local prev = self.pos
local line = countln(src, pos, prev + 1) + self.line
self.line = line
self.pos = pos
end
end
function self:get(node, ...)
if not match[node.type] then
error("no handler for "..tostring(node.type))
end
self:sync(node)
local out = match[node.type](self, node, ...)
out.line = self.line
return out
end
function self:list(nodes, ...)
local list = { }
for i=1, #nodes do
list[#list + 1] = self:get(nodes[i], ...)
end
return list
end
return self:get(tree)
end
return {
transform = transform
}