Debian Codegraph @

brian2/parsing/expressions.py

raw
1 """
2 AST parsing based analysis of expressions
3 """
4
5 import ast
6
7 from brian2.core.functions import Function
8 from brian2.parsing.rendering import NodeRenderer
9 from brian2.units.fundamentalunits import (
10 DIMENSIONLESS,
11 DimensionMismatchError,
12 Unit,
13 get_dimensions,
14 get_unit_for_display,
15 have_same_dimensions,
16 )
17
18 __all__ = ["parse_expression_dimensions"]
19
20
21 def is_boolean_expression(expr, variables):
22 """
23 Determines if an expression is of boolean type or not
24
25 Parameters
26 ----------
27
28 expr : str
29 The expression to test
30 variables : dict-like of `Variable`
31 The variables used in the expression.
32
33 Returns
34 -------
35 isbool : bool
36 Whether or not the expression is boolean.
37
38 Raises
39 ------
40 SyntaxError
41 If the expression ought to be boolean but is not,
42 for example ``x<y and z`` where ``z`` is not a boolean variable.
43
44 Notes
45 -----
46 We test the following cases recursively on the abstract syntax tree:
47
48 * The node is a boolean operation. If all the subnodes are boolean
49 expressions we return ``True``, otherwise we raise the ``SyntaxError``.
50 * The node is a function call, we return ``True`` or ``False`` depending
51 on whether the function description has the ``_returns_bool`` attribute
52 set.
53 * The node is a variable name, we return ``True`` or ``False`` depending
54 on whether ``is_boolean`` attribute is set or if the name is ``True`` or
55 ``False``.
56 * The node is a comparison, we return ``True``.
57 * The node is a unary operation, we return ``True`` if the operation is
58 ``not``, otherwise ``False``.
59 * Otherwise we return ``False``.
60 """
61
62 # If we are working on a string, convert to the top level node
63 if isinstance(expr, str):
64 mod = ast.parse(expr, mode="eval")
65 expr = mod.body
66
67 if expr.__class__ is ast.BoolOp:
68 if all(is_boolean_expression(node, variables) for node in expr.values):
69 return True
70 else:
71 raise SyntaxError(
72 "Expression ought to be boolean but is not (e.g. 'x<y and 3')"
73 )
74 elif expr.__class__ is ast.Constant:
75 value = expr.value
76 if value is True or value is False:
77 return True
78 elif value is None:
79 raise ValueError("Do not know how to deal with 'None'")
80 elif expr.__class__ is ast.Name:
81 name = expr.id
82 if name in variables:
83 return variables[name].is_boolean
84 else:
85 return name == "True" or name == "False"
86 elif expr.__class__ is ast.Call:
87 name = expr.func.id
88 if name in variables and hasattr(variables[name], "_returns_bool"):
89 return variables[name]._returns_bool
90 else:
91 raise SyntaxError(f"Unknown function {name}")
92 elif expr.__class__ is ast.Compare:
93 return True
94 elif expr.__class__ is ast.UnaryOp:
95 return expr.op.__class__.__name__ == "Not"
96 else:
97 return False
98
99
100 def _get_value_from_expression(expr, variables):
101 """
102 Returns the scalar value of an expression, and checks its validity.
103
104 Parameters
105 ----------
106 expr : str or `ast.Expression`
107 The expression to check.
108 variables : dict of `Variable` objects
109 The information about all variables used in `expr` (including `Constant`
110 objects for external variables)
111
112 Returns
113 -------
114 value : float
115 The value of the expression
116
117 Raises
118 ------
119 SyntaxError
120 If the expression cannot be evaluated to a scalar value
121 DimensionMismatchError
122 If any part of the expression is dimensionally inconsistent.
123 """
124 # If we are working on a string, convert to the top level node
125 if isinstance(expr, str):
126 mod = ast.parse(expr, mode="eval")
127 expr = mod.body
128
129 if expr.__class__ is ast.Name:
130 name = expr.id
131 if name in variables:
132 if not getattr(variables[name], "constant", False):
133 raise SyntaxError(f"Value {name} is not constant")
134 if not getattr(variables[name], "scalar", False):
135 raise SyntaxError(f"Value {name} is not scalar")
136 return variables[name].get_value()
137 elif name in ["True", "False"]:
138 return 1.0 if name == "True" else 0.0
139 else:
140 raise ValueError(f"Unknown identifier {name}")
141 elif expr.__class__ is ast.Constant:
142 return expr.value
143 elif expr.__class__ is ast.BoolOp or expr.__class__ is ast.Compare:
144 raise SyntaxError(
145 "Cannot determine the numerical value for a boolean operation."
146 )
147 elif expr.__class__ is ast.Call:
148 raise SyntaxError("Cannot determine the numerical value for a function call.")
149 elif expr.__class__ is ast.BinOp:
150 op = expr.op.__class__.__name__
151 left = _get_value_from_expression(expr.left, variables)
152 right = _get_value_from_expression(expr.right, variables)
153 if op == "Add" or op == "Sub":
154 v = left + right
155 elif op == "Mult":
156 v = left * right
157 elif op == "Div":
158 v = float(left) / right
159 elif op == "FloorDiv":
160 v = left // right
161 elif op == "Pow":
162 v = left**right
163 elif op == "Mod":
164 v = left % right
165 else:
166 raise SyntaxError(f"Unsupported operation {op}")
167 return v
168 elif expr.__class__ is ast.UnaryOp:
169 op = expr.op.__class__.__name__
170 # check validity of operand and get its unit
171 v = _get_value_from_expression(expr.operand, variables)
172 if op == "Not":
173 raise SyntaxError(
174 "Cannot determine the numerical value for a boolean operation."
175 )
176 if op == "USub":
177 return -v
178 else:
179 raise SyntaxError(f"Unknown unary operation {op}")
180 else:
181 raise SyntaxError(f"Unsupported operation {str(expr.__class__)}")
182
183
184 def parse_expression_dimensions(expr, variables, orig_expr=None):
185 """
186 Returns the unit value of an expression, and checks its validity
187
188 Parameters
189 ----------
190 expr : str
191 The expression to check.
192 variables : dict
193 Dictionary of all variables used in the `expr` (including `Constant`
194 objects for external variables)
195
196 Returns
197 -------
198 unit : Quantity
199 The output unit of the expression
200
201 Raises
202 ------
203 SyntaxError
204 If the expression cannot be parsed, or if it uses ``a**b`` for ``b``
205 anything other than a constant number.
206 DimensionMismatchError
207 If any part of the expression is dimensionally inconsistent.
208 """
209
210 # If we are working on a string, convert to the top level node
211 if isinstance(expr, str):
212 orig_expr = expr
213 mod = ast.parse(expr, mode="eval")
214 expr = mod.body
215 if expr.__class__ is ast.Name:
216 name = expr.id
217 # Raise an error if a function is called as if it were a variable
218 # (most of the time this happens for a TimedArray)
219 if name in variables and isinstance(variables[name], Function):
220 raise SyntaxError(
221 f"{name} was used like a variable/constant, but it is a function.",
222 ("<string>", expr.lineno, expr.col_offset + 1, orig_expr),
223 )
224 if name in variables:
225 return get_dimensions(variables[name])
226 elif name in ["True", "False"]:
227 return DIMENSIONLESS
228 else:
229 raise KeyError(f"Unknown identifier {name}")
230 elif expr.__class__ is ast.Constant:
231 return DIMENSIONLESS
232 elif expr.__class__ is ast.BoolOp:
233 # check that the units are valid in each subexpression
234 for node in expr.values:
235 parse_expression_dimensions(node, variables, orig_expr=orig_expr)
236 # but the result is a bool, so we just return 1 as the unit
237 return DIMENSIONLESS
238 elif expr.__class__ is ast.Compare:
239 # check that the units are consistent in each subexpression
240 subexprs = [expr.left] + expr.comparators
241 subunits = []
242 for node in subexprs:
243 subunits.append(
244 parse_expression_dimensions(node, variables, orig_expr=orig_expr)
245 )
246 for left_dim, right_dim in zip(subunits[:-1], subunits[1:], strict=True):
247 if not have_same_dimensions(left_dim, right_dim):
248 left_expr = NodeRenderer().render_node(expr.left)
249 right_expr = NodeRenderer().render_node(expr.comparators[0])
250 dim_left = get_dimensions(left_dim)
251 dim_right = get_dimensions(right_dim)
252 msg = (
253 "Comparison of expressions with different units. Expression "
254 f"'{left_expr}' has unit ({dim_left}), while expression "
255 f"'{right_expr}' has units ({dim_right})."
256 )
257 raise DimensionMismatchError(msg)
258 # but the result is a bool, so we just return 1 as the unit
259 return DIMENSIONLESS
260 elif expr.__class__ is ast.Call:
261 if len(expr.keywords):
262 raise ValueError("Keyword arguments not supported.")
263 elif getattr(expr, "starargs", None) is not None:
264 raise ValueError("Variable number of arguments not supported")
265 elif getattr(expr, "kwargs", None) is not None:
266 raise ValueError("Keyword arguments not supported")
267
268 func = variables.get(expr.func.id, None)
269 if func is None:
270 raise SyntaxError(
271 f"Unknown function {expr.func.id}",
272 ("<string>", expr.lineno, expr.col_offset + 1, orig_expr),
273 )
274 if not hasattr(func, "_arg_units") or not hasattr(func, "_return_unit"):
275 raise ValueError(
276 f"Function {expr.func.id} does not specify how it deals with units."
277 )
278
279 if len(func._arg_units) != len(expr.args):
280 raise SyntaxError(
281 f"Function '{expr.func.id}' was called with "
282 f"{len(expr.args)} parameters, needs "
283 f"{len(func._arg_units)}.",
284 (
285 "<string>",
286 expr.lineno,
287 expr.col_offset + len(expr.func.id) + 1,
288 orig_expr,
289 ),
290 )
291
292 for idx, (arg, expected_unit) in enumerate(
293 zip(expr.args, func._arg_units, strict=True)
294 ):
295 arg_unit = parse_expression_dimensions(arg, variables, orig_expr=orig_expr)
296 # A "None" in func._arg_units means: No matter what unit
297 if expected_unit is None:
298 continue
299 # A string means: same unit as other argument
300 elif isinstance(expected_unit, str):
301 arg_idx = func._arg_names.index(expected_unit)
302 expected_unit = parse_expression_dimensions(
303 expr.args[arg_idx], variables, orig_expr=orig_expr
304 )
305 if not have_same_dimensions(arg_unit, expected_unit):
306 msg = (
307 f"Argument number {idx + 1} for function "
308 f"{expr.func.id} was supposed to have the "
309 f"same units as argument number {arg_idx + 1}, but "
310 f"'{NodeRenderer().render_node(arg)}' has unit "
311 f"{get_unit_for_display(arg_unit)}, while "
312 f"'{NodeRenderer().render_node(expr.args[arg_idx])}' "
313 f"has unit {get_unit_for_display(expected_unit)}"
314 )
315 raise DimensionMismatchError(msg)
316 elif expected_unit is bool:
317 if not is_boolean_expression(arg, variables):
318 rendered_arg = NodeRenderer().render_node(arg)
319 raise TypeError(
320 f"Argument number {idx + 1} for function "
321 f"'{expr.func.id}' was expected to be a boolean "
322 f"value, but is '{rendered_arg}'."
323 )
324 else:
325 if not have_same_dimensions(arg_unit, expected_unit):
326 rendered_arg = NodeRenderer().render_node(arg)
327 arg_unit_dim = get_dimensions(arg_unit)
328 expected_unit_dim = get_dimensions(expected_unit)
329 msg = (
330 f"Argument number {idx + 1} for function {expr.func.id} does "
331 f"not have the correct units. Expression '{rendered_arg}' "
332 f"has units ({arg_unit_dim}), but "
333 "should be "
334 f"({expected_unit_dim})."
335 )
336 raise DimensionMismatchError(msg)
337
338 if func._return_unit is bool:
339 return DIMENSIONLESS
340 elif isinstance(func._return_unit, (Unit, int)):
341 # Function always returns the same unit
342 return getattr(func._return_unit, "dim", DIMENSIONLESS)
343 else:
344 # Function returns a unit that depends on the arguments
345 arg_units = [
346 parse_expression_dimensions(arg, variables, orig_expr=orig_expr)
347 for arg in expr.args
348 ]
349 return func._return_unit(*arg_units).dim
350
351 elif expr.__class__ is ast.BinOp:
352 op = expr.op.__class__.__name__
353 left_dim = parse_expression_dimensions(
354 expr.left, variables, orig_expr=orig_expr
355 )
356 right_dim = parse_expression_dimensions(
357 expr.right, variables, orig_expr=orig_expr
358 )
359 if op in ["Add", "Sub", "Mod"]:
360 # dimensions should be the same
361 if left_dim is not right_dim:
362 op_symbol = {"Add": "+", "Sub": "-", "Mod": "%"}.get(op)
363 left_str = NodeRenderer().render_node(expr.left)
364 right_str = NodeRenderer().render_node(expr.right)
365 left_unit = get_unit_for_display(left_dim)
366 right_unit = get_unit_for_display(right_dim)
367 error_msg = (
368 f"Expression '{left_str} {op_symbol} {right_str}' uses "
369 f"inconsistent units ('{left_str}' has unit "
370 f"{left_unit}; '{right_str}' "
371 f"has unit {right_unit})."
372 )
373 raise DimensionMismatchError(error_msg)
374 u = left_dim
375 elif op == "Mult":
376 u = left_dim * right_dim
377 elif op == "Div":
378 u = left_dim / right_dim
379 elif op == "FloorDiv":
380 if not (left_dim is DIMENSIONLESS and right_dim is DIMENSIONLESS):
381 if left_dim is DIMENSIONLESS:
382 col_offset = expr.right.col_offset + 1
383 else:
384 col_offset = expr.left.col_offset + 1
385 raise SyntaxError(
386 "Floor division can only be used on dimensionless values.",
387 ("<string>", expr.lineno, col_offset, orig_expr),
388 )
389 u = DIMENSIONLESS
390 elif op == "Pow":
391 if left_dim is DIMENSIONLESS and right_dim is DIMENSIONLESS:
392 return DIMENSIONLESS
393 n = _get_value_from_expression(expr.right, variables)
394 u = left_dim**n
395 else:
396 raise SyntaxError(
397 f"Unsupported operation {op}",
398 (
399 "<string>",
400 expr.lineno,
401 getattr(
402 expr.left,
403 "end_col_offset",
404 len(NodeRenderer().render_node(expr.left)),
405 )
406 + 1,
407 orig_expr,
408 ),
409 )
410 return u
411 elif expr.__class__ is ast.UnaryOp:
412 op = expr.op.__class__.__name__
413 # check validity of operand and get its unit
414 u = parse_expression_dimensions(expr.operand, variables, orig_expr=orig_expr)
415 if op == "Not":
416 return DIMENSIONLESS
417 else:
418 return u
419 else:
420 raise SyntaxError(
421 f"Unsupported operation {str(expr.__class__.__name__)}",
422 ("<string>", expr.lineno, expr.col_offset + 1, orig_expr),
423 )