forked from andreax79/python-cstruct
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathc_expr.py
More file actions
203 lines (170 loc) · 6.94 KB
/
c_expr.py
File metadata and controls
203 lines (170 loc) · 6.94 KB
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
#!/usr/bin/env python
# Copyright (c) 2013-2025 Andrea Bonomi <andrea.bonomi@gmail.com>
#
# Published under the terms of the MIT license.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
# sell copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
#
import ast
import inspect
import operator
import sys
from typing import TYPE_CHECKING, Any, Callable, Dict, Optional, Type, Union
from .base import DEFINES, STRUCTS
from .exceptions import ContextNotFound, EvalError
if TYPE_CHECKING:
from .abstract import AbstractCStruct
__all__ = ["c_eval"]
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
def eval_attribute_node(node: ast.Attribute) -> Union[int, float]:
"""
Evaluate node attribute, e.g. 'self.x'
Only 'self' is allowed. The attribute must be a number.
Args:
node: attribute node
Returns:
result: the attribute value
Raises:
EvalError: expression result is not a number, or not self attribute
ContextNotFound: context is not defined
"""
if not node.value or node.value.id != "self": # type: ignore
raise EvalError("only self is allowed")
context = get_cstruct_context()
if context is None:
raise ContextNotFound("context is not defined")
result = getattr(context, node.attr)
if not isinstance(result, (int, float)):
raise EvalError("expression result is not a number")
return result
def eval_node(node: ast.stmt) -> Union[int, float]:
if isinstance(node, ast.Attribute):
return eval_attribute_node(node)
handler = OPS[type(node)]
result = handler(node)
if isinstance(result, bool): # convert bool to int
return 1 if result else 0
elif isinstance(result, str): # convert char to int
if len(result) != 1:
raise EvalError("Multi-character constant")
else:
return ord(result)
return result
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]
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
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)
def eval_call(node) -> Union[int, float]:
from . import sizeof
if node.func.id == "sizeof":
args = [eval_node(x) for x in node.args]
return sizeof(*args)
raise KeyError(node.func.id)
def get_cstruct_context() -> Optional["AbstractCStruct"]:
"""
Get the calling CStruct instance from the stack (if any)
"""
from .abstract import AbstractCStruct
stack = inspect.stack()
for frame in stack:
caller_self = frame.frame.f_locals.get("self")
if isinstance(caller_self, AbstractCStruct):
return caller_self
return None
OPS: Dict[Type[ast.AST], Callable[[Any], Any]] = {
ast.Expr: lambda node: eval_node(node.value),
ast.Name: eval_get,
ast.Call: eval_call,
ast.Constant: lambda node: node.value,
# and/or
ast.BoolOp: lambda node: OPS[type(node.op)](node), # and/or operator
ast.And: lambda node: all(eval_node(x) for x in node.values), # && operator
ast.Or: lambda node: any(eval_node(x) for x in node.values), # || operator
# binary
ast.BinOp: lambda node: OPS[type(node.op)](node), # binary operators
ast.Add: lambda node: operator.add(eval_node(node.left), eval_node(node.right)), # + operator
ast.Sub: lambda node: operator.sub(eval_node(node.left), eval_node(node.right)), # - operator
ast.Mult: lambda node: operator.mul(eval_node(node.left), eval_node(node.right)), # * operator
ast.Div: eval_div,
ast.Mod: lambda node: operator.mod(eval_node(node.left), eval_node(node.right)), # % operator
ast.LShift: lambda node: operator.lshift(eval_node(node.left), eval_node(node.right)), # << operator
ast.RShift: lambda node: operator.rshift(eval_node(node.left), eval_node(node.right)), # >> operator
ast.BitOr: lambda node: operator.or_(eval_node(node.left), eval_node(node.right)), # | operator
ast.BitXor: lambda node: operator.xor(eval_node(node.left), eval_node(node.right)), # ^ operator
ast.BitAnd: lambda node: operator.and_(eval_node(node.left), eval_node(node.right)), # & operator
# unary
ast.UnaryOp: lambda node: OPS[type(node.op)](node), # unary operators
ast.UAdd: lambda node: operator.pos(eval_node(node.operand)), # unary + operator
ast.USub: lambda node: operator.neg(eval_node(node.operand)), # unary - operator
ast.Not: lambda node: operator.not_(eval_node(node.operand)), # ! operator
ast.Invert: lambda node: operator.invert(eval_node(node.operand)), # ~ operator
# Compare
ast.Compare: eval_compare,
ast.Eq: operator.eq,
ast.NotEq: operator.ne,
ast.Gt: operator.gt,
ast.Lt: operator.lt,
ast.GtE: operator.ge,
ast.LtE: operator.le,
}
if sys.version_info.major == 3 and sys.version_info.minor < 8:
OPS[ast.Num] = lambda node: node.n
OPS[ast.Str] = lambda node: node.s