-
Notifications
You must be signed in to change notification settings - Fork 1
/
backend.py
188 lines (156 loc) · 4.82 KB
/
backend.py
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
"""
idris *.idr -o out.qb --codegen qb --cg-opt "--javaName" --cg-opt "--symemu"
requirements:
- pip install -U wisepy2
"""
from wisepy2 import wise
from io import StringIO
literal_map = {
'float': float,
'int': int,
'bigInt': int,
'char': str,
'string': str,
'bool': lambda x: bool(int(x)),
'unit': lambda _: None,
"symbol": str
}
def code_list_to_string(prefix, io, xs):
if isinstance(xs, list):
next_prefix = prefix + ' '
for each in xs:
code_list_to_string(next_prefix, io, each)
xs and io.write('\n')
return
assert isinstance(xs, str), xs
io.write(prefix)
io.write(xs)
io.write('\n')
def concat_stmts(xs):
ret = []
extend = list.extend
append = list.append
for x in xs:
(isinstance(x, list) and extend or append)(ret, x)
return ret
def concat_stmts_(ret, xs):
extend = list.extend
append = list.append
for x in xs:
(isinstance(x, list) and extend or append)(ret, x)
return ret
def mk_list(*args):
return args
class Generate:
@staticmethod
def ExternalCall(name, args):
return '__RTS.{}({})'.format(name, ', '.join(args))
@staticmethod
def ExternalVar(name):
return '__RTS.{}'.format(name)
@staticmethod
def Var(name):
return name
@staticmethod
def Call(name, args):
return '{}({})'.format(name, ', '.join(args))
@staticmethod
def Defun(name, args, body):
return ["def {}({}):".format(name, ','.join(args)), concat_stmts(body)]
@staticmethod
def Introduction(n):
return ["{} = None".format(n)]
@staticmethod
def Update(n, exp):
assert isinstance(exp, str)
return ["{} = {}".format(n, exp)]
@staticmethod
def Constant(n):
return repr(n)
@staticmethod
def Switch(var, xs, body):
ret = []
for i, [cc, stmts] in enumerate(xs):
head = i and "elif" or "if"
ret.append('{} {} == {}:'.format(head, var, cc))
ret.append(concat_stmts(stmts))
ret.append('else:')
ret.append(concat_stmts(body))
return ret
@staticmethod
def If(cond, t, e):
assert isinstance(cond, str)
assert isinstance(t, list)
assert isinstance(e, list)
return ['if {}:'.format(cond), concat_stmts(t), "else:", concat_stmts(e)]
@staticmethod
def EffectExpr(exp):
assert isinstance(exp, str)
return [exp]
@staticmethod
def Return(exp):
return ['return {}'.format(exp)]
@classmethod
def read_and_gen(cls, io):
ctor_stack = []
obj_stack = []
left_stack = []
left = 1
while True:
while left:
pats = io.readline().split()
dispatch = pats[0]
left -= 1
if dispatch == "constructor":
cons = pats[1]
n = int(pats[2])
left_stack.append(left)
left = n
ctor_stack.append((getattr(cls, cons), n))
elif dispatch == "literal":
kind = pats[1]
length = int(pats[2])
buf = io.read(length)
io.readline()
action = literal_map[kind]
if action is not None:
buf = action(buf)
obj_stack.append(buf)
elif dispatch == "list":
n = int(pats[1])
left_stack.append(left)
left = n
ctor_stack.append((mk_list, n))
else:
raise ValueError("malformed qb format")
try:
ctor, n = ctor_stack.pop()
except IndexError:
assert len(obj_stack) == 1
return obj_stack[0]
args = []
for _ in range(n):
args.append(obj_stack.pop())
args.reverse()
if ctor is mk_list:
v = args
else:
v = ctor(*args)
obj_stack.append(v)
left = left_stack.pop()
def main(filename: str, out: str):
"""
QB to Python Compiler
"""
with open(filename, newline='\n') as f:
io = StringIO()
for c in sum(Generate.read_and_gen(f), []):
code_list_to_string('', io, c)
if out.lower() == 'std':
print(io.getvalue())
else:
with open(out, 'w') as f:
f.write('from rts import RTS as __RTS\n')
f.write(io.getvalue())
if __name__ == '__main__':
wise(main)()