c_eval(expr)

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

Parameters:

Name Type Description Default
expr str

C expression

required

Returns:

Name Type Description
result Union[int, float]

the expression evaluation result

Raises:

Type Description
EvalError

expression evaluation error

Source code in cstruct/c_expr.py
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
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

Source code in cstruct/c_expr.py
88
89
90
91
92
93
94
95
96
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)

Source code in cstruct/c_expr.py
 99
100
101
102
103
104
105
106
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

Source code in cstruct/c_expr.py
80
81
82
83
84
85
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]