lib/expression: refactor expression compilation

Signed-off-by: Marc 'risson' Schmitt <marc.schmitt@risson.space>
This commit is contained in:
Marc 'risson' Schmitt 2024-01-09 17:27:42 +01:00
parent 8831e1d946
commit dd69482127
No known key found for this signature in database
GPG Key ID: 9C3FA22FABF1AA8D
1 changed files with 7 additions and 12 deletions

View File

@ -180,6 +180,11 @@ class BaseEvaluator:
full_expression += f"\nresult = handler({handler_signature})" full_expression += f"\nresult = handler({handler_signature})"
return full_expression return full_expression
def compile(self, expression: str) -> Any:
"""Parse expression. Raises SyntaxError or ValueError if the syntax is incorrect."""
param_keys = self._context.keys()
return compile(self.wrap_expression(expression, param_keys), self._filename, "exec")
def evaluate(self, expression_source: str) -> Any: def evaluate(self, expression_source: str) -> Any:
"""Parse and evaluate expression. If the syntax is incorrect, a SyntaxError is raised. """Parse and evaluate expression. If the syntax is incorrect, a SyntaxError is raised.
If any exception is raised during execution, it is raised. If any exception is raised during execution, it is raised.
@ -188,13 +193,8 @@ class BaseEvaluator:
span: Span span: Span
span.description = self._filename span.description = self._filename
span.set_data("expression", expression_source) span.set_data("expression", expression_source)
param_keys = self._context.keys()
try: try:
ast_obj = compile( ast_obj = self.compile(expression_source)
self.wrap_expression(expression_source, param_keys),
self._filename,
"exec",
)
except (SyntaxError, ValueError) as exc: except (SyntaxError, ValueError) as exc:
self.handle_error(exc, expression_source) self.handle_error(exc, expression_source)
raise exc raise exc
@ -221,13 +221,8 @@ class BaseEvaluator:
def validate(self, expression: str) -> bool: def validate(self, expression: str) -> bool:
"""Validate expression's syntax, raise ValidationError if Syntax is invalid""" """Validate expression's syntax, raise ValidationError if Syntax is invalid"""
param_keys = self._context.keys()
try: try:
compile( self.compile(expression)
self.wrap_expression(expression, param_keys),
self._filename,
"exec",
)
return True return True
except (ValueError, SyntaxError) as exc: except (ValueError, SyntaxError) as exc:
raise ValidationError(f"Expression Syntax Error: {str(exc)}") from exc raise ValidationError(f"Expression Syntax Error: {str(exc)}") from exc