sltcalc 0.1.0__tar.gz

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.
@@ -0,0 +1,3 @@
1
+ # These are supported funding model platforms
2
+
3
+ github: fangface-hub
@@ -0,0 +1,43 @@
1
+ name: Publish to PyPI
2
+
3
+ on:
4
+ workflow_dispatch:
5
+
6
+ permissions:
7
+ contents: write
8
+
9
+ jobs:
10
+ build-and-publish:
11
+ runs-on: ubuntu-latest
12
+
13
+ steps:
14
+ - uses: actions/checkout@v4
15
+
16
+ - name: Extract version from pyproject.toml
17
+ id: version
18
+ run: |
19
+ VERSION=$(grep -m1 '^version = "' pyproject.toml | sed -E 's/^version = "([^"]+)"$/\1/')
20
+ echo "version=$VERSION" >> "$GITHUB_OUTPUT"
21
+ echo "tag=v$VERSION" >> "$GITHUB_OUTPUT"
22
+
23
+ - name: Install uv
24
+ uses: astral-sh/setup-uv@v3
25
+
26
+ - name: Build distribution
27
+ run: uv build
28
+
29
+ - name: Publish to PyPI
30
+ uses: pypa/gh-action-pypi-publish@release/v1
31
+ with:
32
+ password: ${{ secrets.PYPI_API_TOKEN }}
33
+ packages-dir: dist
34
+
35
+ - name: Create GitHub release and upload artifacts
36
+ uses: softprops/action-gh-release@v2
37
+ with:
38
+ tag_name: ${{ steps.version.outputs.tag }}
39
+ name: ${{ steps.version.outputs.tag }}
40
+ generate_release_notes: true
41
+ files: |
42
+ dist/*.tar.gz
43
+ dist/*.whl
@@ -0,0 +1,24 @@
1
+ name: Publish to TestPyPI
2
+
3
+ on:
4
+ workflow_dispatch:
5
+
6
+ jobs:
7
+ build-and-publish:
8
+ runs-on: ubuntu-latest
9
+
10
+ steps:
11
+ - uses: actions/checkout@v4
12
+
13
+ - name: Install uv
14
+ uses: astral-sh/setup-uv@v3
15
+
16
+ - name: Build wheel
17
+ run: uv build
18
+
19
+ - name: Publish to TestPyPI
20
+ uses: pypa/gh-action-pypi-publish@release/v1
21
+ with:
22
+ password: ${{ secrets.TEST_PYPI_API_TOKEN }}
23
+ repository-url: https://test.pypi.org/legacy/
24
+ packages-dir: dist
@@ -0,0 +1,218 @@
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[codz]
4
+ *$py.class
5
+
6
+ # C extensions
7
+ *.so
8
+
9
+ # Distribution / packaging
10
+ .Python
11
+ build/
12
+ develop-eggs/
13
+ dist/
14
+ downloads/
15
+ eggs/
16
+ .eggs/
17
+ lib/
18
+ lib64/
19
+ parts/
20
+ sdist/
21
+ var/
22
+ wheels/
23
+ share/python-wheels/
24
+ *.egg-info/
25
+ .installed.cfg
26
+ *.egg
27
+ MANIFEST
28
+
29
+ # PyInstaller
30
+ # Usually these files are written by a python script from a template
31
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
32
+ *.manifest
33
+ *.spec
34
+
35
+ # Installer logs
36
+ pip-log.txt
37
+ pip-delete-this-directory.txt
38
+
39
+ # Unit test / coverage reports
40
+ htmlcov/
41
+ .tox/
42
+ .nox/
43
+ .coverage
44
+ .coverage.*
45
+ .cache
46
+ nosetests.xml
47
+ coverage.xml
48
+ *.cover
49
+ *.py.cover
50
+ .hypothesis/
51
+ .pytest_cache/
52
+ cover/
53
+
54
+ # Translations
55
+ *.mo
56
+ *.pot
57
+
58
+ # Django stuff:
59
+ *.log
60
+ local_settings.py
61
+ db.sqlite3
62
+ db.sqlite3-journal
63
+
64
+ # Flask stuff:
65
+ instance/
66
+ .webassets-cache
67
+
68
+ # Scrapy stuff:
69
+ .scrapy
70
+
71
+ # Sphinx documentation
72
+ docs/_build/
73
+
74
+ # PyBuilder
75
+ .pybuilder/
76
+ target/
77
+
78
+ # Jupyter Notebook
79
+ .ipynb_checkpoints
80
+
81
+ # IPython
82
+ profile_default/
83
+ ipython_config.py
84
+
85
+ # pyenv
86
+ # For a library or package, you might want to ignore these files since the code is
87
+ # intended to run in multiple environments; otherwise, check them in:
88
+ # .python-version
89
+
90
+ # pipenv
91
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
92
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
93
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
94
+ # install all needed dependencies.
95
+ # Pipfile.lock
96
+
97
+ # UV
98
+ # Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.
99
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
100
+ # commonly ignored for libraries.
101
+ # uv.lock
102
+
103
+ # poetry
104
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
105
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
106
+ # commonly ignored for libraries.
107
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
108
+ # poetry.lock
109
+ # poetry.toml
110
+
111
+ # pdm
112
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
113
+ # pdm recommends including project-wide configuration in pdm.toml, but excluding .pdm-python.
114
+ # https://pdm-project.org/en/latest/usage/project/#working-with-version-control
115
+ # pdm.lock
116
+ # pdm.toml
117
+ .pdm-python
118
+ .pdm-build/
119
+
120
+ # pixi
121
+ # Similar to Pipfile.lock, it is generally recommended to include pixi.lock in version control.
122
+ # pixi.lock
123
+ # Pixi creates a virtual environment in the .pixi directory, just like venv module creates one
124
+ # in the .venv directory. It is recommended not to include this directory in version control.
125
+ .pixi
126
+
127
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
128
+ __pypackages__/
129
+
130
+ # Celery stuff
131
+ celerybeat-schedule
132
+ celerybeat.pid
133
+
134
+ # Redis
135
+ *.rdb
136
+ *.aof
137
+ *.pid
138
+
139
+ # RabbitMQ
140
+ mnesia/
141
+ rabbitmq/
142
+ rabbitmq-data/
143
+
144
+ # ActiveMQ
145
+ activemq-data/
146
+
147
+ # SageMath parsed files
148
+ *.sage.py
149
+
150
+ # Environments
151
+ .env
152
+ .envrc
153
+ .venv
154
+ env/
155
+ venv/
156
+ ENV/
157
+ env.bak/
158
+ venv.bak/
159
+
160
+ # Spyder project settings
161
+ .spyderproject
162
+ .spyproject
163
+
164
+ # Rope project settings
165
+ .ropeproject
166
+
167
+ # mkdocs documentation
168
+ /site
169
+
170
+ # mypy
171
+ .mypy_cache/
172
+ .dmypy.json
173
+ dmypy.json
174
+
175
+ # Pyre type checker
176
+ .pyre/
177
+
178
+ # pytype static type analyzer
179
+ .pytype/
180
+
181
+ # Cython debug symbols
182
+ cython_debug/
183
+
184
+ # PyCharm
185
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
186
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
187
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
188
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
189
+ # .idea/
190
+
191
+ # Abstra
192
+ # Abstra is an AI-powered process automation framework.
193
+ # Ignore directories containing user credentials, local state, and settings.
194
+ # Learn more at https://abstra.io/docs
195
+ .abstra/
196
+
197
+ # Visual Studio Code
198
+ # Visual Studio Code specific template is maintained in a separate VisualStudioCode.gitignore
199
+ # that can be found at https://github.com/github/gitignore/blob/main/Global/VisualStudioCode.gitignore
200
+ # and can be added to the global gitignore or merged into this file. However, if you prefer,
201
+ # you could uncomment the following to ignore the entire vscode folder
202
+ # .vscode/
203
+ # Temporary file for partial code execution
204
+ tempCodeRunnerFile.py
205
+
206
+ # Ruff stuff:
207
+ .ruff_cache/
208
+
209
+ # PyPI configuration file
210
+ .pypirc
211
+
212
+ # Marimo
213
+ marimo/_static/
214
+ marimo/_lsp/
215
+ __marimo__/
216
+
217
+ # Streamlit
218
+ .streamlit/secrets.toml
@@ -0,0 +1,23 @@
1
+ {
2
+ "version": "0.2.0",
3
+ "configurations": [
4
+ {
5
+ "name": "Debug Pytest (single test)",
6
+ "type": "python",
7
+ "request": "launch",
8
+ "module": "pytest",
9
+ "args": [
10
+ "-k", "${input:test_name}"
11
+ ],
12
+ "console": "integratedTerminal"
13
+ }
14
+ ],
15
+ "inputs": [
16
+ {
17
+ "id": "test_name",
18
+ "type": "promptString",
19
+ "description": "Enter pytest -k expression",
20
+ "default": "test_bits_get_cross_byte"
21
+ }
22
+ ]
23
+ }
@@ -0,0 +1,3 @@
1
+ {
2
+ "python.defaultInterpreterPath": "${workspaceFolder}/.venv/Scripts/python.exe"
3
+ }
sltcalc-0.1.0/LICENSE ADDED
@@ -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.
sltcalc-0.1.0/PKG-INFO ADDED
@@ -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,115 @@
1
+ # StructLayoutToolkitCalc
2
+
3
+ A safe, deterministic expression evaluator for computing bit‑accurate offsets, sizes, and field values within StructLayoutToolkit.
4
+
5
+ ## Overview
6
+
7
+ sltcalc provides a safe and deterministic expression evaluator used across StructLayoutToolkit to compute bit‑accurate offsets, sizes, and derived field values.
8
+ 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.
9
+ The evaluator supports arithmetic, bitwise operations, conditional expressions, and user‑defined variables supplied through an isolated environment.
10
+ This module enables dynamic field definitions, computed offsets, variable‑length structures, and protocol‑specific formulas while maintaining strict safety and structural consistency.
11
+
12
+ ## Usage
13
+
14
+ ### Basic
15
+
16
+ ```python
17
+ from sltcalc import SltEval
18
+
19
+ evaluator = SltEval()
20
+ result = evaluator.eval("1 + 2 * 3")
21
+ print(result) # 7
22
+ ```
23
+
24
+ ### With variables
25
+
26
+ ```python
27
+ from sltcalc import SltEval
28
+
29
+ env = {
30
+ "offset": 8,
31
+ "width": 3,
32
+ "flag": True,
33
+ }
34
+
35
+ evaluator = SltEval(env)
36
+
37
+ print(evaluator.eval("offset + width * 2")) # 14
38
+ print(evaluator.eval("1 if flag else 0")) # 1
39
+ print(evaluator.eval("99 if offset >= 8 else -1")) # 99
40
+ ```
41
+
42
+ ### Error behavior
43
+
44
+ ```python
45
+ from sltcalc import SltEval
46
+
47
+ evaluator = SltEval()
48
+
49
+ # NameError: undefined variable
50
+ evaluator.eval("unknown + 1")
51
+
52
+ # ValueError: unsafe function
53
+ evaluator.eval("sum(1, 2)")
54
+ ```
55
+
56
+ ## Supported expressions
57
+
58
+ SltEval evaluates a restricted subset of Python expression AST nodes.
59
+
60
+ ### Literals
61
+
62
+ - Numeric constants (for example: 0, 42, 3.5)
63
+ - Boolean constants (True, False)
64
+ - List literals (for example: [1, 2, 3])
65
+ - Tuple literals (for example: (1, 2, 3))
66
+ - Dict literals (for example: {"a": 1, "b": 2})
67
+
68
+ ### Variables
69
+
70
+ - Variable lookup from the evaluator environment (SltEval(env))
71
+
72
+ ### Binary operators
73
+
74
+ - Arithmetic: +, -, *, /, //, %, **
75
+ - Bitwise: &, |, ^, <<, >>
76
+
77
+ ### Unary operators
78
+
79
+ - Unary plus: +x
80
+ - Unary minus: -x
81
+ - Boolean negation: not x
82
+
83
+ ### Boolean operators
84
+
85
+ - and
86
+ - or
87
+
88
+ ### Comparisons
89
+
90
+ - ==, !=, <, <=, >, >=, is, is not, in, not in
91
+ - Chained comparisons are supported (for example: 1 < 2 < 3)
92
+
93
+ ### Conditional expression
94
+
95
+ - Ternary expression: a if condition else b
96
+
97
+ ### Subscript access
98
+
99
+ - Index/key access (for example: arr[0], mapping["key"])
100
+ - Nested access is supported (for example: access key "items" and then index 0)
101
+
102
+ ### Function calls
103
+
104
+ - Built-in allowlist: abs(...), all(...), any(...), len(...),
105
+ min(...), max(...), round(...), sorted(...), sum(...)
106
+ - Callables passed through environment are allowed
107
+ (for example: SltEval({"triple": triple}) then triple(4))
108
+
109
+ ## Not supported
110
+
111
+ - Attribute access (for example: obj.value)
112
+ - Set literals in expressions
113
+ - Non-name call targets (for example: (lambda x: x)(1))
114
+
115
+ Unsupported constructs raise ValueError with an Unsupported expression message.
@@ -0,0 +1,18 @@
1
+ $tomlFile = "pyproject.toml"
2
+ $content = Get-Content $tomlFile -Raw
3
+ $versionMatch = [regex]::Match($content, 'version\s*=\s*"(\d+)\.(\d+)\.(\d+)"')
4
+
5
+ if ($versionMatch.Success) {
6
+ $major = [int]$versionMatch.Groups[1].Value
7
+ $minor = [int]$versionMatch.Groups[2].Value
8
+ $patch = [int]$versionMatch.Groups[3].Value
9
+
10
+ $newMajor = $major + 1
11
+ $newVersion = "$newMajor.0.0"
12
+
13
+ $newContent = $content -replace 'version\s*=\s*"\d+\.\d+\.\d+"', "version = `"$newVersion`""
14
+ Set-Content $tomlFile $newContent -NoNewline
15
+ Write-Host "Bumped version to $newVersion"
16
+ } else {
17
+ Write-Error "Could not find version in $tomlFile"
18
+ }
@@ -0,0 +1,18 @@
1
+ $tomlFile = "pyproject.toml"
2
+ $content = Get-Content $tomlFile -Raw
3
+ $versionMatch = [regex]::Match($content, 'version\s*=\s*"(\d+)\.(\d+)\.(\d+)"')
4
+
5
+ if ($versionMatch.Success) {
6
+ $major = [int]$versionMatch.Groups[1].Value
7
+ $minor = [int]$versionMatch.Groups[2].Value
8
+ $patch = [int]$versionMatch.Groups[3].Value
9
+
10
+ $newMinor = $minor + 1
11
+ $newVersion = "$major.$newMinor.0"
12
+
13
+ $newContent = $content -replace 'version\s*=\s*"\d+\.\d+\.\d+"', "version = `"$newVersion`""
14
+ Set-Content $tomlFile $newContent -NoNewline
15
+ Write-Host "Bumped version to $newVersion"
16
+ } else {
17
+ Write-Error "Could not find version in $tomlFile"
18
+ }
@@ -0,0 +1,18 @@
1
+ $tomlFile = "pyproject.toml"
2
+ $content = Get-Content $tomlFile -Raw
3
+ $versionMatch = [regex]::Match($content, 'version\s*=\s*"(\d+)\.(\d+)\.(\d+)"')
4
+
5
+ if ($versionMatch.Success) {
6
+ $major = [int]$versionMatch.Groups[1].Value
7
+ $minor = [int]$versionMatch.Groups[2].Value
8
+ $patch = [int]$versionMatch.Groups[3].Value
9
+
10
+ $newPatch = $patch + 1
11
+ $newVersion = "$major.$minor.$newPatch"
12
+
13
+ $newContent = $content -replace 'version\s*=\s*"\d+\.\d+\.\d+"', "version = `"$newVersion`""
14
+ Set-Content $tomlFile $newContent -NoNewline
15
+ Write-Host "Bumped version to $newVersion"
16
+ } else {
17
+ Write-Error "Could not find version in $tomlFile"
18
+ }
@@ -0,0 +1,41 @@
1
+ [project]
2
+ name = "sltcalc"
3
+ version = "0.1.0"
4
+ license = "MIT"
5
+ license-files = ["LICENSE"]
6
+ description = "A safe, deterministic expression evaluator for computing bit‑accurate offsets, sizes, and field values within StructLayoutToolkit."
7
+ readme = "README.md"
8
+ authors = [
9
+ { name = "fangface" }
10
+ ]
11
+ requires-python = ">=3.12"
12
+ dependencies = []
13
+ keywords = ["struct", "byte", "bit", "layout", "data", "serialization", "deserialization"]
14
+
15
+ [project.urls]
16
+ Homepage = "https://github.com/fangface-hub/StructLayoutToolkitCalc"
17
+ Documentation = "https://readthedocs.org"
18
+ Repository = "https://github.com/fangface-hub/StructLayoutToolkitCalc"
19
+ Issues = "https://github.com/fangface-hub/StructLayoutToolkitCalc/issues"
20
+
21
+ [build-system]
22
+ requires = ["hatchling"]
23
+ build-backend = "hatchling.build"
24
+
25
+ [tool.hatch.build.targets.wheel]
26
+ packages = ["src/sltcalc"]
27
+
28
+ [dependency-groups]
29
+ dev = [
30
+ "pytest>=9.1.1",
31
+ ]
32
+
33
+ [tool.pytest.ini_options]
34
+ pythonpath = ["src"]
35
+ testpaths = ["tests"]
36
+
37
+ [[tool.uv.index]]
38
+ name = "testpypi"
39
+ url = "https://test.pypi.org/simple/"
40
+ publish-url = "https://test.pypi.org/legacy/"
41
+ explicit = true
@@ -0,0 +1,3 @@
1
+ from .sltcalc import SltEval
2
+
3
+ __all__ = ["SltEval"]
@@ -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,181 @@
1
+ """Tests for the SltEval class in sltcalc."""
2
+ import pytest
3
+
4
+ from sltcalc import SltEval
5
+
6
+
7
+ @pytest.mark.parametrize(
8
+ ("expr", "expected"),
9
+ [
10
+ ("1 + 2 * 3", 7),
11
+ ("7 // 2", 3),
12
+ ("2 ** 5", 32),
13
+ ("17 % 5", 2),
14
+ ("8 >> 1", 4),
15
+ ("3 << 2", 12),
16
+ ("5 & 3", 1),
17
+ ("5 | 2", 7),
18
+ ("5 ^ 3", 6),
19
+ ("+4", 4),
20
+ ("-4", -4),
21
+ ("10 / 4", 2.5),
22
+ ],
23
+ )
24
+ def test_eval_basic_operations(expr, expected):
25
+ """Test that SltEval correctly evaluates basic mathematical operations."""
26
+ evaluator = SltEval()
27
+ assert evaluator.eval(expr) == expected
28
+
29
+
30
+ def test_eval_uses_environment_variables():
31
+ """Test that SltEval correctly uses environment variables in expressions."""
32
+ evaluator = SltEval({"offset": 8, "width": 3})
33
+ assert evaluator.eval("offset + width * 2") == 14
34
+
35
+
36
+ @pytest.mark.parametrize(
37
+ ("env", "expr", "expected"),
38
+ [
39
+ ({
40
+ "flag": True
41
+ }, "1 if flag else 0", 1),
42
+ ({
43
+ "flag": False
44
+ }, "1 if flag else 0", 0),
45
+ ({}, "1 if 2 > 1 else 0", 1),
46
+ ({}, "1 if 2 < 1 else 0", 0),
47
+ ({
48
+ "x": 8
49
+ }, "99 if x >= 8 else -1", 99),
50
+ ({
51
+ "x": 7
52
+ }, "99 if x >= 8 else -1", -1),
53
+ ],
54
+ )
55
+ def test_eval_conditional_expression(env, expr, expected):
56
+ """Test that SltEval correctly evaluates conditional expressions."""
57
+ evaluator = SltEval(env)
58
+ assert evaluator.eval(expr) == expected
59
+
60
+
61
+ @pytest.mark.parametrize(
62
+ ("expr", "expected"),
63
+ [
64
+ ("2 > 1", True),
65
+ ("2 < 1", False),
66
+ ("10 >= 10", True),
67
+ ("10 != 10", False),
68
+ ("1 < 2 < 3", True),
69
+ ("1 < 2 > 3", False),
70
+ ("1 is 1", True),
71
+ ("1 is not 2", True),
72
+ ("2 in [1, 2, 3]", True),
73
+ ("9 not in [1, 2, 3]", True),
74
+ ],
75
+ )
76
+ def test_eval_comparison_expression(expr, expected):
77
+ """Test that SltEval correctly evaluates comparison expressions."""
78
+ evaluator = SltEval()
79
+ assert evaluator.eval(expr) is expected
80
+
81
+
82
+ @pytest.mark.parametrize(
83
+ ("expr", "expected"),
84
+ [
85
+ ("True and 1", 1),
86
+ ("False and 1", False),
87
+ ("0 or 5", 5),
88
+ ("3 or 5", 3),
89
+ ("not 0", True),
90
+ ("not 1", False),
91
+ ],
92
+ )
93
+ def test_eval_boolean_operators(expr, expected):
94
+ """Test that SltEval correctly evaluates boolean operators."""
95
+ evaluator = SltEval()
96
+ assert evaluator.eval(expr) == expected
97
+
98
+
99
+ def test_eval_call_with_unsupported_callable_expression_raises_value_error():
100
+ """Test that SltEval rejects non-name callable expressions."""
101
+ evaluator = SltEval()
102
+ with pytest.raises(ValueError, match="Unsupported expression"):
103
+ evaluator.eval("(lambda x: x)(1)")
104
+
105
+
106
+ @pytest.mark.parametrize(
107
+ ("expr", "expected"),
108
+ [
109
+ ("abs(-10)", 10),
110
+ ("sum([1, 2, 3])", 6),
111
+ ("len([1, 2, 3])", 3),
112
+ ("round(3.14159, 2)", 3.14),
113
+ ("min(3, 1, 9)", 1),
114
+ ("max(3, 1, 9)", 9),
115
+ ("max(2, abs(-5))", 5),
116
+ ],
117
+ )
118
+ def test_eval_safe_functions(expr, expected):
119
+ """Test that SltEval correctly evaluates allowed function calls."""
120
+ evaluator = SltEval()
121
+ assert evaluator.eval(expr) == expected
122
+
123
+
124
+ def test_eval_raises_name_error_for_undefined_variable():
125
+ """Test that SltEval raises a NameError for undefined variables."""
126
+ evaluator = SltEval()
127
+ with pytest.raises(NameError, match="Undefined variable: unknown"):
128
+ evaluator.eval("unknown + 1")
129
+
130
+
131
+ def test_eval_raises_value_error_for_unsafe_function():
132
+ """Test that SltEval raises a ValueError for unsafe functions."""
133
+ evaluator = SltEval()
134
+ with pytest.raises(ValueError, match="Unsafe function: open"):
135
+ evaluator.eval("open('dummy.txt')")
136
+
137
+
138
+ def test_eval_uses_callable_from_environment():
139
+ """Test that SltEval can call callables provided through env."""
140
+
141
+ def triple(x):
142
+ return x * 3
143
+
144
+ evaluator = SltEval({"triple": triple})
145
+ assert evaluator.eval("triple(4)") == 12
146
+
147
+
148
+ def test_eval_raises_value_error_for_unsupported_expression():
149
+ """Test that SltEval raises a ValueError for unsupported expressions."""
150
+ evaluator = SltEval()
151
+ # Set literals are intentionally unsupported by the evaluator.
152
+ with pytest.raises(ValueError, match="Unsupported expression"):
153
+ evaluator.eval("{1, 2, 3}")
154
+
155
+
156
+ @pytest.mark.parametrize(
157
+ ("expr", "expected"),
158
+ [
159
+ ("[1, 2, 3]", [1, 2, 3]),
160
+ ("{'a': 1, 'b': 2}", {
161
+ "a": 1,
162
+ "b": 2
163
+ }),
164
+ ("(1, 2, 3)", (1, 2, 3)),
165
+ ("[1, 2, 3][1]", 2),
166
+ ("{'a': 10, 'b': 20}['b']", 20),
167
+ ("('x', 'y', 'z')[2]", "z"),
168
+ ("{'items': [4, 5, 6]}['items'][0]", 4),
169
+ ],
170
+ )
171
+ def test_eval_collections_and_subscript(expr, expected):
172
+ """Test that SltEval supports list/dict/tuple literals and indexing."""
173
+ evaluator = SltEval()
174
+ assert evaluator.eval(expr) == expected
175
+
176
+
177
+ def test_eval_subscript_with_environment_variable():
178
+ """Test indexing into collections provided via environment variables."""
179
+ evaluator = SltEval({"arr": [10, 20, 30], "mapping": {"k": 7}})
180
+ assert evaluator.eval("arr[2]") == 30
181
+ assert evaluator.eval("mapping['k']") == 7
sltcalc-0.1.0/uv.lock ADDED
@@ -0,0 +1,79 @@
1
+ version = 1
2
+ revision = 3
3
+ requires-python = ">=3.12"
4
+
5
+ [[package]]
6
+ name = "colorama"
7
+ version = "0.4.6"
8
+ source = { registry = "https://pypi.org/simple" }
9
+ sdist = { url = "https://files.pythonhosted.org/packages/d8/53/6f443c9a4a8358a93a6792e2acffb9d9d5cb0a5cfd8802644b7b1c9a02e4/colorama-0.4.6.tar.gz", hash = "sha256:08695f5cb7ed6e0531a20572697297273c47b8cae5a63ffc6d6ed5c201be6e44", size = 27697, upload-time = "2022-10-25T02:36:22.414Z" }
10
+ wheels = [
11
+ { url = "https://files.pythonhosted.org/packages/d1/d6/3965ed04c63042e047cb6a3e6ed1a63a35087b6a609aa3a15ed8ac56c221/colorama-0.4.6-py2.py3-none-any.whl", hash = "sha256:4f1d9991f5acc0ca119f9d443620b77f9d6b33703e51011c16baf57afb285fc6", size = 25335, upload-time = "2022-10-25T02:36:20.889Z" },
12
+ ]
13
+
14
+ [[package]]
15
+ name = "iniconfig"
16
+ version = "2.3.0"
17
+ source = { registry = "https://pypi.org/simple" }
18
+ sdist = { url = "https://files.pythonhosted.org/packages/72/34/14ca021ce8e5dfedc35312d08ba8bf51fdd999c576889fc2c24cb97f4f10/iniconfig-2.3.0.tar.gz", hash = "sha256:c76315c77db068650d49c5b56314774a7804df16fee4402c1f19d6d15d8c4730", size = 20503, upload-time = "2025-10-18T21:55:43.219Z" }
19
+ wheels = [
20
+ { url = "https://files.pythonhosted.org/packages/cb/b1/3846dd7f199d53cb17f49cba7e651e9ce294d8497c8c150530ed11865bb8/iniconfig-2.3.0-py3-none-any.whl", hash = "sha256:f631c04d2c48c52b84d0d0549c99ff3859c98df65b3101406327ecc7d53fbf12", size = 7484, upload-time = "2025-10-18T21:55:41.639Z" },
21
+ ]
22
+
23
+ [[package]]
24
+ name = "packaging"
25
+ version = "26.2"
26
+ source = { registry = "https://pypi.org/simple" }
27
+ sdist = { url = "https://files.pythonhosted.org/packages/d7/f1/e7a6dd94a8d4a5626c03e4e99c87f241ba9e350cd9e6d75123f992427270/packaging-26.2.tar.gz", hash = "sha256:ff452ff5a3e828ce110190feff1178bb1f2ea2281fa2075aadb987c2fb221661", size = 228134, upload-time = "2026-04-24T20:15:23.917Z" }
28
+ wheels = [
29
+ { url = "https://files.pythonhosted.org/packages/df/b2/87e62e8c3e2f4b32e5fe99e0b86d576da1312593b39f47d8ceef365e95ed/packaging-26.2-py3-none-any.whl", hash = "sha256:5fc45236b9446107ff2415ce77c807cee2862cb6fac22b8a73826d0693b0980e", size = 100195, upload-time = "2026-04-24T20:15:22.081Z" },
30
+ ]
31
+
32
+ [[package]]
33
+ name = "pluggy"
34
+ version = "1.6.0"
35
+ source = { registry = "https://pypi.org/simple" }
36
+ sdist = { url = "https://files.pythonhosted.org/packages/f9/e2/3e91f31a7d2b083fe6ef3fa267035b518369d9511ffab804f839851d2779/pluggy-1.6.0.tar.gz", hash = "sha256:7dcc130b76258d33b90f61b658791dede3486c3e6bfb003ee5c9bfb396dd22f3", size = 69412, upload-time = "2025-05-15T12:30:07.975Z" }
37
+ wheels = [
38
+ { url = "https://files.pythonhosted.org/packages/54/20/4d324d65cc6d9205fabedc306948156824eb9f0ee1633355a8f7ec5c66bf/pluggy-1.6.0-py3-none-any.whl", hash = "sha256:e920276dd6813095e9377c0bc5566d94c932c33b27a3e3945d8389c374dd4746", size = 20538, upload-time = "2025-05-15T12:30:06.134Z" },
39
+ ]
40
+
41
+ [[package]]
42
+ name = "pygments"
43
+ version = "2.20.0"
44
+ source = { registry = "https://pypi.org/simple" }
45
+ sdist = { url = "https://files.pythonhosted.org/packages/c3/b2/bc9c9196916376152d655522fdcebac55e66de6603a76a02bca1b6414f6c/pygments-2.20.0.tar.gz", hash = "sha256:6757cd03768053ff99f3039c1a36d6c0aa0b263438fcab17520b30a303a82b5f", size = 4955991, upload-time = "2026-03-29T13:29:33.898Z" }
46
+ wheels = [
47
+ { url = "https://files.pythonhosted.org/packages/f4/7e/a72dd26f3b0f4f2bf1dd8923c85f7ceb43172af56d63c7383eb62b332364/pygments-2.20.0-py3-none-any.whl", hash = "sha256:81a9e26dd42fd28a23a2d169d86d7ac03b46e2f8b59ed4698fb4785f946d0176", size = 1231151, upload-time = "2026-03-29T13:29:30.038Z" },
48
+ ]
49
+
50
+ [[package]]
51
+ name = "pytest"
52
+ version = "9.1.1"
53
+ source = { registry = "https://pypi.org/simple" }
54
+ dependencies = [
55
+ { name = "colorama", marker = "sys_platform == 'win32'" },
56
+ { name = "iniconfig" },
57
+ { name = "packaging" },
58
+ { name = "pluggy" },
59
+ { name = "pygments" },
60
+ ]
61
+ sdist = { url = "https://files.pythonhosted.org/packages/e4/47/b9efed96c114afcfa3c9d3fe98a76a1d14c74a9e266d397cf6eb64be5e01/pytest-9.1.1.tar.gz", hash = "sha256:1088fbde8f2b49d95a549a195707afa7a76a3ce9bcadc26b6d71f0ffda5fe313", size = 1636369, upload-time = "2026-06-19T10:58:32.857Z" }
62
+ wheels = [
63
+ { url = "https://files.pythonhosted.org/packages/24/25/1de2678b631f5a49215c6c96fff41ba892b0a34df68d6d80292b1b48aa7f/pytest-9.1.1-py3-none-any.whl", hash = "sha256:37a86b45efb9a47a61a36449063e8e18d0cab3161329fc099eb21783169c4f0c", size = 386536, upload-time = "2026-06-19T10:58:31.347Z" },
64
+ ]
65
+
66
+ [[package]]
67
+ name = "sltcalc"
68
+ version = "0.1.0"
69
+ source = { editable = "." }
70
+
71
+ [package.dev-dependencies]
72
+ dev = [
73
+ { name = "pytest" },
74
+ ]
75
+
76
+ [package.metadata]
77
+
78
+ [package.metadata.requires-dev]
79
+ dev = [{ name = "pytest", specifier = ">=9.1.1" }]