-
Notifications
You must be signed in to change notification settings - Fork 31
Expand file tree
/
Copy pathnodevisitor.py
More file actions
595 lines (452 loc) · 17.7 KB
/
Copy pathnodevisitor.py
File metadata and controls
595 lines (452 loc) · 17.7 KB
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
"""Node visitor"""
import ast
from .binopdesc import BinaryOperationDesc
from .boolopdesc import BooleanOperationDesc
from .cmpopdesc import CompareOperationDesc
from .nameconstdesc import NameConstantDesc
from .unaryopdesc import UnaryOperationDesc
from .context import Context
from .loopcounter import LoopCounter
from .tokenendmode import TokenEndMode
class NodeVisitor(ast.NodeVisitor):
LUACODE = "[[luacode]]"
"""Node visitor"""
def __init__(self, context=None, config=None):
self.context = context if context is not None else Context()
self.config = config
self.last_end_mode = TokenEndMode.LINE_FEED
self.output = []
def visit_Assign(self, node):
"""Visit assign"""
target = self.visit_all(node.targets[0], inline=True)
value = self.visit_all(node.value, inline=True)
local_keyword = ""
last_ctx = self.context.last()
if last_ctx["class_name"]:
target = ".".join([last_ctx["class_name"], target])
if "." not in target and not last_ctx["locals"].exists(target):
local_keyword = "local "
last_ctx["locals"].add_symbol(target)
self.emit("{local}{target} = {value}".format(local=local_keyword,
target=target,
value=value))
def visit_AugAssign(self, node):
"""Visit augassign"""
operation = BinaryOperationDesc.OPERATION[node.op.__class__]
target = self.visit_all(node.target, inline=True)
values = {
"left": target,
"right": self.visit_all(node.value, inline=True),
"operation": operation["value"],
}
line = "({})".format(operation["format"])
line = line.format(**values)
self.emit("{target} = {line}".format(target=target, line=line))
def visit_Attribute(self, node):
"""Visit attribute"""
line = "{object}.{attr}"
values = {
"object": self.visit_all(node.value, True),
"attr": node.attr,
}
self.emit(line.format(**values))
def visit_BinOp(self, node):
"""Visit binary operation"""
operation = BinaryOperationDesc.OPERATION[node.op.__class__]
line = "({})".format(operation["format"])
values = {
"left": self.visit_all(node.left, True),
"right": self.visit_all(node.right, True),
"operation": operation["value"],
}
self.emit(line.format(**values))
def visit_BoolOp(self, node):
"""Visit boolean operation"""
operation = BooleanOperationDesc.OPERATION[node.op.__class__]
line = "({})".format(operation["format"])
values = {
"left": self.visit_all(node.values[0], True),
"right": self.visit_all(node.values[1], True),
"operation": operation["value"],
}
self.emit(line.format(**values))
def visit_Break(self, node):
"""Visit break"""
self.emit("break")
def visit_Call(self, node):
"""Visit function call"""
line = "{name}({arguments})"
name = self.visit_all(node.func, inline=True)
arguments = [self.visit_all(arg, inline=True) for arg in node.args]
self.emit(line.format(name=name, arguments=", ".join(arguments)))
def visit_ClassDef(self, node):
"""Visit class definition"""
bases = [self.visit_all(base, inline=True) for base in node.bases]
local_keyword = ""
last_ctx = self.context.last()
if not last_ctx["class_name"] and not last_ctx["locals"].exists(node.name):
local_keyword = "local "
last_ctx["locals"].add_symbol(node.name)
name = node.name
if last_ctx["class_name"]:
name = ".".join([last_ctx["class_name"], name])
values = {
"local": local_keyword,
"name": name,
"node_name": node.name,
}
self.emit("{local}{name} = class(function({node_name})".format(**values))
self.context.push({"class_name": node.name})
self.visit_all(node.body)
self.context.pop()
self.output[-1].append("return {node_name}".format(**values))
self.emit("end, {{{}}})".format(", ".join(bases)))
# Return class object only in the top-level classes.
# Not in the nested classes.
if self.config["class"]["return_at_the_end"] and not last_ctx["class_name"]:
self.emit("return {}".format(name))
def visit_Compare(self, node):
"""Visit compare"""
line = ""
left = self.visit_all(node.left, inline=True)
for i in range(len(node.ops)):
operation = node.ops[i]
operation = CompareOperationDesc.OPERATION[operation.__class__]
right = self.visit_all(node.comparators[i], inline=True)
values = {
"left": left,
"right": right,
}
if isinstance(operation, str):
values["op"] = operation
line += "{left} {op} {right}".format(**values)
elif isinstance(operation, dict):
line += operation["format"].format(**values)
if i < len(node.ops) - 1:
left = right
line += " and "
self.emit("({})".format(line))
def visit_Continue(self, node):
"""Visit continue"""
last_ctx = self.context.last()
line = "goto {}".format(last_ctx["loop_label_name"])
self.emit(line)
def visit_Delete(self, node):
"""Visit delete"""
targets = [self.visit_all(target, inline=True) for target in node.targets]
nils = ["nil" for _ in targets]
line = "{targets} = {nils}".format(targets=", ".join(targets),
nils=", ".join(nils))
self.emit(line)
def visit_Dict(self, node):
"""Visit dictionary"""
keys = []
for key in node.keys:
value = self.visit_all(key, inline=True)
if isinstance(key, ast.Str):
value = "[{}]".format(value)
keys.append(value)
values = [self.visit_all(item, inline=True) for item in node.values]
elements = ["{} = {}".format(keys[i], values[i]) for i in range(len(keys))]
elements = ", ".join(elements)
self.emit("dict {{{}}}".format(elements))
def visit_DictComp(self, node):
"""Visit dictionary comprehension"""
self.emit("(function()")
self.emit("local result = dict {}")
ends_count = 0
for comp in node.generators:
line = "for {target} in {iterator} do"
values = {
"target": self.visit_all(comp.target, inline=True),
"iterator": self.visit_all(comp.iter, inline=True),
}
line = line.format(**values)
self.emit(line)
ends_count += 1
for if_ in comp.ifs:
line = "if {} then".format(self.visit_all(if_, inline=True))
self.emit(line)
ends_count += 1
line = "result[{key}] = {value}"
values = {
"key": self.visit_all(node.key, inline=True),
"value": self.visit_all(node.value, inline=True),
}
self.emit(line.format(**values))
self.emit(" ".join(["end"] * ends_count))
self.emit("return result")
self.emit("end)()")
def visit_Ellipsis(self, node):
"""Visit ellipsis"""
self.emit("...")
def visit_Expr(self, node):
"""Visit expr"""
expr_is_docstring = False
if isinstance(node.value, ast.Str):
expr_is_docstring = True
self.context.push({"docstring": expr_is_docstring})
output = self.visit_all(node.value)
self.context.pop()
self.output.append(output)
def visit_FunctionDef(self, node):
"""Visit function definition"""
line = "{local}function {name}({arguments})"
last_ctx = self.context.last()
name = node.name
if last_ctx["class_name"]:
name = ".".join([last_ctx["class_name"], name])
arguments = [arg.arg for arg in node.args.args]
if node.args.vararg is not None:
arguments.append("...")
local_keyword = ""
if "." not in name and not last_ctx["locals"].exists(name):
local_keyword = "local "
last_ctx["locals"].add_symbol(name)
function_def = line.format(local=local_keyword,
name=name,
arguments=", ".join(arguments))
self.emit(function_def)
self.context.push({"class_name": ""})
self.visit_all(node.body)
self.context.pop()
body = self.output[-1]
if node.args.vararg is not None:
line = "local {name} = list {{...}}".format(name=node.args.vararg.arg)
body.insert(0, line)
arg_index = -1
for i in reversed(node.args.defaults):
line = "{name} = {name} or {value}"
arg = node.args.args[arg_index]
values = {
"name": arg.arg,
"value": self.visit_all(i, inline=True),
}
body.insert(0, line.format(**values))
arg_index -= 1
self.emit("end")
for decorator in reversed(node.decorator_list):
decorator_name = self.visit_all(decorator, inline=True)
values = {
"name": name,
"decorator": decorator_name,
}
line = "{name} = {decorator}({name})".format(**values)
self.emit(line)
def visit_For(self, node):
"""Visit for loop"""
line = "for {target} in {iter} do"
values = {
"target": self.visit_all(node.target, inline=True),
"iter": self.visit_all(node.iter, inline=True),
}
self.emit(line.format(**values))
continue_label = LoopCounter.get_next()
self.context.push({
"loop_label_name": continue_label,
})
self.visit_all(node.body)
self.context.pop()
self.output[-1].append("::{}::".format(continue_label))
self.emit("end")
def visit_Global(self, node):
"""Visit globals"""
last_ctx = self.context.last()
for name in node.names:
last_ctx["globals"].add_symbol(name)
def visit_If(self, node):
"""Visit if"""
test = self.visit_all(node.test, inline=True)
line = "if {} then".format(test)
self.emit(line)
self.visit_all(node.body)
if node.orelse:
if isinstance(node.orelse[0], ast.If):
elseif = node.orelse[0]
elseif_test = self.visit_all(elseif.test, inline=True)
line = "elseif {} then".format(elseif_test)
self.emit(line)
output_length = len(self.output)
self.visit_If(node.orelse[0])
del self.output[output_length]
del self.output[-1]
else:
self.emit("else")
self.visit_all(node.orelse)
self.emit("end")
def visit_IfExp(self, node):
"""Visit if expression"""
line = "{cond} and {true_cond} or {false_cond}"
values = {
"cond": self.visit_all(node.test, inline=True),
"true_cond": self.visit_all(node.body, inline=True),
"false_cond": self.visit_all(node.orelse, inline=True),
}
self.emit(line.format(**values))
def visit_Import(self, node):
"""Visit import"""
line = 'local {asname} = require "{name}"'
values = {"asname": "", "name": ""}
if node.names[0].asname is None:
values["name"] = node.names[0].name
values["asname"] = values["name"]
values["asname"] = values["asname"].split(".")[-1]
else:
values["asname"] = node.names[0].asname
values["name"] = node.names[0].name
self.emit(line.format(**values))
def visit_Index(self, node):
"""Visit index"""
self.emit(self.visit_all(node.value, inline=True))
def visit_Lambda(self, node):
"""Visit lambda"""
line = "function({arguments}) return"
arguments = [arg.arg for arg in node.args.args]
function_def = line.format(arguments=", ".join(arguments))
output = []
output.append(function_def)
output.append(self.visit_all(node.body, inline=True))
output.append("end")
self.emit(" ".join(output))
def visit_List(self, node):
"""Visit list"""
elements = [self.visit_all(item, inline=True) for item in node.elts]
line = "list {{{}}}".format(", ".join(elements))
self.emit(line)
def visit_ListComp(self, node):
"""Visit list comprehension"""
self.emit("(function()")
self.emit("local result = list {}")
ends_count = 0
for comp in node.generators:
line = "for {target} in {iterator} do"
values = {
"target": self.visit_all(comp.target, inline=True),
"iterator": self.visit_all(comp.iter, inline=True),
}
line = line.format(**values)
self.emit(line)
ends_count += 1
for if_ in comp.ifs:
line = "if {} then".format(self.visit_all(if_, inline=True))
self.emit(line)
ends_count += 1
line = "result.append({})"
line = line.format(self.visit_all(node.elt, inline=True))
self.emit(line)
self.emit(" ".join(["end"] * ends_count))
self.emit("return result")
self.emit("end)()")
def visit_Module(self, node):
"""Visit module"""
self.visit_all(node.body)
self.output = self.output[0]
def visit_Name(self, node):
"""Visit name"""
self.emit(node.id)
def visit_NameConstant(self, node):
"""Visit name constant"""
self.emit(NameConstantDesc.NAME[node.value])
def visit_Num(self, node):
"""Visit number"""
self.emit(str(node.n))
def visit_Pass(self, node):
"""Visit pass"""
pass
def visit_Return(self, node):
"""Visit return"""
line = "return "
line += self.visit_all(node.value, inline=True)
self.emit(line)
def visit_Starred(self, node):
"""Visit starred object"""
value = self.visit_all(node.value, inline=True)
line = "unpack({})".format(value)
self.emit(line)
def visit_Str(self, node):
"""Visit str"""
value = node.s
if value.startswith(NodeVisitor.LUACODE):
value = value[len(NodeVisitor.LUACODE):]
self.emit(value)
elif self.context.last()["docstring"]:
self.emit('--[[ {} ]]'.format(node.s))
else:
self.emit('"{}"'.format(node.s))
def visit_Subscript(self, node):
"""Visit subscript"""
line = "{name}[{index}]"
values = {
"name": self.visit_all(node.value, inline=True),
"index": self.visit_all(node.slice, inline=True),
}
self.emit(line.format(**values))
def visit_Tuple(self, node):
"""Visit tuple"""
elements = [self.visit_all(item, inline=True) for item in node.elts]
self.emit(", ".join(elements))
def visit_UnaryOp(self, node):
"""Visit unary operator"""
operation = UnaryOperationDesc.OPERATION[node.op.__class__]
value = self.visit_all(node.operand, inline=True)
line = operation["format"]
values = {
"value": value,
"operation": operation["value"],
}
self.emit(line.format(**values))
def visit_While(self, node):
"""Visit while"""
test = self.visit_all(node.test, inline=True)
self.emit("while {} do".format(test))
continue_label = LoopCounter.get_next()
self.context.push({
"loop_label_name": continue_label,
})
self.visit_all(node.body)
self.context.pop()
self.output[-1].append("::{}::".format(continue_label))
self.emit("end")
def visit_With(self, node):
"""Visit with"""
self.emit("do")
self.visit_all(node.body)
body = self.output[-1]
lines = []
for i in node.items:
line = ""
if i.optional_vars is not None:
line = "local {} = "
line = line.format(self.visit_all(i.optional_vars,
inline=True))
line += self.visit_all(i.context_expr, inline=True)
lines.append(line)
for line in lines:
body.insert(0, line)
self.emit("end")
def generic_visit(self, node):
"""Unknown nodes handler"""
raise RuntimeError("Unknown node: {}".format(node))
def visit_all(self, nodes, inline=False):
"""Visit all nodes in the given list"""
if not inline:
last_ctx = self.context.last()
last_ctx["locals"].push()
visitor = NodeVisitor(context=self.context, config=self.config)
if isinstance(nodes, list):
for node in nodes:
visitor.visit(node)
if not inline:
self.output.append(visitor.output)
else:
visitor.visit(nodes)
if not inline:
self.output.extend(visitor.output)
if not inline:
last_ctx = self.context.last()
last_ctx["locals"].pop()
if inline:
return " ".join(visitor.output)
def emit(self, value):
"""Add translated value to the output"""
self.output.append(value)