c_eval(expr)

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
Parameters:
  • expr (str) –

    C expression

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

eval_compare(node)

Evaluate a compare node

cstruct/c_expr.py
89
90
91
92
93
94
95
96
97
def eval_compare(node) -> bool:
    "Evaluate a compare node"
    right = eval_node(node.left)
    for operation, comp in zip(node.ops, node.comparators):
        left = right
        right = eval_node(comp)
        if not OPS[type(operation)](left, right):
            return False
    return True

eval_div(node)

Evaluate div node (integer/float)

cstruct/c_expr.py
100
101
102
103
104
105
106
107
def eval_div(node) -> Union[int, float]:
    "Evaluate div node (integer/float)"
    left = eval_node(node.left)
    right = eval_node(node.right)
    if isinstance(left, float) or isinstance(right, float):
        return operator.truediv(left, right)
    else:
        return operator.floordiv(left, right)

eval_get(node)

Get definition/struct by name

cstruct/c_expr.py
81
82
83
84
85
86
def eval_get(node) -> Union[int, float, Type["AbstractCStruct"]]:
    "Get definition/struct by name"
    try:
        return DEFINES[node.id]
    except KeyError:
        return STRUCTS[node.id]