From fda1718dd1d0baff72ae2758041d8a5e66b44250 Mon Sep 17 00:00:00 2001 From: Marco Lampacrescia Date: Tue, 10 Sep 2024 14:04:18 +0200 Subject: [PATCH] Handle possible function calls in params expressions Signed-off-by: Marco Lampacrescia --- .../src/as2fm_common/ecmascript_interpretation.py | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/as2fm_common/src/as2fm_common/ecmascript_interpretation.py b/as2fm_common/src/as2fm_common/ecmascript_interpretation.py index f00a462e..f98bc2e5 100644 --- a/as2fm_common/src/as2fm_common/ecmascript_interpretation.py +++ b/as2fm_common/src/as2fm_common/ecmascript_interpretation.py @@ -17,7 +17,8 @@ Module for interpreting ecmascript. """ -from typing import Dict, Optional, Union +import re +from typing import Dict, List, Optional, Union from array import array import js2py @@ -27,6 +28,16 @@ BASIC_JS_TYPES = Union[int, float, bool] +# Functions that, if found in the expression, should be interpreted as math functions (Math.fun()) +MATH_FUNCTIONS: List[str] = ["abs", "floor", "ceil", "cos", "sin", "log", "pow", "min", "max"] + + +def prepend_math_functions(expr: str) -> str: + """Append 'Math.' to the functions in the provided expression and return a copy.""" + for fun in MATH_FUNCTIONS: + expr = re.sub(rf"(^|[^a-zA-Z0-9_]){fun}\(", rf"\g<1>Math.{fun}(", expr) + return expr + def interpret_ecma_script_expr( expr: str, variables: Optional[Dict[str, ValidTypes]] = None) -> object: @@ -36,6 +47,7 @@ def interpret_ecma_script_expr( :param expr: The ECMA script expression :return: The interpreted object """ + expr = prepend_math_functions(expr) if variables is None: variables = {} context = js2py.EvalJs(variables)