-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy paththe_super_tiny_compiler.py
234 lines (187 loc) · 5.71 KB
/
the_super_tiny_compiler.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
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
import copy
from string import digits
from string import ascii_lowercase
def tokenizer(program):
current = 0
tokens = []
while current < len(program):
char = program[current]
if char == '(':
tokens.append({
'type': 'paren',
'value': '('
})
current += 1
continue
if char == ')':
tokens.append({
'type': 'paren',
'value': ')'
})
current += 1
continue
if char == ' ':
current += 1
continue
numbers = [i for i in digits]
if char in numbers:
value = ''
while char in numbers:
value += char
current += 1
char = program[current]
tokens.append({
'type': 'number',
'value': value
})
continue
if char == '"':
value = ''
current += 1
char = program[current]
while char != '"':
value += char
current += 1
char = program[current]
tokens.append({
'type': 'string',
'value': value
})
continue
letters = [i for i in ascii_lowercase]
if char in letters:
value = ''
while char in letters:
value += char
current += 1
char = program[current]
tokens.append({
'type': 'name',
'value': value
})
continue
raise TypeError(f'I dont know what this character is {char}')
return tokens
def parser(tokens):
global current
current = 0
def walk():
global current
token = tokens[current]
if token['type'] == 'number':
current += 1
return {
'type': 'NumberLiteral',
'value': token['value']
}
if token['type'] == 'string':
current += 1
return {
'type': 'StringLiteral',
'value': token['value']
}
if token['type'] == 'paren' and token['value'] == '(':
current += 1
token = tokens[current]
node = {
'type': 'CallExpression',
'name': token['value'],
'params': []
}
current += 1
token = tokens[current]
while not token['type'] == 'paren' or (token['type'] == 'paren' and token['value'] != ')'):
node['params'].append(walk())
token = tokens[current]
current += 1
return node
raise TypeError(token['type'])
ast = {
'type': 'Program',
'body': []
}
while current < len(tokens):
ast['body'].append(walk())
return ast
def traverser(ast, visitor):
def traverse_array(array, parent):
for child in array:
traverse_node(child, parent)
def traverse_node(node, parent):
method = visitor.get(node['type'])
if method:
method(node, parent)
if node['type'] == 'Program':
traverse_array(node['body'], node)
elif node['type'] == 'CallExpression':
traverse_array(node['params'], node)
elif node['type'] == 'NumberLiteral' or 'StringLiteral':
pass
else:
raise TypeError(node['type'])
traverse_node(ast, None)
def transformer(ast):
new_ast = {
'type': 'Program',
'body': []
}
old_ast = ast
ast = copy.deepcopy(old_ast)
ast['_context'] = new_ast.get('body')
def number_literal(node, parent):
parent['_context'].append({
'type': 'NumberLiteral',
'value': node['value'],
})
def string_literal(node, parent):
parent['_context'].append({
'type': 'StringLiteral',
'value': node['value'],
})
def call_expression(node, parent):
expression = {
'type': 'CallExpression',
'callee': {
'type': 'Identifier',
'name': node['name']
},
'arguments': []
}
node['_context'] = expression['arguments']
if parent['type'] != 'CallExpression':
expression = {
'type': 'ExpressionStatement',
'expression': expression
}
parent['_context'].append(expression)
traverser(ast, {
'NumberLiteral': number_literal,
'StringLiteral': string_literal,
'CallExpression': call_expression,
})
return new_ast
def code_generator(node):
if node['type'] == 'Program':
return '\n'.join([code for code in map(code_generator, node['body'])])
elif node['type'] == 'ExpressionStatement':
return code_generator(node['expression']) + ';'
elif node['type'] == 'CallExpression':
callee = code_generator(node['callee'])
params = ', '.join([code for code in map(code_generator, node['arguments'])])
return f'{callee}({params})'
elif node['type'] == 'Identifier':
return node['name']
elif node['type'] == 'NumberLiteral':
return node['value']
elif node['type'] == 'StringLiteral':
return '"' + node['value'] + '"'
else:
raise TypeError(node['type'])
def compiler(program):
tokens = tokenizer(program)
ast = parser(tokens)
new_ast = transformer(ast)
output = code_generator(new_ast)
return output
if __name__ == '__main__':
output = compiler('(add 2 (subtract 4 2))')