Add a CExpressionStatement to wrap expressions instead of passing them into statement...
[fur] / transformation.py
1 import collections
2
3 import normalization
4 import parsing
5
6 CIntegerLiteral = collections.namedtuple(
7     'CIntegerLiteral',
8     [
9         'value',
10     ],
11 )
12
13 CStringLiteral = collections.namedtuple(
14     'CStringLiteral',
15     [
16         'index',
17         'value',
18     ],
19 )
20
21 CConstantExpression = collections.namedtuple(
22     'CConstantExpression',
23     [
24         'value'
25     ],
26 )
27
28 CVariableExpression = collections.namedtuple(
29     'CVariableExpression',
30     [
31         'variable',
32     ],
33 )
34
35 CSymbolExpression = collections.namedtuple(
36     'CSymbolExpression',
37     [
38         'symbol',
39         'symbol_list_index',
40     ],
41 )
42
43 CNegationExpression = collections.namedtuple(
44     'CNegationExpression',
45     [
46         'value',
47     ],
48 )
49
50 CFunctionCallForFurInfixOperator = collections.namedtuple(
51     'CFunctionCallForFurInfixOperator',
52     [
53         'name',
54         'left',
55         'right',
56     ],
57 )
58
59 CFunctionCallExpression = collections.namedtuple(
60     'CFunctionCallExpression',
61     [
62         'name',
63         'arguments',
64     ],
65 )
66
67 CSymbolAssignmentStatement = collections.namedtuple(
68     'CSymbolAssignmentStatement',
69     [
70         'target',
71         'target_symbol_list_index',
72         'expression',
73     ],
74 )
75
76 CVariableAssignmentStatement = collections.namedtuple(
77     'CVariableAssignmentStatement',
78     [
79         'variable',
80         'expression',
81     ],
82 )
83
84 CExpressionStatement = collections.namedtuple(
85     'CExpressionStatement',
86     [
87         'expression',
88     ],
89 )
90
91 CProgram = collections.namedtuple(
92     'CProgram',
93     [
94         'builtin_set',
95         'statements',
96         'standard_libraries',
97         'string_literal_list',
98         'symbol_list',
99     ],
100 )
101
102 EQUALITY_LEVEL_OPERATOR_TO_FUNCTION_NAME_MAPPING = {
103     '==':   'equals',
104     '!=':   'notEquals',
105     '<=':   'lessThanOrEqual',
106     '>=':   'greaterThanOrEqual',
107     '<':    'lessThan',
108     '>':    'greaterThan',
109 }
110
111 def transform_equality_level_expression(accumulators, expression):
112     # Transform expressions like 1 < 2 < 3 into expressions like 1 < 2 && 2 < 3
113     if isinstance(expression.left, parsing.FurInfixExpression) and expression.left.order == 'equality_level':
114         left = transform_equality_level_expression(
115             accumulators,
116             expression.left
117         )
118
119         middle = left.right
120
121         right = transform_expression(
122             accumulators,
123             expression.right,
124         )
125
126         # TODO Don't evaluate the middle expression twice
127         return CFunctionCallForFurInfixOperator(
128             name='and',
129             left=left,
130             right=CFunctionCallForFurInfixOperator(
131                 name=EQUALITY_LEVEL_OPERATOR_TO_FUNCTION_NAME_MAPPING[expression.operator],
132                 left=middle,
133                 right=right,
134             ),
135         )
136
137     return CFunctionCallForFurInfixOperator(
138         name=EQUALITY_LEVEL_OPERATOR_TO_FUNCTION_NAME_MAPPING[expression.operator],
139         left=transform_expression(accumulators, expression.left),
140         right=transform_expression(accumulators, expression.right),
141     )
142
143 BUILTINS = {
144     'false':    [],
145     'pow':      ['math.h'],
146     'print':    ['stdio.h'],
147     'true':     [],
148 }
149
150 def transform_variable_expression(accumulators, expression):
151     return CVariableExpression(variable=expression.variable)
152
153 def transform_expression(accumulators, expression):
154     if isinstance(expression, parsing.FurParenthesizedExpression):
155         # Parentheses can be removed because everything in the C output is explicitly parenthesized
156         return transform_expression(accumulators, expression.internal)
157
158     if isinstance(expression, parsing.FurNegationExpression):
159         return transform_negation_expression(accumulators, expression)
160
161     if isinstance(expression, parsing.FurFunctionCallExpression):
162         return transform_function_call_expression(accumulators, expression)
163
164     if isinstance(expression, parsing.FurSymbolExpression):
165         if expression.value in ['true', 'false']:
166             return CConstantExpression(value=expression.value)
167
168         if expression.value not in accumulators.symbol_list:
169             symbol_list.append(expression.value)
170
171         return CSymbolExpression(
172             symbol=expression.value,
173             symbol_list_index=accumulators.symbol_list.index(expression.value),
174         )
175
176     if isinstance(expression, parsing.FurStringLiteralExpression):
177         value = expression.value
178
179         try:
180             index = accumulators.string_literal_list.index(value)
181         except ValueError:
182             index = len(accumulators.string_literal_list)
183             accumulators.string_literal_list.append(value)
184
185         return CStringLiteral(index=index, value=value)
186
187     LITERAL_TYPE_MAPPING = {
188         parsing.FurIntegerLiteralExpression: CIntegerLiteral,
189     }
190
191     if type(expression) in LITERAL_TYPE_MAPPING:
192         return LITERAL_TYPE_MAPPING[type(expression)](value=expression.value)
193
194     if isinstance(expression, parsing.FurInfixExpression):
195         if expression.order == 'equality_level':
196             return transform_equality_level_expression(accumulators, expression)
197
198         INFIX_OPERATOR_TO_FUNCTION_NAME = {
199             '+':    'add',
200             '-':    'subtract',
201             '*':    'multiply',
202             '//':   'integerDivide',
203             '%':    'modularDivide',
204             'and':  'and',
205             'or':   'or',
206         }
207
208         return CFunctionCallForFurInfixOperator(
209             name=INFIX_OPERATOR_TO_FUNCTION_NAME[expression.operator],
210             left=transform_expression(accumulators, expression.left),
211             right=transform_expression(accumulators, expression.right),
212         )
213
214     # TODO Handle all possible types in this form
215     return {
216         normalization.NormalVariableExpression: transform_variable_expression,
217     }[type(expression)](accumulators, expression)
218
219 def transform_symbol_assignment_statement(accumulators, assignment_statement):
220     # TODO Check that target is not a builtin
221     if assignment_statement.target not in accumulators.symbol_list:
222         accumulators.symbol_list.append(assignment_statement.target)
223
224     return CSymbolAssignmentStatement(
225         target=assignment_statement.target,
226         target_symbol_list_index=accumulators.symbol_list.index(assignment_statement.target),
227         expression=transform_expression(
228             accumulators,
229             assignment_statement.expression,
230         ),
231     )
232
233 def transform_negation_expression(accumulators, negation_expression):
234     return CNegationExpression(
235         value=transform_expression(accumulators, negation_expression.value),
236     )
237
238 def transform_function_call_expression(accumulators, function_call):
239     if function_call.function.value in BUILTINS.keys():
240         # TODO Check that the builtin is actually callable
241         accumulators.builtin_set.add(function_call.function.value)
242
243         return CFunctionCallExpression(
244             name='builtin$' + function_call.function.value,
245             arguments=tuple(
246                 transform_expression(accumulators, arg)
247                 for arg in function_call.arguments
248             ),
249         )
250
251     raise Exception()
252
253 def transform_expression_statement(accumulators, statement):
254     expression = {
255         parsing.FurFunctionCallExpression: transform_function_call_expression,
256         normalization.NormalFunctionCallExpression: transform_function_call_expression,
257     }[type(statement.expression)](accumulators, statement.expression)
258
259     return CExpressionStatement(
260         expression=expression,
261     )
262
263 def transform_variable_assignment_statement(accumulators, statement):
264     return CVariableAssignmentStatement(
265         variable=statement.variable,
266         expression=transform_expression(accumulators, statement.expression),
267     )
268
269 def transform_statement(accumulators, statement):
270     return {
271         parsing.FurAssignmentStatement: transform_symbol_assignment_statement,
272         parsing.FurExpressionStatement: transform_expression_statement,
273         normalization.NormalVariableAssignmentStatement: transform_variable_assignment_statement,
274         normalization.NormalExpressionStatement: transform_expression_statement,
275     }[type(statement)](accumulators, statement)
276
277
278 Accumulators = collections.namedtuple(
279     'Accumulators',
280     [
281         'builtin_set',
282         'symbol_list',
283         'string_literal_list',
284     ],
285 )
286
287 def transform(program):
288     accumulators = Accumulators(
289         builtin_set=set(),
290         symbol_list=[],
291         string_literal_list=[],
292     )
293
294     statement_list = [
295         transform_statement(accumulators, statement) for statement in program.statement_list
296     ]
297
298     standard_library_set = set()
299     for builtin in accumulators.builtin_set:
300         for standard_library in BUILTINS[builtin]:
301             standard_library_set.add(standard_library)
302
303     return CProgram(
304         builtin_set=accumulators.builtin_set,
305         statements=statement_list,
306         standard_libraries=standard_library_set,
307         string_literal_list=accumulators.string_literal_list,
308         symbol_list=accumulators.symbol_list,
309     )
310
311
312 if __name__ == '__main__':
313     import unittest
314
315     unittest.main()