esp-bsasm 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,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,254 @@
1
+ Metadata-Version: 2.4
2
+ Name: esp-bsasm
3
+ Version: 0.1.0
4
+ Summary: BitScrambler program assembler for ESP-IDF
5
+ Author-email: "Espressif Systems (Shanghai) CO LTD" <espressif@espressif.com>
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Repository, https://github.com/espressif/esp-bsasm
8
+ Project-URL: Source Code, https://gitlab.espressif.cn:27227/espressif/esp-bsasm
9
+ Project-URL: Documentation, https://docs.espressif.com/projects/esp-idf/en/latest/esp32c5/api-reference/peripherals/bitscrambler.html
10
+ Keywords: esp32,espressif,bitscrambler,assembler
11
+ Classifier: Development Status :: 5 - Production/Stable
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Natural Language :: English
14
+ Classifier: Environment :: Console
15
+ Classifier: Topic :: Software Development :: Embedded Systems
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3 :: Only
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Classifier: Programming Language :: Python :: 3.13
21
+ Classifier: Programming Language :: Python :: 3.14
22
+ Classifier: Programming Language :: Python :: 3.15
23
+ Classifier: Operating System :: POSIX
24
+ Classifier: Operating System :: Microsoft :: Windows
25
+ Classifier: Operating System :: MacOS :: MacOS X
26
+ Requires-Python: >=3.11
27
+ Description-Content-Type: text/markdown
28
+ License-File: LICENSE
29
+ Requires-Dist: antlr4-python3-runtime>=4.13.2
30
+ Requires-Dist: esp-pylib>=1.2.1
31
+ Requires-Dist: rich-click
32
+ Provides-Extra: dev
33
+ Requires-Dist: czespressif; extra == "dev"
34
+ Dynamic: license-file
35
+
36
+ # esp-bsasm — the BitScrambler program assembler
37
+
38
+ `esp-bsasm` translates BitScrambler assembly programs (`.bsasm`) into the
39
+ binary format the BitScrambler hardware loads (`.bsbin`), as documented in
40
+ the ESP32-C5 Technical Reference Manual, BitScrambler (BITSCRM) chapter, and
41
+ in the ESP-IDF programming guide under *API Reference > Peripherals >
42
+ BitScrambler*.
43
+
44
+ This README is written for maintainers. For the user-visible language and
45
+ build integration, see the ESP-IDF programming guide; for the hardware bit
46
+ layouts, see the TRM chapter.
47
+
48
+ ## Relationship with ESP-IDF
49
+
50
+ ESP-IDF consumes this package as the `esp-bsasm` pip dependency (listed in
51
+ `tools/requirements/requirements.core.txt`) and builds BitScrambler programs
52
+ from its own CI. It does not vendor the sources; what lives on the ESP-IDF
53
+ side is the test suite (`tools/test_bsasm/`), which validates the installed
54
+ package — including unreleased branches via the `CI_PYTHON_TOOL_REPO` /
55
+ `CI_PYTHON_TOOL_BRANCH` CI mechanism (see below). Language changes are
56
+ developed and validated here; an ESP-IDF MR is only needed when wiring the
57
+ results into the ESP-IDF test suite.
58
+
59
+ ## Directory layout
60
+
61
+ ```
62
+ BitScrambler.g4 the language grammar: the single source of truth
63
+ for the syntax of the language
64
+ regenerate.py re-create the ANTLR products (pinned ANTLR version;
65
+ --check verifies the committed files are in sync)
66
+ pyproject.toml package metadata (no setup.py; src layout)
67
+ src/bsasm/
68
+ generated/ ANTLR-generated lexer/parser/visitor (committed,
69
+ so assembling never needs a JDK)
70
+ parsing.py ANTLR driver: source text -> parse tree
71
+ builder.py visitor: parse tree -> statements
72
+ model.py all the data: statement IR and program IR (frozen
73
+ dataclasses over shared instruction-level enums)
74
+ sema.py semantic analysis: statements -> Program (label
75
+ resolution, ranges, mux compatibility, chip gating)
76
+ encoder.py Program -> .bsbin bytes (257-bit instructions,
77
+ header, LUT packing)
78
+ cli.py command line interface
79
+ errors.py AssemblerError diagnostics with 1-based locations
80
+ ```
81
+
82
+ The pipeline is strictly linear, one module per stage, each independently
83
+ testable:
84
+
85
+ ```
86
+ source text --parsing--> parse tree --builder--> statements --sema--> Program --encoder--> .bsbin
87
+ ```
88
+
89
+ `model.py` owns all the data; `parsing`/`builder` only move data into shape;
90
+ `sema` owns every decision that needs a readable diagnostic; `encoder` is a
91
+ mechanical bit packer.
92
+
93
+ ## Who checks what
94
+
95
+ The grammar owns the *shape* of the language; the assembler owns *meaning*:
96
+
97
+ | Grammar (`BitScrambler.g4`) | Assembler (`sema.py`, `encoder.py`) |
98
+ | --- | --- |
99
+ | instruction operand counts and shapes | numeric ranges (e.g. width ∈ {0, 8, 16, 32}) |
100
+ | ranges (`a..b`), comparator sources (`bl<=o0`), relative addressing (`5+a`) | value spellings (`cfg prefetch true`, hex/bin) |
101
+ | bundle structure (comma continuation, newline termination) | label resolution and duplicate detection |
102
+ | labels vs mnemonics lexing (`loopa:` is a label) | ctrsel/lutsel/rel_addr conflicts between mux sources |
103
+ | | the 8-instruction hardware limit, output duplication checks, jump targets past the program end |
104
+
105
+ Rationale: only the assembler can produce readable diagnostics (it knows
106
+ what a mux source *means*), while ANTLR reports syntax errors with exact
107
+ positions and is far easier to extend than hand-rolled character scanning.
108
+
109
+ ## Workflow: assembling a program (daily use)
110
+
111
+ ```
112
+ python -m bsasm program.bsasm [output.bsbin] [-c chip.json]
113
+ ```
114
+
115
+ `chip.json` describes per-chip capabilities (see the
116
+ `bsasm_targets/*.json` files in ESP-IDF). As a library:
117
+
118
+ ```python
119
+ import bsasm
120
+
121
+ program = bsasm.assemble(source_text, chipcfg)
122
+ binary = bsasm.encode(program)
123
+ ```
124
+
125
+ ## Workflow: changing the grammar
126
+
127
+ 1. Edit `BitScrambler.g4`.
128
+ 2. Run `python regenerate.py` and commit the regenerated files under
129
+ `src/bsasm/generated/`. CI checks they are in sync (`--check`).
130
+ 3. Add tests (see *Testing* below) and, if the language changed, update the
131
+ ESP-IDF programming guide.
132
+
133
+ Rules of thumb that keep the grammar clean:
134
+
135
+ * Keep it free of target-language actions and semantic predicates, so it
136
+ stays a portable spec.
137
+ * Every keyword token must be defined before `NAME` (equal-length lexer
138
+ matches go to the first rule) and must be accepted by the `identifier`
139
+ rule, so labels named after keywords (`loopa:`, `jmp set`) keep working.
140
+ * Glued constructs must be single lexer tokens: `AUX_CMP` ('bl<=o0') and
141
+ `REL_OPERAND` ('l0+a') pin the no-whitespace rule without target-specific
142
+ tricks.
143
+ * One content statement per line (`line` rule); a comma always introduces
144
+ another sub-instruction (no dangling commas).
145
+
146
+ ## Workflow: adding an instruction
147
+
148
+ 1. Grammar: add the mnemonic token (with case-insensitive fragments, before
149
+ `NAME`) and a parser rule wiring its operand shape; add the rule to
150
+ `subInstr` and the token to `identifier`.
151
+ 2. Regenerate (`python regenerate.py`) and commit.
152
+ 3. `model.py`: add a `*Sub` statement dataclass.
153
+ 4. `builder.py`: add a `visitSub*` method — for mnemonics with A/B/H/L
154
+ suffixes, add a mnemonic→(counter, halves) table alongside the existing
155
+ ones.
156
+ 5. `sema.py`: handle the new sub-instruction in `_InstBuilder.add`,
157
+ producing an `Opcode`; wrap in `_check_chip_supports(...)` if gated, and
158
+ list the group in the chip capability json.
159
+ 6. `encoder.py`: extend the opcode assembly only for a genuinely new
160
+ opcode pattern (the `_OP_BASES` table covers all seven hardware
161
+ opcodes).
162
+ 7. Tests as above.
163
+
164
+ ## Workflow: adding a cfg key
165
+
166
+ 1. Grammar: keyword token(s) for the key and its value spellings, plus a
167
+ `cfgStmt` alternative.
168
+ 2. `model.py`: `CfgKey` member, plus a dedicated enum type if the value is
169
+ an enum (see `LoopEndsOn`).
170
+ 3. `builder.py`: a `visitCfgStmt` alternative. Match explicitly — a missing
171
+ alternative must fail loudly, not fall through to another key.
172
+ 4. `sema.py`: a `_collect_cfg` case with the allowed spellings; make sure
173
+ the `ProgramMeta` default keeps old programs byte-identical.
174
+ 5. `encoder.py`: only if the value reaches the .bsbin header — see
175
+ `loop_ends_on` and the formerly-reserved header byte for the pattern.
176
+ 6. Tests — the regression suite currently lives in ESP-IDF at
177
+ `tools/test_bsasm/` (see below) and runs against the installed package.
178
+
179
+ ## Testing
180
+
181
+ The regression suite currently lives in ESP-IDF at `tools/test_bsasm/`
182
+ (subprocess harness over JSON-sidecar testcases, the frozen byte-compat
183
+ golden corpus, and API-level tests including TRM bit-layout conformance)
184
+ and runs against the installed `esp-bsasm` package. It migrates into this
185
+ repository once the first release cycle has settled.
186
+
187
+ ## Testing unreleased changes in ESP-IDF CI
188
+
189
+ ESP-IDF can test a Python tool package from a live git branch instead of the
190
+ released version: its CI defines `CI_PYTHON_TOOL_REPO` and
191
+ `CI_PYTHON_TOOL_BRANCH` (component inputs of the `ci/actions/common`
192
+ template, documented in esp-idf's `.gitlab/ci/common.yml`). Running the
193
+ ESP-IDF pipeline with those set to `espressif/esp-bsasm` and this
194
+ repository's branch pip-installs this checkout into the ESP-IDF CI
195
+ environment before the jobs run — so ESP-IDF's `tools/test_bsasm` suite
196
+ validates an unmerged esp-bsasm branch end to end.
197
+
198
+ Today ESP-IDF CI already exercises the vendored copy at `tools/bsasm` with
199
+ no extra configuration; the mechanism becomes relevant once ESP-IDF
200
+ switches to consuming the published package (then a esp-bsasm MR triggers
201
+ an ESP-IDF pipeline against its own branch before release).
202
+
203
+ ## Repository CI
204
+
205
+ `.gitlab-ci.yml` runs three jobs on merge requests and on the default
206
+ branch: `pre-commit` (ruff-based hooks, see `.pre-commit-config.yaml`),
207
+ `regenerate-check` (`regenerate.py --check`, needs a JDK; only when the
208
+ grammar changed), and `publish_pypi` on release tags `v*` (build + twine
209
+ upload; requires the protected/masked `TWINE_USERNAME`/`TWINE_PASSWORD` CI
210
+ variables).
211
+
212
+ ## Pre-commit hooks — code quality
213
+
214
+ - ruff for linting (pyflakes, pycodestyle, import sorting and pyupgrade
215
+ rules) and ruff for code formatting
216
+ - mypy type checker
217
+ - codespell for finding common misspellings
218
+ - conventional-precommit-linter for checking commit messages
219
+
220
+ The ruff, mypy and codespell settings live in `pyproject.toml`. Install the
221
+ hooks locally with `pre-commit install`; most hooks fix the problems they
222
+ find instead of only reporting them.
223
+
224
+ ## Generated files and linting
225
+
226
+ `src/bsasm/generated/` is machine output (ANTLR 4.13.2, pinned in
227
+ `pyproject.toml` and `regenerate.py`; keep the two in sync). It is excluded
228
+ from ruff, ruff format, the whitespace/EOF hooks and mypy error reporting
229
+ (per-module override in `pyproject.toml`) — do not edit or reformat it by
230
+ hand. All other sources are ruff-formatted (single quotes, 120 columns,
231
+ py311 target).
232
+
233
+ ## Behaviour compatibility contract
234
+
235
+ The rewrite is verified byte-identical against the original assembler (the
236
+ one that lived in ESP-IDF until the ANTLR rewrite) on the golden corpus.
237
+ Beyond that contract:
238
+
239
+ **Fixed bugs** (all clean errors now): `cfg trailing_bytes` above 8191 (was
240
+ a `struct.pack` crash); `l8`/`l16` beyond the LUT width (were silently
241
+ encoded as comparator inputs); 16-bit LUT values above 65535 (wrapped
242
+ around); jump targets past the program end (overflowed the 3-bit target
243
+ field into the counter-select bit); duplicate labels (silently
244
+ overwritten).
245
+
246
+ **Tightened error handling** (legal programs unaffected): misspelled
247
+ mnemonics like `ifx`/`loopax`/`addafoo`, dangling trailing commas, numeric
248
+ labels, two bundles on one line — all syntax errors now.
249
+
250
+ **Kept quirks** for parity: labels and cfg spellings are case-insensitive;
251
+ a bare `+a` operand resolves to input 32 relative; duplicate `write`/`read`
252
+ in one bundle keep the last value; the `Did you forget an L` hint message.
253
+
254
+ **Diagnostics**: 1-based line/column; exit code 2 on any error.
@@ -0,0 +1,219 @@
1
+ # esp-bsasm — the BitScrambler program assembler
2
+
3
+ `esp-bsasm` translates BitScrambler assembly programs (`.bsasm`) into the
4
+ binary format the BitScrambler hardware loads (`.bsbin`), as documented in
5
+ the ESP32-C5 Technical Reference Manual, BitScrambler (BITSCRM) chapter, and
6
+ in the ESP-IDF programming guide under *API Reference > Peripherals >
7
+ BitScrambler*.
8
+
9
+ This README is written for maintainers. For the user-visible language and
10
+ build integration, see the ESP-IDF programming guide; for the hardware bit
11
+ layouts, see the TRM chapter.
12
+
13
+ ## Relationship with ESP-IDF
14
+
15
+ ESP-IDF consumes this package as the `esp-bsasm` pip dependency (listed in
16
+ `tools/requirements/requirements.core.txt`) and builds BitScrambler programs
17
+ from its own CI. It does not vendor the sources; what lives on the ESP-IDF
18
+ side is the test suite (`tools/test_bsasm/`), which validates the installed
19
+ package — including unreleased branches via the `CI_PYTHON_TOOL_REPO` /
20
+ `CI_PYTHON_TOOL_BRANCH` CI mechanism (see below). Language changes are
21
+ developed and validated here; an ESP-IDF MR is only needed when wiring the
22
+ results into the ESP-IDF test suite.
23
+
24
+ ## Directory layout
25
+
26
+ ```
27
+ BitScrambler.g4 the language grammar: the single source of truth
28
+ for the syntax of the language
29
+ regenerate.py re-create the ANTLR products (pinned ANTLR version;
30
+ --check verifies the committed files are in sync)
31
+ pyproject.toml package metadata (no setup.py; src layout)
32
+ src/bsasm/
33
+ generated/ ANTLR-generated lexer/parser/visitor (committed,
34
+ so assembling never needs a JDK)
35
+ parsing.py ANTLR driver: source text -> parse tree
36
+ builder.py visitor: parse tree -> statements
37
+ model.py all the data: statement IR and program IR (frozen
38
+ dataclasses over shared instruction-level enums)
39
+ sema.py semantic analysis: statements -> Program (label
40
+ resolution, ranges, mux compatibility, chip gating)
41
+ encoder.py Program -> .bsbin bytes (257-bit instructions,
42
+ header, LUT packing)
43
+ cli.py command line interface
44
+ errors.py AssemblerError diagnostics with 1-based locations
45
+ ```
46
+
47
+ The pipeline is strictly linear, one module per stage, each independently
48
+ testable:
49
+
50
+ ```
51
+ source text --parsing--> parse tree --builder--> statements --sema--> Program --encoder--> .bsbin
52
+ ```
53
+
54
+ `model.py` owns all the data; `parsing`/`builder` only move data into shape;
55
+ `sema` owns every decision that needs a readable diagnostic; `encoder` is a
56
+ mechanical bit packer.
57
+
58
+ ## Who checks what
59
+
60
+ The grammar owns the *shape* of the language; the assembler owns *meaning*:
61
+
62
+ | Grammar (`BitScrambler.g4`) | Assembler (`sema.py`, `encoder.py`) |
63
+ | --- | --- |
64
+ | instruction operand counts and shapes | numeric ranges (e.g. width ∈ {0, 8, 16, 32}) |
65
+ | ranges (`a..b`), comparator sources (`bl<=o0`), relative addressing (`5+a`) | value spellings (`cfg prefetch true`, hex/bin) |
66
+ | bundle structure (comma continuation, newline termination) | label resolution and duplicate detection |
67
+ | labels vs mnemonics lexing (`loopa:` is a label) | ctrsel/lutsel/rel_addr conflicts between mux sources |
68
+ | | the 8-instruction hardware limit, output duplication checks, jump targets past the program end |
69
+
70
+ Rationale: only the assembler can produce readable diagnostics (it knows
71
+ what a mux source *means*), while ANTLR reports syntax errors with exact
72
+ positions and is far easier to extend than hand-rolled character scanning.
73
+
74
+ ## Workflow: assembling a program (daily use)
75
+
76
+ ```
77
+ python -m bsasm program.bsasm [output.bsbin] [-c chip.json]
78
+ ```
79
+
80
+ `chip.json` describes per-chip capabilities (see the
81
+ `bsasm_targets/*.json` files in ESP-IDF). As a library:
82
+
83
+ ```python
84
+ import bsasm
85
+
86
+ program = bsasm.assemble(source_text, chipcfg)
87
+ binary = bsasm.encode(program)
88
+ ```
89
+
90
+ ## Workflow: changing the grammar
91
+
92
+ 1. Edit `BitScrambler.g4`.
93
+ 2. Run `python regenerate.py` and commit the regenerated files under
94
+ `src/bsasm/generated/`. CI checks they are in sync (`--check`).
95
+ 3. Add tests (see *Testing* below) and, if the language changed, update the
96
+ ESP-IDF programming guide.
97
+
98
+ Rules of thumb that keep the grammar clean:
99
+
100
+ * Keep it free of target-language actions and semantic predicates, so it
101
+ stays a portable spec.
102
+ * Every keyword token must be defined before `NAME` (equal-length lexer
103
+ matches go to the first rule) and must be accepted by the `identifier`
104
+ rule, so labels named after keywords (`loopa:`, `jmp set`) keep working.
105
+ * Glued constructs must be single lexer tokens: `AUX_CMP` ('bl<=o0') and
106
+ `REL_OPERAND` ('l0+a') pin the no-whitespace rule without target-specific
107
+ tricks.
108
+ * One content statement per line (`line` rule); a comma always introduces
109
+ another sub-instruction (no dangling commas).
110
+
111
+ ## Workflow: adding an instruction
112
+
113
+ 1. Grammar: add the mnemonic token (with case-insensitive fragments, before
114
+ `NAME`) and a parser rule wiring its operand shape; add the rule to
115
+ `subInstr` and the token to `identifier`.
116
+ 2. Regenerate (`python regenerate.py`) and commit.
117
+ 3. `model.py`: add a `*Sub` statement dataclass.
118
+ 4. `builder.py`: add a `visitSub*` method — for mnemonics with A/B/H/L
119
+ suffixes, add a mnemonic→(counter, halves) table alongside the existing
120
+ ones.
121
+ 5. `sema.py`: handle the new sub-instruction in `_InstBuilder.add`,
122
+ producing an `Opcode`; wrap in `_check_chip_supports(...)` if gated, and
123
+ list the group in the chip capability json.
124
+ 6. `encoder.py`: extend the opcode assembly only for a genuinely new
125
+ opcode pattern (the `_OP_BASES` table covers all seven hardware
126
+ opcodes).
127
+ 7. Tests as above.
128
+
129
+ ## Workflow: adding a cfg key
130
+
131
+ 1. Grammar: keyword token(s) for the key and its value spellings, plus a
132
+ `cfgStmt` alternative.
133
+ 2. `model.py`: `CfgKey` member, plus a dedicated enum type if the value is
134
+ an enum (see `LoopEndsOn`).
135
+ 3. `builder.py`: a `visitCfgStmt` alternative. Match explicitly — a missing
136
+ alternative must fail loudly, not fall through to another key.
137
+ 4. `sema.py`: a `_collect_cfg` case with the allowed spellings; make sure
138
+ the `ProgramMeta` default keeps old programs byte-identical.
139
+ 5. `encoder.py`: only if the value reaches the .bsbin header — see
140
+ `loop_ends_on` and the formerly-reserved header byte for the pattern.
141
+ 6. Tests — the regression suite currently lives in ESP-IDF at
142
+ `tools/test_bsasm/` (see below) and runs against the installed package.
143
+
144
+ ## Testing
145
+
146
+ The regression suite currently lives in ESP-IDF at `tools/test_bsasm/`
147
+ (subprocess harness over JSON-sidecar testcases, the frozen byte-compat
148
+ golden corpus, and API-level tests including TRM bit-layout conformance)
149
+ and runs against the installed `esp-bsasm` package. It migrates into this
150
+ repository once the first release cycle has settled.
151
+
152
+ ## Testing unreleased changes in ESP-IDF CI
153
+
154
+ ESP-IDF can test a Python tool package from a live git branch instead of the
155
+ released version: its CI defines `CI_PYTHON_TOOL_REPO` and
156
+ `CI_PYTHON_TOOL_BRANCH` (component inputs of the `ci/actions/common`
157
+ template, documented in esp-idf's `.gitlab/ci/common.yml`). Running the
158
+ ESP-IDF pipeline with those set to `espressif/esp-bsasm` and this
159
+ repository's branch pip-installs this checkout into the ESP-IDF CI
160
+ environment before the jobs run — so ESP-IDF's `tools/test_bsasm` suite
161
+ validates an unmerged esp-bsasm branch end to end.
162
+
163
+ Today ESP-IDF CI already exercises the vendored copy at `tools/bsasm` with
164
+ no extra configuration; the mechanism becomes relevant once ESP-IDF
165
+ switches to consuming the published package (then a esp-bsasm MR triggers
166
+ an ESP-IDF pipeline against its own branch before release).
167
+
168
+ ## Repository CI
169
+
170
+ `.gitlab-ci.yml` runs three jobs on merge requests and on the default
171
+ branch: `pre-commit` (ruff-based hooks, see `.pre-commit-config.yaml`),
172
+ `regenerate-check` (`regenerate.py --check`, needs a JDK; only when the
173
+ grammar changed), and `publish_pypi` on release tags `v*` (build + twine
174
+ upload; requires the protected/masked `TWINE_USERNAME`/`TWINE_PASSWORD` CI
175
+ variables).
176
+
177
+ ## Pre-commit hooks — code quality
178
+
179
+ - ruff for linting (pyflakes, pycodestyle, import sorting and pyupgrade
180
+ rules) and ruff for code formatting
181
+ - mypy type checker
182
+ - codespell for finding common misspellings
183
+ - conventional-precommit-linter for checking commit messages
184
+
185
+ The ruff, mypy and codespell settings live in `pyproject.toml`. Install the
186
+ hooks locally with `pre-commit install`; most hooks fix the problems they
187
+ find instead of only reporting them.
188
+
189
+ ## Generated files and linting
190
+
191
+ `src/bsasm/generated/` is machine output (ANTLR 4.13.2, pinned in
192
+ `pyproject.toml` and `regenerate.py`; keep the two in sync). It is excluded
193
+ from ruff, ruff format, the whitespace/EOF hooks and mypy error reporting
194
+ (per-module override in `pyproject.toml`) — do not edit or reformat it by
195
+ hand. All other sources are ruff-formatted (single quotes, 120 columns,
196
+ py311 target).
197
+
198
+ ## Behaviour compatibility contract
199
+
200
+ The rewrite is verified byte-identical against the original assembler (the
201
+ one that lived in ESP-IDF until the ANTLR rewrite) on the golden corpus.
202
+ Beyond that contract:
203
+
204
+ **Fixed bugs** (all clean errors now): `cfg trailing_bytes` above 8191 (was
205
+ a `struct.pack` crash); `l8`/`l16` beyond the LUT width (were silently
206
+ encoded as comparator inputs); 16-bit LUT values above 65535 (wrapped
207
+ around); jump targets past the program end (overflowed the 3-bit target
208
+ field into the counter-select bit); duplicate labels (silently
209
+ overwritten).
210
+
211
+ **Tightened error handling** (legal programs unaffected): misspelled
212
+ mnemonics like `ifx`/`loopax`/`addafoo`, dangling trailing commas, numeric
213
+ labels, two bundles on one line — all syntax errors now.
214
+
215
+ **Kept quirks** for parity: labels and cfg spellings are case-insensitive;
216
+ a bare `+a` operand resolves to input 32 relative; duplicate `write`/`read`
217
+ in one bundle keep the last value; the `Did you forget an L` hint message.
218
+
219
+ **Diagnostics**: 1-based line/column; exit code 2 on any error.