-
Notifications
You must be signed in to change notification settings - Fork 0
/
str_parser.py
68 lines (57 loc) · 2.19 KB
/
str_parser.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import ast
import sympy
from sympy.parsing.sympy_parser import parse_expr, standard_transformations, convert_xor
transformations = standard_transformations + (convert_xor,)
sympy_defs = dir(sympy) # Get all sympy definitions
def is_safe(string: str) -> bool:
"""
Check if a string is safe for eval. This reduces the risk of arbitrary code execution, but may not catch all cases.
Args:
string (str): The string to check.
Returns:
bool: Whether the string is safe.
"""
try:
tree = ast.parse(string)
except SyntaxError:
return False
disallowed = (ast.Import, ast.ImportFrom, ast.FunctionDef, ast.ClassDef, ast.AsyncFunctionDef)
for node in ast.walk(tree):
flag = False
if isinstance(node, disallowed):
flag = True
elif isinstance(node, ast.Call):
if isinstance(node.func, ast.Name):
if node.func.id not in sympy_defs:
# Example: abc(), abc(1, 2, 3), etc.
flag = True
elif isinstance(node.func, ast.Attribute):
if node.func.attr not in sympy_defs:
# Example: abc.xyz(), abc.xyz(1, 2, 3), etc.
flag = True
else:
raise ValueError("Unknown function call type.") # Should never happen
if flag:
return False
return True
def parse(expr: str) -> sympy.Expr:
"""
Parse an arbitrary string into a sympy expression.
Args:
expr (str): The expression to parse.
Returns:
sympy.Expr: The parsed expression.
Raises:
ValueError: If the expression cannot be parsed correctly.
"""
if not isinstance(expr, str):
raise ValueError("Expression must be a string.")
if "=" in expr:
raise ValueError("Expression must be all on one side of the equals sign, omitting the equals sign.")
# Check if the expression is safe for eval.
if not is_safe(expr):
raise ValueError("Expression is not safe.")
try:
return parse_expr(expr, transformations=transformations)
except Exception as exception:
raise ValueError("Could not parse the expression.") from exception