From 805905667b533a6a8d1fe79bfb87d4b1138003ad Mon Sep 17 00:00:00 2001 From: Oliver Stolz Date: Fri, 12 Jan 2024 09:38:30 +0100 Subject: [PATCH] Add helper method to cast datatypes from string --- pfdl_scheduler/parser/pfdl_tree_visitor.py | 12 ++++++------ pfdl_scheduler/utils/helpers.py | 19 ++++++++++++++++++- 2 files changed, 24 insertions(+), 7 deletions(-) diff --git a/pfdl_scheduler/parser/pfdl_tree_visitor.py b/pfdl_scheduler/parser/pfdl_tree_visitor.py index 046509a..de0b979 100644 --- a/pfdl_scheduler/parser/pfdl_tree_visitor.py +++ b/pfdl_scheduler/parser/pfdl_tree_visitor.py @@ -358,12 +358,12 @@ def visitExpression(self, ctx: PFDLParser.ExpressionContext) -> Dict: ele = self.get_content(ctx.children[0]) if isinstance(ele, List): return ele - if helpers.is_int(ele): - return int(ele) - if helpers.is_float(ele): - return float(ele) - if helpers.is_boolean(ele): - return ele == "true" + elif not helpers.is_string(ele): + # strings should not appear here + casted_element = helpers.cast_element(ele) + # check if ele is a primitve datatype (number or bool) + if casted_element != ele: + return casted_element if length == 2: un_op = self.get_content(ctx.children[0]) ele = self.get_content(ctx.children[1]) diff --git a/pfdl_scheduler/utils/helpers.py b/pfdl_scheduler/utils/helpers.py index 64857a1..b2eebef 100644 --- a/pfdl_scheduler/utils/helpers.py +++ b/pfdl_scheduler/utils/helpers.py @@ -7,7 +7,7 @@ """Helper functions used in the project (especially in the SemanticErrorChecker).""" # standard libraries -from typing import Any, Dict, List +from typing import Any, Dict, List, Union import operator # local sources @@ -123,6 +123,23 @@ def is_int(string: str) -> bool: return True +def cast_element(string: str) -> Union[str, int, float, bool]: + """Tries to cast the given string to a primitive datatype. + + Returns: + The casted element if casting was successful, otherwise the input string + """ + if is_int(string): + return int(string) + elif is_float(string): + return float(string) + elif is_boolean(string): + return string == "true" + elif is_string(string): + return string.replace('"', "") + return string + + def parse_operator(op: str) -> operator: """Parses a PFDL operator in form of a string into a Python executable operator func.""" ops = {