sltcalc 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- sltcalc/__init__.py +3 -0
- sltcalc/sltcalc.py +155 -0
- sltcalc-0.1.0.dist-info/METADATA +130 -0
- sltcalc-0.1.0.dist-info/RECORD +6 -0
- sltcalc-0.1.0.dist-info/WHEEL +4 -0
- sltcalc-0.1.0.dist-info/licenses/LICENSE +21 -0
sltcalc/__init__.py
ADDED
sltcalc/sltcalc.py
ADDED
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
"""Safe, deterministic expression evaluator for computing bit‑accurate
|
|
2
|
+
offsets, sizes, and field values within StructLayoutToolkit."""
|
|
3
|
+
import ast
|
|
4
|
+
import operator
|
|
5
|
+
|
|
6
|
+
OPS = {
|
|
7
|
+
ast.Add: operator.add,
|
|
8
|
+
ast.Sub: operator.sub,
|
|
9
|
+
ast.Mult: operator.mul,
|
|
10
|
+
ast.Div: operator.truediv,
|
|
11
|
+
ast.FloorDiv: operator.floordiv,
|
|
12
|
+
ast.Pow: operator.pow,
|
|
13
|
+
ast.Mod: operator.mod,
|
|
14
|
+
ast.Eq: operator.eq,
|
|
15
|
+
ast.NotEq: operator.ne,
|
|
16
|
+
ast.Lt: operator.lt,
|
|
17
|
+
ast.LtE: operator.le,
|
|
18
|
+
ast.Gt: operator.gt,
|
|
19
|
+
ast.GtE: operator.ge,
|
|
20
|
+
ast.Is: operator.is_,
|
|
21
|
+
ast.IsNot: operator.is_not,
|
|
22
|
+
ast.In: lambda left, right: left in right,
|
|
23
|
+
ast.NotIn: lambda left, right: left not in right,
|
|
24
|
+
ast.BitAnd: operator.and_,
|
|
25
|
+
ast.BitOr: operator.or_,
|
|
26
|
+
ast.BitXor: operator.xor,
|
|
27
|
+
ast.LShift: operator.lshift,
|
|
28
|
+
ast.RShift: operator.rshift,
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
UNARY = {
|
|
32
|
+
ast.UAdd: lambda x: x,
|
|
33
|
+
ast.USub: lambda x: -x,
|
|
34
|
+
ast.Not: lambda x: not x,
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
SAFE_FUNCS = {
|
|
38
|
+
"abs": abs,
|
|
39
|
+
"all": all,
|
|
40
|
+
"any": any,
|
|
41
|
+
"len": len,
|
|
42
|
+
"min": min,
|
|
43
|
+
"max": max,
|
|
44
|
+
"round": round,
|
|
45
|
+
"sorted": sorted,
|
|
46
|
+
"sum": sum,
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
class SltEval:
|
|
51
|
+
"""A safe, deterministic expression evaluator for computing bit‑accurate
|
|
52
|
+
offsets, sizes, and field values within StructLayoutToolkit."""
|
|
53
|
+
|
|
54
|
+
def __init__(self, env=None):
|
|
55
|
+
self.env = env or {}
|
|
56
|
+
|
|
57
|
+
def eval(self, expr: str) -> any:
|
|
58
|
+
"""Evaluate a mathematical expression in a safe and deterministic
|
|
59
|
+
manner.
|
|
60
|
+
Args:
|
|
61
|
+
expr (str): The mathematical expression to evaluate.
|
|
62
|
+
|
|
63
|
+
Returns:
|
|
64
|
+
The result of the evaluated expression.
|
|
65
|
+
"""
|
|
66
|
+
node = ast.parse(expr, mode="eval").body
|
|
67
|
+
return self._eval(node)
|
|
68
|
+
|
|
69
|
+
def _eval(self, node) -> any:
|
|
70
|
+
"""Recursively evaluate an AST node."""
|
|
71
|
+
if isinstance(node, ast.Constant):
|
|
72
|
+
return node.value
|
|
73
|
+
|
|
74
|
+
if isinstance(node, ast.Name):
|
|
75
|
+
if node.id not in self.env:
|
|
76
|
+
raise NameError(f"Undefined variable: {node.id}")
|
|
77
|
+
return self.env[node.id]
|
|
78
|
+
|
|
79
|
+
if isinstance(node, ast.List):
|
|
80
|
+
return [self._eval(element) for element in node.elts]
|
|
81
|
+
|
|
82
|
+
if isinstance(node, ast.Tuple):
|
|
83
|
+
return tuple(self._eval(element) for element in node.elts)
|
|
84
|
+
|
|
85
|
+
if isinstance(node, ast.Dict):
|
|
86
|
+
return {
|
|
87
|
+
self._eval(key): self._eval(value)
|
|
88
|
+
for key, value in zip(node.keys, node.values)
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
if isinstance(node, ast.BinOp):
|
|
92
|
+
op = OPS[type(node.op)]
|
|
93
|
+
return op(self._eval(node.left), self._eval(node.right))
|
|
94
|
+
|
|
95
|
+
if isinstance(node, ast.UnaryOp):
|
|
96
|
+
op = UNARY[type(node.op)]
|
|
97
|
+
return op(self._eval(node.operand))
|
|
98
|
+
|
|
99
|
+
if isinstance(node, ast.IfExp):
|
|
100
|
+
cond = self._eval(node.test)
|
|
101
|
+
return self._eval(node.body if cond else node.orelse)
|
|
102
|
+
|
|
103
|
+
if isinstance(node, ast.BoolOp):
|
|
104
|
+
if isinstance(node.op, ast.And):
|
|
105
|
+
result = self._eval(node.values[0])
|
|
106
|
+
for value_node in node.values[1:]:
|
|
107
|
+
if not result:
|
|
108
|
+
return result
|
|
109
|
+
result = self._eval(value_node)
|
|
110
|
+
return result
|
|
111
|
+
|
|
112
|
+
if isinstance(node.op, ast.Or):
|
|
113
|
+
result = self._eval(node.values[0])
|
|
114
|
+
for value_node in node.values[1:]:
|
|
115
|
+
if result:
|
|
116
|
+
return result
|
|
117
|
+
result = self._eval(value_node)
|
|
118
|
+
return result
|
|
119
|
+
|
|
120
|
+
raise ValueError(f"Unsupported expression: {ast.dump(node)}")
|
|
121
|
+
|
|
122
|
+
if isinstance(node, ast.Compare):
|
|
123
|
+
left = self._eval(node.left)
|
|
124
|
+
for op_node, comparator in zip(node.ops, node.comparators):
|
|
125
|
+
op = OPS.get(type(op_node))
|
|
126
|
+
if op is None:
|
|
127
|
+
raise ValueError(
|
|
128
|
+
f"Unsupported expression: {ast.dump(node)}")
|
|
129
|
+
right = self._eval(comparator)
|
|
130
|
+
if not op(left, right):
|
|
131
|
+
return False
|
|
132
|
+
left = right
|
|
133
|
+
return True
|
|
134
|
+
|
|
135
|
+
if isinstance(node, ast.Call):
|
|
136
|
+
if not isinstance(node.func, ast.Name):
|
|
137
|
+
raise ValueError(f"Unsupported expression: {ast.dump(node)}")
|
|
138
|
+
|
|
139
|
+
func = SAFE_FUNCS.get(node.func.id)
|
|
140
|
+
if func is None and node.func.id in self.env:
|
|
141
|
+
env_func = self.env[node.func.id]
|
|
142
|
+
if callable(env_func):
|
|
143
|
+
func = env_func
|
|
144
|
+
|
|
145
|
+
if func is None:
|
|
146
|
+
raise ValueError(f"Unsafe function: {node.func.id}")
|
|
147
|
+
args = [self._eval(a) for a in node.args]
|
|
148
|
+
return func(*args)
|
|
149
|
+
|
|
150
|
+
if isinstance(node, ast.Subscript):
|
|
151
|
+
value = self._eval(node.value)
|
|
152
|
+
index = self._eval(node.slice)
|
|
153
|
+
return value[index]
|
|
154
|
+
|
|
155
|
+
raise ValueError(f"Unsupported expression: {ast.dump(node)}")
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: sltcalc
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: A safe, deterministic expression evaluator for computing bit‑accurate offsets, sizes, and field values within StructLayoutToolkit.
|
|
5
|
+
Project-URL: Homepage, https://github.com/fangface-hub/StructLayoutToolkitCalc
|
|
6
|
+
Project-URL: Documentation, https://readthedocs.org
|
|
7
|
+
Project-URL: Repository, https://github.com/fangface-hub/StructLayoutToolkitCalc
|
|
8
|
+
Project-URL: Issues, https://github.com/fangface-hub/StructLayoutToolkitCalc/issues
|
|
9
|
+
Author: fangface
|
|
10
|
+
License-Expression: MIT
|
|
11
|
+
License-File: LICENSE
|
|
12
|
+
Keywords: bit,byte,data,deserialization,layout,serialization,struct
|
|
13
|
+
Requires-Python: >=3.12
|
|
14
|
+
Description-Content-Type: text/markdown
|
|
15
|
+
|
|
16
|
+
# StructLayoutToolkitCalc
|
|
17
|
+
|
|
18
|
+
A safe, deterministic expression evaluator for computing bit‑accurate offsets, sizes, and field values within StructLayoutToolkit.
|
|
19
|
+
|
|
20
|
+
## Overview
|
|
21
|
+
|
|
22
|
+
sltcalc provides a safe and deterministic expression evaluator used across StructLayoutToolkit to compute bit‑accurate offsets, sizes, and derived field values.
|
|
23
|
+
It parses expressions into Python’s AST and evaluates a restricted subset of operations, ensuring predictable behavior without accessing Python globals or executing arbitrary code.
|
|
24
|
+
The evaluator supports arithmetic, bitwise operations, conditional expressions, and user‑defined variables supplied through an isolated environment.
|
|
25
|
+
This module enables dynamic field definitions, computed offsets, variable‑length structures, and protocol‑specific formulas while maintaining strict safety and structural consistency.
|
|
26
|
+
|
|
27
|
+
## Usage
|
|
28
|
+
|
|
29
|
+
### Basic
|
|
30
|
+
|
|
31
|
+
```python
|
|
32
|
+
from sltcalc import SltEval
|
|
33
|
+
|
|
34
|
+
evaluator = SltEval()
|
|
35
|
+
result = evaluator.eval("1 + 2 * 3")
|
|
36
|
+
print(result) # 7
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
### With variables
|
|
40
|
+
|
|
41
|
+
```python
|
|
42
|
+
from sltcalc import SltEval
|
|
43
|
+
|
|
44
|
+
env = {
|
|
45
|
+
"offset": 8,
|
|
46
|
+
"width": 3,
|
|
47
|
+
"flag": True,
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
evaluator = SltEval(env)
|
|
51
|
+
|
|
52
|
+
print(evaluator.eval("offset + width * 2")) # 14
|
|
53
|
+
print(evaluator.eval("1 if flag else 0")) # 1
|
|
54
|
+
print(evaluator.eval("99 if offset >= 8 else -1")) # 99
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
### Error behavior
|
|
58
|
+
|
|
59
|
+
```python
|
|
60
|
+
from sltcalc import SltEval
|
|
61
|
+
|
|
62
|
+
evaluator = SltEval()
|
|
63
|
+
|
|
64
|
+
# NameError: undefined variable
|
|
65
|
+
evaluator.eval("unknown + 1")
|
|
66
|
+
|
|
67
|
+
# ValueError: unsafe function
|
|
68
|
+
evaluator.eval("sum(1, 2)")
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
## Supported expressions
|
|
72
|
+
|
|
73
|
+
SltEval evaluates a restricted subset of Python expression AST nodes.
|
|
74
|
+
|
|
75
|
+
### Literals
|
|
76
|
+
|
|
77
|
+
- Numeric constants (for example: 0, 42, 3.5)
|
|
78
|
+
- Boolean constants (True, False)
|
|
79
|
+
- List literals (for example: [1, 2, 3])
|
|
80
|
+
- Tuple literals (for example: (1, 2, 3))
|
|
81
|
+
- Dict literals (for example: {"a": 1, "b": 2})
|
|
82
|
+
|
|
83
|
+
### Variables
|
|
84
|
+
|
|
85
|
+
- Variable lookup from the evaluator environment (SltEval(env))
|
|
86
|
+
|
|
87
|
+
### Binary operators
|
|
88
|
+
|
|
89
|
+
- Arithmetic: +, -, *, /, //, %, **
|
|
90
|
+
- Bitwise: &, |, ^, <<, >>
|
|
91
|
+
|
|
92
|
+
### Unary operators
|
|
93
|
+
|
|
94
|
+
- Unary plus: +x
|
|
95
|
+
- Unary minus: -x
|
|
96
|
+
- Boolean negation: not x
|
|
97
|
+
|
|
98
|
+
### Boolean operators
|
|
99
|
+
|
|
100
|
+
- and
|
|
101
|
+
- or
|
|
102
|
+
|
|
103
|
+
### Comparisons
|
|
104
|
+
|
|
105
|
+
- ==, !=, <, <=, >, >=, is, is not, in, not in
|
|
106
|
+
- Chained comparisons are supported (for example: 1 < 2 < 3)
|
|
107
|
+
|
|
108
|
+
### Conditional expression
|
|
109
|
+
|
|
110
|
+
- Ternary expression: a if condition else b
|
|
111
|
+
|
|
112
|
+
### Subscript access
|
|
113
|
+
|
|
114
|
+
- Index/key access (for example: arr[0], mapping["key"])
|
|
115
|
+
- Nested access is supported (for example: access key "items" and then index 0)
|
|
116
|
+
|
|
117
|
+
### Function calls
|
|
118
|
+
|
|
119
|
+
- Built-in allowlist: abs(...), all(...), any(...), len(...),
|
|
120
|
+
min(...), max(...), round(...), sorted(...), sum(...)
|
|
121
|
+
- Callables passed through environment are allowed
|
|
122
|
+
(for example: SltEval({"triple": triple}) then triple(4))
|
|
123
|
+
|
|
124
|
+
## Not supported
|
|
125
|
+
|
|
126
|
+
- Attribute access (for example: obj.value)
|
|
127
|
+
- Set literals in expressions
|
|
128
|
+
- Non-name call targets (for example: (lambda x: x)(1))
|
|
129
|
+
|
|
130
|
+
Unsupported constructs raise ValueError with an Unsupported expression message.
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
sltcalc/__init__.py,sha256=lNh3PxqV4Hkv3a-gDUer7CJrdBAR-Vv12EzlrQg-3VU,55
|
|
2
|
+
sltcalc/sltcalc.py,sha256=g7sPXCMYo7NG0yb6QAMZsn-VjpJhAo9MBL7ZgIzTIX4,5100
|
|
3
|
+
sltcalc-0.1.0.dist-info/METADATA,sha256=tqBa7h3Q3eRsAEcEoncm36sGv3zVRIHY5dyzixiVPE4,3663
|
|
4
|
+
sltcalc-0.1.0.dist-info/WHEEL,sha256=lCkmxWfQsSc9CfIClYeavTdQeEX2toPqufh9gI35EQA,87
|
|
5
|
+
sltcalc-0.1.0.dist-info/licenses/LICENSE,sha256=_WBHmfGHT8uGAnHK2W-hi7O_rO8t70lubivrqYujdIw,1065
|
|
6
|
+
sltcalc-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 fangface
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|