Skip to content

Commit

Permalink
Add helper method to cast datatypes from string
Browse files Browse the repository at this point in the history
  • Loading branch information
OliverStolzBO committed Jan 12, 2024
1 parent 3faa540 commit 8059056
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 7 deletions.
12 changes: 6 additions & 6 deletions pfdl_scheduler/parser/pfdl_tree_visitor.py
Original file line number Diff line number Diff line change
Expand Up @@ -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])
Expand Down
19 changes: 18 additions & 1 deletion pfdl_scheduler/utils/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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 = {
Expand Down

0 comments on commit 8059056

Please sign in to comment.