Peano
Loading...
Searching...
No Matches
Parser.py
Go to the documentation of this file.
1import ast_comments as ast, inspect
2from collections.abc import Sequence
4from exahype2.api.PDETerm import PDETerm
5
6class Parser:
7 def _parse_string(self, string: str) -> AST.External:
8 if "." in string:
9 sections = string.split(".")
10 if len(sections) != 2:
11 raise Exception("External format is not supported")
12 struct_name = AST.Name(sections[0])
13 if struct_name not in self.struct_map:
14 raise Exception(f"Struct does not exist in struct_map: {struct_name.id}")
15 struct_type = self.struct_map[struct_name]
16 field_name = AST.Name(sections[1])
17 return AST.ExternalStructField(struct_name, struct_type, field_name)
18 else:
19 return AST.External(string)
20
21 def _parse_constant(self, constant: ast.Constant) -> AST.Element | AST.External:
22 if type(constant.value) == int:
23 return AST.Integer(constant.value)
24 if type(constant.value) == float:
25 return AST.Float(constant.value)
26 if type(constant.value) == str:
27 return self._parse_string(constant.value)
28 raise Exception(f"Constant type is not supported: {type(constant.value)}")
29
30 def _parse_variable(self, name: ast.Name) -> AST.Variable:
31 return AST.Variable(AST.Name(name.id))
32
33 def _parse_data_block_constructor(self, constructor: ast.Call) -> AST.DataBlock:
34 if len(constructor.args) < 2 or len(constructor.args) > 3:
35 raise Exception(f"DataBlock constructor expects 2 or 3 arguments, where the third is an optional type specifier: {len(constructor.args)} provided")
36
37 # Argument 1 is the iteration range
38 iteration_range: list[list[AST.Element | AST.Variable]] = []
39 assert(type(constructor.args[0]) == ast.List)
40 for interval in constructor.args[0].elts:
41 assert(type(interval) == ast.List)
42 if (len(interval.elts) != 2):
43 raise Exception("DataBlock constructor intervals must be a list of 2 integers")
44 interval_start = self._parse_expression(interval.elts[0])
45 interval_end = self._parse_expression(interval.elts[1])
46 if isinstance(interval_start.get_type(), AST.TInteger) and isinstance(interval_end.get_type(), AST.TInteger):
47 assert(isinstance(interval_start, AST.Element) or isinstance(interval_start, AST.Variable))
48 assert(isinstance(interval_end, AST.Element) or isinstance(interval_end, AST.Variable))
49 interval_start = interval_start.convert_integers_to_indices()
50 interval_end = interval_end.convert_integers_to_indices()
51 iteration_range.append([interval_start, interval_end])
52 else:
53 raise Exception("DataBlock iteration ranges must be specified with integers")
54
55 # Argument 2 is the source of the DataBlock's data
56 source = self._parse_expression(constructor.args[1])
57 if not (isinstance(source, AST.Element) or isinstance(source, AST.ExternalStructField) or isinstance(source, AST.FunctionCall)):
58 raise Exception(f"DataBlock source is not a supported: {type(source)}")
59
60 if isinstance(source, AST.ExternalStructField):
61 flatten_array_representation = source.struct_type.fields[source.field_name].flatten
62 else:
63 flatten_array_representation = AST.TArray.flatten_temporaries
64
65 return AST.DataBlock(iteration_range, source, flatten=flatten_array_representation)
66
67 def _parse_evaluation(self, call: ast.Call) -> AST.FunctionCall:
68 function_name = self._parse_expression(call.args[0])
69 assert(isinstance(function_name, AST.External))
70 function_name = AST.Name(function_name.reference)
71 if function_name not in self.function_map:
72 raise Exception(f"Function name is not recognised: {function_name.id}")
73 arguments = [self._parse_expression(argument) for argument in call.args[1:]]
74 return AST.FunctionCall(function_name, arguments, self.function_map[function_name], stateless = self.stateless)
75
76 def parse_call(self, call: ast.Call) -> AST.Expression | AST.FunctionCall:
77 assert(type(call.func) == ast.Name)
78 match call.func.id:
79 case "DataBlock":
80 return self._parse_data_block_constructor(call)
81 case "Integer":
82 assert(isinstance(call.args[0], ast.Constant))
83 assert(isinstance(call.args[0].value, str))
84 return AST.Integer(self._parse_string(call.args[0].value))
85 case "eval":
86 return self._parse_evaluation(call)
87 case "max":
88 if len(call.args) == 1:
89 operand = self._parse_expression(call.args[0])
90 assert(isinstance(operand, AST.Variable) and isinstance(operand.get_type(), AST.TDataBlock))
91 return AST.DataBlockUnaryOperation(AST.Operator.MAX, operand)
92 if len(call.args) == 2:
93 lhs = self._parse_expression(call.args[0])
94 rhs = self._parse_expression(call.args[1])
95 if isinstance(lhs.get_type(), AST.TElement) and isinstance(rhs.get_type(), AST.TElement):
96 assert(isinstance(lhs, AST.Element) or isinstance(lhs, AST.Variable))
97 assert(isinstance(rhs, AST.Element) or isinstance(rhs, AST.Variable))
98 return AST.ElementBinaryOperation(AST.Operator.MAX, lhs, rhs)
99 else:
100 return AST.DataBlockBinaryOperation(AST.Operator.MAX, lhs, rhs)
101 raise Exception("Unknown format for max: 1 or 2 arguments expected")
102
103 case _:
104 if AST.Name(call.func.id) in AST.Variable.symbol_map:
105 assert(isinstance(AST.Variable.symbol_map[AST.Name(call.func.id)].get_type(), AST.TDataBlock))
106 index = self._parse_expression(call.args[0])
107 assert(isinstance(index, AST.Integer))
108 index = index.convert_integers_to_indices()
109 return AST.DataBlockIndex(AST.Variable(AST.Name(call.func.id)), index)
110
111 raise Exception(f"Function name is not supported: {call.func.id}")
112
113 def parse_unary_operation(self, operation: ast.UnaryOp) -> AST.ElementUnaryOperation | AST.DataBlockUnaryOperation | AST.Element:
114 if isinstance(operation.op, ast.USub):
115 operand = self._parse_expression(operation.operand)
116 if isinstance(operand.get_type(), AST.TElement):
117 assert(isinstance(operand, AST.Element) or isinstance(operand, AST.Variable))
118 if isinstance(operand, AST.Integer) and isinstance(operand.value, int):
119 return AST.Integer(-operand.value)
120 return AST.ElementUnaryOperation(AST.Operator.SUBTRACTION, operand)
121 else:
122 return AST.DataBlockUnaryOperation(AST.Operator.SUBTRACTION, operand)
123 raise Exception("Only minus is supported among unary operations")
124
125 def parse_binary_operation(self, operation: ast.BinOp) -> AST.ElementBinaryOperation | AST.DataBlockBinaryOperation | AST.Element:
126 lhs = self._parse_expression(operation.left)
127 rhs = self._parse_expression(operation.right)
128
129 if isinstance(lhs.get_type(), AST.TElement) and isinstance(rhs.get_type(), AST.TElement):
130 assert(isinstance(lhs, AST.Element) or isinstance(lhs, AST.Variable))
131 assert(isinstance(rhs, AST.Element) or isinstance(rhs, AST.Variable))
132
133 # If both arguments are integers, the operation should be evaluated immediately
134 if isinstance(lhs, AST.Integer) and isinstance(lhs.value, int) and \
135 isinstance(rhs, AST.Integer) and isinstance(rhs.value, int):
136 if isinstance(operation.op, ast.Add):
137 return AST.Integer(lhs.value + rhs.value)
138 if isinstance(operation.op, ast.Sub):
139 return AST.Integer(lhs.value - rhs.value)
140 if isinstance(operation.op, ast.Mult):
141 return AST.Integer(lhs.value * rhs.value)
142
143 if isinstance(operation.op, ast.Add):
144 return AST.ElementBinaryOperation(AST.Operator.ADDITION, lhs, rhs)
145 if isinstance(operation.op, ast.Sub):
146 return AST.ElementBinaryOperation(AST.Operator.SUBTRACTION, lhs, rhs)
147 if isinstance(operation.op, ast.Mult):
148 return AST.ElementBinaryOperation(AST.Operator.MULTIPLICATION, lhs, rhs)
149 if isinstance(operation.op, ast.Div):
150 return AST.ElementBinaryOperation(AST.Operator.DIVISION, lhs, rhs)
151 else:
152 if isinstance(operation.op, ast.Add):
153 return AST.DataBlockBinaryOperation(AST.Operator.ADDITION, lhs, rhs)
154 if isinstance(operation.op, ast.Sub):
155 return AST.DataBlockBinaryOperation(AST.Operator.SUBTRACTION, lhs, rhs)
156 if isinstance(operation.op, ast.Mult):
157 return AST.DataBlockBinaryOperation(AST.Operator.MULTIPLICATION, lhs, rhs)
158 if isinstance(operation.op, ast.Div):
159 return AST.DataBlockBinaryOperation(AST.Operator.DIVISION, lhs, rhs)
160
161 def parse_slice(self, slice: ast.Slice, original_iteration_range: Sequence[AST.Element | AST.Variable]) -> list[AST.Element | AST.Variable]:
162 if slice.lower is None:
163 slice_start = original_iteration_range[0]
164 else:
165 slice_start = self._parse_expression(slice.lower)
166 assert(isinstance(slice_start, AST.Element) or isinstance(slice_start, AST.Variable))
167 slice_start = slice_start.convert_integers_to_indices()
168
169 if slice.upper is None:
170 slice_end = original_iteration_range[1]
171 else:
172 slice_end = self._parse_expression(slice.upper)
173 assert(isinstance(slice_end, AST.Element) or isinstance(slice_end, AST.Variable))
174 slice_end = slice_end.convert_integers_to_indices()
175
176 return [slice_start, slice_end]
177
178 def parse_subscript(self, subscript: ast.Subscript) -> AST.DataBlockSlice:
179 base = self._parse_expression(subscript.value)
180 assert(isinstance(base, AST.Variable))
181 base_value = base.get_value()
182 assert(isinstance(base_value, AST.DataBlock))
183
184 iteration_range: list[list[AST.Element | AST.Variable]] = []
185 if isinstance(subscript.slice, ast.Tuple):
186 for i, interval in enumerate(subscript.slice.elts):
187 assert(isinstance(interval, ast.Slice))
188 slice = self.parse_slice(interval, base_value.iteration_range[i])
189 iteration_range.append(slice)
190 else:
191 assert(isinstance(subscript.slice, ast.Slice))
192 slice = self.parse_slice(subscript.slice, base_value.iteration_range[0])
193 iteration_range.append(slice)
194
195 for i in range(len(iteration_range), len(base_value.iteration_range)):
196 iteration_range.append([base_value.iteration_range[i][0], base_value.iteration_range[i][1]])
197 return AST.DataBlockSlice(base, iteration_range)
198
199 def _parse_assignable_expression(self, expression: ast.expr) -> AST.AssignableExpression:
200 if isinstance(expression, ast.Name):
201 return self._parse_variable(expression)
202 if isinstance(expression, ast.Subscript):
203 return self.parse_subscript(expression)
204 raise Exception(f"Expression type is not supported or is not assignable: {type(expression)}")
205
206 def _parse_expression(self, expression: ast.expr) -> AST.Expression:
207 if isinstance(expression, ast.Constant):
208 return self._parse_constant(expression)
209 if isinstance(expression, ast.Name):
210 for external_variable in self.external_variables.keys():
211 if external_variable.name.id == expression.id:
212 if isinstance(external_variable.type, AST.TInteger):
213 value = self.external_variables[external_variable]
214 assert(isinstance(value, int))
215 return AST.Integer(value)
216 if isinstance(external_variable.type, AST.TFloat):
217 value = self.external_variables[external_variable]
218 assert(isinstance(value, float))
219 return AST.Float(value)
220 return self._parse_variable(expression)
221 if isinstance(expression, ast.Call):
222 return self.parse_call(expression)
223 if isinstance(expression, ast.BinOp):
224 return self.parse_binary_operation(expression)
225 if isinstance(expression, ast.UnaryOp):
226 return self.parse_unary_operation(expression)
227 if isinstance(expression, ast.Subscript):
228 return self.parse_subscript(expression)
229 raise Exception(f"Expression type is not supported: {type(expression)}")
230
231 def parse_data_block_construction(self, lhs: AST.Variable, rhs: AST.DataBlock) -> list[AST.Statement]:
232 if isinstance(rhs.value, AST.Element):
233 return [AST.DataBlockConstructionFromElement(lhs, rhs)]
234 if isinstance(rhs.value, AST.External):
235 return [AST.DataBlockConstructionFromExternal(lhs, rhs)]
236 if isinstance(rhs.value, AST.FunctionCall):
237 return [AST.DataBlockConstructionFromFunctionCall(lhs, rhs)]
238 if isinstance(rhs, AST.DataBlockBinaryOperation):
239 return [AST.DataBlockConstructionFromOperation(lhs, rhs)]
240 raise Exception(f"Source type for DataBlock is not supported: {rhs.value}")
241
242 def _parse_construction(self, assignment: ast.Assign) -> list[AST.Statement]:
243 lhs = self._parse_assignable_expression(assignment.targets[0])
244 assert(type(lhs) == AST.Variable)
245
246 rhs = self._parse_expression(assignment.value)
247 if isinstance(rhs, AST.DataBlock):
248 return self.parse_data_block_construction(lhs, rhs)
249 return [AST.Construction(lhs, rhs)]
250
251 def _parse_assignment_without_construction(self, assignment: ast.Assign) -> list[AST.Statement]:
252 lhs = self._parse_assignable_expression(assignment.targets[0])
253 rhs = self._parse_expression(assignment.value)
254
255 if (isinstance(lhs.get_type(), AST.TDataBlock) or isinstance(rhs.get_type(), AST.TDataBlock)):
256 # For a DataBlock assignment it is ok for the rhs to not be a DataBlock, but the lhs must be
257 if not isinstance(lhs.get_type(), AST.TDataBlock):
258 raise Exception("LHS of data block assignment must be a data block")
259 if isinstance(rhs, AST.DataBlockUnaryOperation) and rhs.operator == AST.Operator.MAX:
260 return [AST.DataBlockUnaryMax(lhs, rhs.operand)]
261 return [AST.DataBlockAssignment(lhs, rhs)]
262
263 return [AST.Assignment(lhs, rhs)]
264
265 def _parse_assignment(self, assignment: ast.Assign) -> list[AST.Statement]:
266 lhs = self._parse_expression(assignment.targets[0])
267 if not isinstance(lhs, AST.AssignableExpression):
268 raise Exception(f"LHS of assignment must be an assignable value: {type(lhs)} was given")
269
270 if lhs.get_name() in AST.Variable.symbol_map:
271 return self._parse_assignment_without_construction(assignment)
272 else:
273 return self._parse_construction(assignment)
274
275 def _parse_if(self, if_statement: ast.If) -> list[AST.Statement]:
276 pde_term_is_in_use = False
277 assert(isinstance(if_statement.test, ast.Name))
278 test = if_statement.test.id
279
280 for pde_term in self.enabled_pde_terms:
281 if pde_term.NAME == test or type(pde_term).__name__ == test:
282 pde_term_is_in_use = True
283
284 statements: list[AST.Statement] = []
285 if pde_term_is_in_use:
286 for s in if_statement.body:
287 statements.extend(self._parse_statement(s))
288 return statements
289
290 def _parse_statement(self, statement: ast.stmt) -> list[AST.Statement]:
291 try:
292 if isinstance(statement, ast.Assign):
293 return self._parse_assignment(statement)
294 if isinstance(statement, ast.If):
295 return self._parse_if(statement)
296 if isinstance(statement, ast.Comment):
297 return [AST.Comment(statement.value[1:])]
298 raise Exception(f"Statement type is not supported: {type(statement)}")
299
300 except Exception as exception:
301 if len(exception.args) > 0:
302 raise Exception(f"Error on line {self.line_number}: {exception.args[0]}")
303 raise Exception(f"Error on line {self.line_number}")
304
305 def _parse_function(self, function: ast.FunctionDef, function_id: str|None, function_namespace: list[str], function_arguments: list[AST.Argument], stateless: bool) -> AST.Function:
306 if function_id is None:
307 function_name = AST.Name(function.name)
308 else:
309 function_name = AST.Name(function_id)
310
311 parsed_function = AST.Function(function_name, function_namespace, stateless)
312 parsed_function.function_map = self.function_map
313 parsed_function.add_arguments(function_arguments)
314
315 for statement in function.body:
316 parsed_function.add_statements(self._parse_statement(statement))
317 self.line_number = self.line_number + 1
318
319 array_allocations = AST.ArrayAllocation.array_allocations.copy()
320 for array_allocation in array_allocations:
321 parsed_function.add_statements([AST.ArrayDeallocation(array_allocation)])
322
323 return parsed_function
324
325 def parse(self, function, function_id: str|None = None, function_namespace: list[str] = [], function_arguments: list[AST.Argument] = [], function_map: dict[AST.Name, AST.TFunction] = {}, enabled_pde_terms: list[PDETerm] = [], external_variables: dict[AST.Argument,int|float] = {}, stateless: bool = False) -> AST.Function:
326 self.line_number = 1
327 self.enabled_pde_terms = enabled_pde_terms
328 self.external_variables = external_variables
329 self.function_map = function_map
330 self.stateless = stateless
331
332 AST.Variable.symbol_map = {}
333 AST.ArrayAllocation.array_allocations = []
334
335 self.struct_map: dict[AST.Name, AST.TStruct] = {}
336 for argument in function_arguments:
337 if isinstance(argument.type, AST.TStruct):
338 self.struct_map.update({argument.name: argument.type})
339
340 source_code = inspect.getsource(function)
341 module = ast.parse(source_code)
342 assert (isinstance(module, ast.Module))
343 function_definition = module.body[0]
344 assert isinstance(function_definition, ast.FunctionDef)
345
346 function = self._parse_function(function_definition, function_id, function_namespace, function_arguments, stateless)
347 return function
#define assert(...)
Definition LinuxAMD.h:28
Represents one named, point-wise PDE operator that a solver exposes for the user to implement: a C++ ...
Definition PDETerm.py:6
AST.AssignableExpression _parse_assignable_expression(self, ast.expr expression)
Definition Parser.py:199
AST.DataBlockSlice parse_subscript(self, ast.Subscript subscript)
Definition Parser.py:178
list[AST.Statement] _parse_statement(self, ast.stmt statement)
Definition Parser.py:290
AST.Expression|AST.FunctionCall parse_call(self, ast.Call call)
Definition Parser.py:76
list[AST.Statement] _parse_if(self, ast.If if_statement)
Definition Parser.py:275
list[AST.Element|AST.Variable] parse_slice(self, ast.Slice slice, Sequence[AST.Element|AST.Variable] original_iteration_range)
Definition Parser.py:161
AST.DataBlock _parse_data_block_constructor(self, ast.Call constructor)
Definition Parser.py:33
AST.ElementBinaryOperation|AST.DataBlockBinaryOperation|AST.Element parse_binary_operation(self, ast.BinOp operation)
Definition Parser.py:125
list[AST.Statement] _parse_assignment_without_construction(self, ast.Assign assignment)
Definition Parser.py:251
AST.External _parse_string(self, str string)
Definition Parser.py:7
AST.Function parse(self, function, str|None function_id=None, list[str] function_namespace=[], list[AST.Argument] function_arguments=[], dict[AST.Name, AST.TFunction] function_map={}, list[PDETerm] enabled_pde_terms=[], dict[AST.Argument, int|float] external_variables={}, bool stateless=False)
Definition Parser.py:325
list[AST.Statement] parse_data_block_construction(self, AST.Variable lhs, AST.DataBlock rhs)
Definition Parser.py:231
AST.Element|AST.External _parse_constant(self, ast.Constant constant)
Definition Parser.py:21
AST.FunctionCall _parse_evaluation(self, ast.Call call)
Definition Parser.py:67
AST.Expression _parse_expression(self, ast.expr expression)
Definition Parser.py:206
list[AST.Statement] _parse_construction(self, ast.Assign assignment)
Definition Parser.py:242
list[AST.Statement] _parse_assignment(self, ast.Assign assignment)
Definition Parser.py:265
AST.Function _parse_function(self, ast.FunctionDef function, str|None function_id, list[str] function_namespace, list[AST.Argument] function_arguments, bool stateless)
Definition Parser.py:305
AST.Variable _parse_variable(self, ast.Name name)
Definition Parser.py:30
AST.ElementUnaryOperation|AST.DataBlockUnaryOperation|AST.Element parse_unary_operation(self, ast.UnaryOp operation)
Definition Parser.py:113