Evaluate a C arithmetic/logic expression and return the result
>>> c_eval('10 + (5 / 3)')
11
>>> c_eval('!0')
1
>>> c_eval('sizeof(x)')
128
Returns: |
-
result ( Union[int, float]
) –
the expression evaluation result
|
Raises: |
-
EvalError
–
expression evaluation error
|
cstruct/c_expr.py
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 | def c_eval(expr: str) -> Union[int, float]:
"""
Evaluate a C arithmetic/logic expression and return the result
Examples:
>>> c_eval('10 + (5 / 3)')
11
>>> c_eval('!0')
1
>>> c_eval('sizeof(x)')
128
Args:
expr: C expression
Returns:
result: the expression evaluation result
Raises:
EvalError: expression evaluation error
"""
try:
expr = expr.replace("!", " not ").replace("&&", " and ").replace("||", " or ")
return eval_node(ast.parse(expr.strip()).body[0])
except EvalError:
raise
except Exception:
raise EvalError
|