Skip to content

Commit 2829487

Browse files
dgwSnoopJ
andcommitted
tools.calculation: more refined handling of unsupported node types
Co-authored-by: SnoopJ <[email protected]>
1 parent 6cae1b6 commit 2829487

File tree

1 file changed

+28
-9
lines changed

1 file changed

+28
-9
lines changed

sopel/tools/calculation.py

Lines changed: 28 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -57,31 +57,50 @@ def _eval_node(self, node, timeout):
5757
A subclass could overwrite this to handle more nodes, calling it only
5858
for nodes it does not implement itself.
5959
"""
60-
if (
61-
isinstance(node, ast.Constant) and
62-
isinstance(node.value, (int, float))
63-
):
60+
if isinstance(node, ast.Constant):
61+
if not isinstance(node.value, (int, float)):
62+
raise ExpressionEvaluator.Error(
63+
"'{}' values are not supported".format(
64+
type(node.value).__name__,
65+
)
66+
)
67+
6468
return node.value
6569

66-
elif (isinstance(node, ast.BinOp) and
67-
type(node.op) in self.binary_ops):
70+
elif isinstance(node, ast.BinOp):
71+
if type(node.op) not in self.binary_ops:
72+
raise ExpressionEvaluator.Error(
73+
"Unsupported binary operator '{}'".format(
74+
type(node.op).__name__,
75+
)
76+
)
77+
6878
left = self._eval_node(node.left, timeout)
6979
right = self._eval_node(node.right, timeout)
7080
if time.time() > timeout:
7181
raise ExpressionEvaluator.Error(
7282
"Time for evaluating expression ran out.")
7383
return self.binary_ops[type(node.op)](left, right)
7484

75-
elif (isinstance(node, ast.UnaryOp) and
76-
type(node.op) in self.unary_ops):
85+
elif isinstance(node, ast.UnaryOp):
86+
if type(node.op) not in self.unary_ops:
87+
raise ExpressionEvaluator.Error(
88+
"Unsupported unary operator '{}'".format(
89+
type(node.op).__name__,
90+
)
91+
)
92+
7793
operand = self._eval_node(node.operand, timeout)
7894
if time.time() > timeout:
7995
raise ExpressionEvaluator.Error(
8096
"Time for evaluating expression ran out.")
8197
return self.unary_ops[type(node.op)](operand)
8298

8399
raise ExpressionEvaluator.Error(
84-
"ast.Node '%s' not implemented." % (type(node).__name__,))
100+
"Node type '{}' is not supported.".format(
101+
type(node).__name__,
102+
)
103+
)
85104

86105

87106
def guarded_mul(left, right):

0 commit comments

Comments
 (0)