esp-bsasm 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.
- bsasm/__init__.py +47 -0
- bsasm/__main__.py +16 -0
- bsasm/builder.py +221 -0
- bsasm/cli.py +63 -0
- bsasm/encoder.py +217 -0
- bsasm/errors.py +47 -0
- bsasm/generated/BitScramblerLexer.py +361 -0
- bsasm/generated/BitScramblerListener.py +417 -0
- bsasm/generated/BitScramblerParser.py +2823 -0
- bsasm/generated/BitScramblerVisitor.py +238 -0
- bsasm/generated/__init__.py +9 -0
- bsasm/model.py +354 -0
- bsasm/parsing.py +122 -0
- bsasm/sema.py +523 -0
- esp_bsasm-0.1.0.dist-info/METADATA +254 -0
- esp_bsasm-0.1.0.dist-info/RECORD +20 -0
- esp_bsasm-0.1.0.dist-info/WHEEL +5 -0
- esp_bsasm-0.1.0.dist-info/entry_points.txt +2 -0
- esp_bsasm-0.1.0.dist-info/licenses/LICENSE +202 -0
- esp_bsasm-0.1.0.dist-info/top_level.txt +1 -0
bsasm/__init__.py
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: 2026 Espressif Systems (Shanghai) CO LTD
|
|
2
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
"""Public API of the BitScrambler assembler.
|
|
4
|
+
|
|
5
|
+
Typical use, mirroring what the CLI does::
|
|
6
|
+
|
|
7
|
+
import bsasm
|
|
8
|
+
|
|
9
|
+
program = bsasm.assemble(source_text, chipcfg)
|
|
10
|
+
binary = bsasm.encode(program)
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
__version__ = '0.1.0'
|
|
14
|
+
|
|
15
|
+
from bsasm.encoder import encode
|
|
16
|
+
from bsasm.errors import AssemblerError
|
|
17
|
+
from bsasm.errors import AssemblerSyntaxError
|
|
18
|
+
from bsasm.errors import Location
|
|
19
|
+
from bsasm.model import Chipcfg
|
|
20
|
+
from bsasm.model import Instruction
|
|
21
|
+
from bsasm.model import Program
|
|
22
|
+
from bsasm.model import ProgramMeta
|
|
23
|
+
from bsasm.parsing import parse
|
|
24
|
+
from bsasm.sema import DEFAULT_CHIPCFG
|
|
25
|
+
from bsasm.sema import analyze
|
|
26
|
+
|
|
27
|
+
__all__ = [
|
|
28
|
+
'DEFAULT_CHIPCFG',
|
|
29
|
+
'AssemblerError',
|
|
30
|
+
'AssemblerSyntaxError',
|
|
31
|
+
'Instruction',
|
|
32
|
+
'Location',
|
|
33
|
+
'Program',
|
|
34
|
+
'ProgramMeta',
|
|
35
|
+
'analyze',
|
|
36
|
+
'encode',
|
|
37
|
+
'parse',
|
|
38
|
+
]
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def assemble(source: str, chipcfg: Chipcfg | None = None) -> Program:
|
|
42
|
+
"""Parse and analyze bsasm ``source`` into a :class:`Program`.
|
|
43
|
+
|
|
44
|
+
Raises :class:`AssemblerSyntaxError` (a subclass of esp-pylib's
|
|
45
|
+
FatalError) for any problem in the source.
|
|
46
|
+
"""
|
|
47
|
+
return analyze(parse(source), chipcfg)
|
bsasm/__main__.py
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: 2026 Espressif Systems (Shanghai) CO LTD
|
|
2
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
"""Entry point for ``python -m bsasm``."""
|
|
4
|
+
|
|
5
|
+
from esp_pylib.errors import FatalError
|
|
6
|
+
from esp_pylib.excepthook import install_exception_reporting
|
|
7
|
+
from esp_pylib.logger import log
|
|
8
|
+
|
|
9
|
+
from bsasm.cli import main
|
|
10
|
+
|
|
11
|
+
if __name__ == '__main__':
|
|
12
|
+
install_exception_reporting()
|
|
13
|
+
try:
|
|
14
|
+
main()
|
|
15
|
+
except FatalError as e:
|
|
16
|
+
log.die(str(e), exit_code=2)
|
bsasm/builder.py
ADDED
|
@@ -0,0 +1,221 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: 2026 Espressif Systems (Shanghai) CO LTD
|
|
2
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
"""Parse tree to statement IR: the ANTLR visitor layer.
|
|
4
|
+
|
|
5
|
+
The grammar guarantees the *shape* of every statement; this module walks the
|
|
6
|
+
parse tree and records that shape as the statement dataclasses defined in
|
|
7
|
+
:mod:`bsasm.model`, without interpreting anything (no numeric parsing, no
|
|
8
|
+
label resolution). All interpretation lives in :mod:`bsasm.sema`.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from dataclasses import dataclass
|
|
12
|
+
|
|
13
|
+
from antlr4 import ParserRuleContext
|
|
14
|
+
from antlr4 import TerminalNode
|
|
15
|
+
|
|
16
|
+
from bsasm.errors import Location
|
|
17
|
+
from bsasm.generated.BitScramblerLexer import BitScramblerLexer
|
|
18
|
+
from bsasm.generated.BitScramblerParser import BitScramblerParser
|
|
19
|
+
from bsasm.generated.BitScramblerVisitor import BitScramblerVisitor
|
|
20
|
+
from bsasm.model import AddctiSub
|
|
21
|
+
from bsasm.model import AddSub
|
|
22
|
+
from bsasm.model import Atom
|
|
23
|
+
from bsasm.model import BundleStmt
|
|
24
|
+
from bsasm.model import CfgKey
|
|
25
|
+
from bsasm.model import CfgStmt
|
|
26
|
+
from bsasm.model import CounterSel
|
|
27
|
+
from bsasm.model import Halves
|
|
28
|
+
from bsasm.model import IfSub
|
|
29
|
+
from bsasm.model import JmpSub
|
|
30
|
+
from bsasm.model import LabelStmt
|
|
31
|
+
from bsasm.model import LdctdSub
|
|
32
|
+
from bsasm.model import LdctiSub
|
|
33
|
+
from bsasm.model import LoopSub
|
|
34
|
+
from bsasm.model import LutStmt
|
|
35
|
+
from bsasm.model import NopSub
|
|
36
|
+
from bsasm.model import SetSub
|
|
37
|
+
from bsasm.model import Statement
|
|
38
|
+
from bsasm.model import WidthSub
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
@dataclass(frozen=True, slots=True)
|
|
42
|
+
class _Mnemonic:
|
|
43
|
+
"""What the A/B/H/L letters baked into a mnemonic token stand for."""
|
|
44
|
+
|
|
45
|
+
counter: CounterSel
|
|
46
|
+
halves: Halves
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
# Mnemonic token type -> counter and written-back halves. The H/L suffixes
|
|
50
|
+
# select which bytes of the counter are written back; a bare mnemonic means
|
|
51
|
+
# both (h=1, l=1), see the ADD/LDCTD/LDCTI/ADDCTI opcode tables in the TRM.
|
|
52
|
+
_ADD_MNEMONICS: dict[int, _Mnemonic] = {
|
|
53
|
+
BitScramblerLexer.ADDA: _Mnemonic(CounterSel.A, Halves.FULL),
|
|
54
|
+
BitScramblerLexer.ADDAH: _Mnemonic(CounterSel.A, Halves.HIGH),
|
|
55
|
+
BitScramblerLexer.ADDAL: _Mnemonic(CounterSel.A, Halves.LOW),
|
|
56
|
+
BitScramblerLexer.ADDB: _Mnemonic(CounterSel.B, Halves.FULL),
|
|
57
|
+
BitScramblerLexer.ADDBH: _Mnemonic(CounterSel.B, Halves.HIGH),
|
|
58
|
+
BitScramblerLexer.ADDBL: _Mnemonic(CounterSel.B, Halves.LOW),
|
|
59
|
+
}
|
|
60
|
+
_LDCTD_MNEMONICS: dict[int, _Mnemonic] = {
|
|
61
|
+
BitScramblerLexer.LDCTDA: _Mnemonic(CounterSel.A, Halves.FULL),
|
|
62
|
+
BitScramblerLexer.LDCTDAH: _Mnemonic(CounterSel.A, Halves.HIGH),
|
|
63
|
+
BitScramblerLexer.LDCTDAL: _Mnemonic(CounterSel.A, Halves.LOW),
|
|
64
|
+
BitScramblerLexer.LDCTDB: _Mnemonic(CounterSel.B, Halves.FULL),
|
|
65
|
+
BitScramblerLexer.LDCTDBH: _Mnemonic(CounterSel.B, Halves.HIGH),
|
|
66
|
+
BitScramblerLexer.LDCTDBL: _Mnemonic(CounterSel.B, Halves.LOW),
|
|
67
|
+
}
|
|
68
|
+
_LDCTI_MNEMONICS: dict[int, _Mnemonic] = {
|
|
69
|
+
BitScramblerLexer.LDCTIA: _Mnemonic(CounterSel.A, Halves.FULL),
|
|
70
|
+
BitScramblerLexer.LDCTIAH: _Mnemonic(CounterSel.A, Halves.HIGH),
|
|
71
|
+
BitScramblerLexer.LDCTIAL: _Mnemonic(CounterSel.A, Halves.LOW),
|
|
72
|
+
BitScramblerLexer.LDCTIB: _Mnemonic(CounterSel.B, Halves.FULL),
|
|
73
|
+
BitScramblerLexer.LDCTIBH: _Mnemonic(CounterSel.B, Halves.HIGH),
|
|
74
|
+
BitScramblerLexer.LDCTIBL: _Mnemonic(CounterSel.B, Halves.LOW),
|
|
75
|
+
}
|
|
76
|
+
_ADDCTI_MNEMONICS: dict[int, _Mnemonic] = {
|
|
77
|
+
BitScramblerLexer.ADDCTIA: _Mnemonic(CounterSel.A, Halves.FULL),
|
|
78
|
+
BitScramblerLexer.ADDCTIAH: _Mnemonic(CounterSel.A, Halves.HIGH),
|
|
79
|
+
BitScramblerLexer.ADDCTIAL: _Mnemonic(CounterSel.A, Halves.LOW),
|
|
80
|
+
BitScramblerLexer.ADDCTIB: _Mnemonic(CounterSel.B, Halves.FULL),
|
|
81
|
+
BitScramblerLexer.ADDCTIBH: _Mnemonic(CounterSel.B, Halves.HIGH),
|
|
82
|
+
BitScramblerLexer.ADDCTIBL: _Mnemonic(CounterSel.B, Halves.LOW),
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _token_location(node: ParserRuleContext | TerminalNode) -> Location:
|
|
87
|
+
"""Location of a rule context or of a single terminal node."""
|
|
88
|
+
token = node.getSymbol() if hasattr(node, 'getSymbol') else node.start
|
|
89
|
+
return Location(token.line, token.column + 1, token.text)
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
class ProgramBuilder(BitScramblerVisitor):
|
|
93
|
+
"""Collects the parse tree into an ordered list of :data:`Statement`."""
|
|
94
|
+
|
|
95
|
+
def visitProgram(self, ctx: BitScramblerParser.ProgramContext) -> list[Statement]:
|
|
96
|
+
statements: list[Statement] = []
|
|
97
|
+
for line in ctx.line():
|
|
98
|
+
statements.extend(self.visit(line))
|
|
99
|
+
return statements
|
|
100
|
+
|
|
101
|
+
# Lines ----------------------------------------------------------------
|
|
102
|
+
|
|
103
|
+
def visitBlankLine(self, ctx: BitScramblerParser.BlankLineContext) -> list[Statement]: # noqa: ARG002
|
|
104
|
+
return []
|
|
105
|
+
|
|
106
|
+
def visitContentLine(self, ctx: BitScramblerParser.ContentLineContext) -> list[Statement]:
|
|
107
|
+
# labelDef* lineContent? labelDef*: children are in document order,
|
|
108
|
+
# so a plain walk reproduces the source order exactly.
|
|
109
|
+
statements: list[Statement] = []
|
|
110
|
+
for child in ctx.children:
|
|
111
|
+
if isinstance(child, BitScramblerParser.LabelDefContext):
|
|
112
|
+
name = child.LABEL().getText()[:-1] # drop the colon
|
|
113
|
+
statements.append(LabelStmt(name, _token_location(child)))
|
|
114
|
+
else:
|
|
115
|
+
statements.append(self.visit(child))
|
|
116
|
+
return statements
|
|
117
|
+
|
|
118
|
+
# Meta statements ------------------------------------------------------
|
|
119
|
+
|
|
120
|
+
def visitCfgStmt(self, ctx: BitScramblerParser.CfgStmtContext) -> CfgStmt:
|
|
121
|
+
# ctx is the CfgStmtContext itself; the grammar guarantees exactly
|
|
122
|
+
# one of the alternatives. Matching on the token accessors instead
|
|
123
|
+
# of a silent fallback means a newly added cfg key whose case is
|
|
124
|
+
# forgotten here fails loudly instead of parsing as lut_width_bits.
|
|
125
|
+
value: ParserRuleContext
|
|
126
|
+
if ctx.K_PREFETCH():
|
|
127
|
+
key, value = CfgKey.PREFETCH, ctx.cfgBoolean()
|
|
128
|
+
elif ctx.K_TRAILING_BYTES():
|
|
129
|
+
key, value = CfgKey.TRAILING_BYTES, ctx.NUMBER()
|
|
130
|
+
elif ctx.K_EOF_ON():
|
|
131
|
+
key, value = CfgKey.EOF_ON, (ctx.K_UPSTREAM() or ctx.K_DOWNSTREAM())
|
|
132
|
+
elif ctx.K_LUT_WIDTH_BITS():
|
|
133
|
+
key, value = CfgKey.LUT_WIDTH_BITS, ctx.NUMBER()
|
|
134
|
+
elif ctx.K_LOOP_ENDS_ON():
|
|
135
|
+
key, value = CfgKey.LOOP_ENDS_ON, (ctx.K_EQUAL() or ctx.K_EQUAL_OR_GREATER())
|
|
136
|
+
else:
|
|
137
|
+
raise AssertionError(f'Unknown cfg statement at {_token_location(ctx)}')
|
|
138
|
+
return CfgStmt(key, Atom(value.getText(), _token_location(value)), _token_location(ctx))
|
|
139
|
+
|
|
140
|
+
def visitLutStmt(self, ctx: BitScramblerParser.LutStmtContext) -> LutStmt:
|
|
141
|
+
values = tuple(Atom(v.getText(), _token_location(v)) for v in ctx.lutValue())
|
|
142
|
+
return LutStmt(values, _token_location(ctx))
|
|
143
|
+
|
|
144
|
+
# Bundles and sub-instructions ------------------------------------------
|
|
145
|
+
|
|
146
|
+
def visitBundle(self, ctx: BitScramblerParser.BundleContext) -> BundleStmt:
|
|
147
|
+
subs = tuple(self.visit(sub) for sub in ctx.subInstr())
|
|
148
|
+
return BundleStmt(subs, subs[0].location)
|
|
149
|
+
|
|
150
|
+
def visitSubSet(self, ctx: BitScramblerParser.SubSetContext) -> SetSub:
|
|
151
|
+
inst = ctx.setInstr()
|
|
152
|
+
out_numbers = inst.outSpec().NUMBER()
|
|
153
|
+
in_bits = inst.inSpec().sourceBit()
|
|
154
|
+
return SetSub(
|
|
155
|
+
out_start=self._atom(out_numbers[0]),
|
|
156
|
+
out_end=self._atom(out_numbers[1]) if len(out_numbers) > 1 else None,
|
|
157
|
+
in_start=self._atom(in_bits[0]),
|
|
158
|
+
in_end=self._atom(in_bits[1]) if len(in_bits) > 1 else None,
|
|
159
|
+
location=_token_location(inst),
|
|
160
|
+
)
|
|
161
|
+
|
|
162
|
+
def visitSubWrite(self, ctx: BitScramblerParser.SubWriteContext) -> WidthSub:
|
|
163
|
+
inst = ctx.writeInstr()
|
|
164
|
+
return WidthSub(self._atom(inst.NUMBER()), is_read=False, location=_token_location(inst))
|
|
165
|
+
|
|
166
|
+
def visitSubRead(self, ctx: BitScramblerParser.SubReadContext) -> WidthSub:
|
|
167
|
+
inst = ctx.readInstr()
|
|
168
|
+
return WidthSub(self._atom(inst.NUMBER()), is_read=True, location=_token_location(inst))
|
|
169
|
+
|
|
170
|
+
def visitSubLoop(self, ctx: BitScramblerParser.SubLoopContext) -> LoopSub:
|
|
171
|
+
inst = ctx.loopInstr()
|
|
172
|
+
numbers = inst.NUMBER()
|
|
173
|
+
return LoopSub(
|
|
174
|
+
counter=CounterSel.A if inst.LOOPA() else CounterSel.B,
|
|
175
|
+
end_val=self._atom(numbers[0]),
|
|
176
|
+
ctr_add=self._atom(numbers[1]),
|
|
177
|
+
target=self._atom(inst.labelRef().identifier()),
|
|
178
|
+
location=_token_location(inst),
|
|
179
|
+
)
|
|
180
|
+
|
|
181
|
+
def visitSubAdd(self, ctx: BitScramblerParser.SubAddContext) -> AddSub:
|
|
182
|
+
inst = ctx.addInstr()
|
|
183
|
+
mnemonic = _ADD_MNEMONICS[inst.addMnemonic().start.type]
|
|
184
|
+
return AddSub(mnemonic.counter, mnemonic.halves, self._atom(inst.NUMBER()), _token_location(inst))
|
|
185
|
+
|
|
186
|
+
def visitSubIf(self, ctx: BitScramblerParser.SubIfContext) -> IfSub:
|
|
187
|
+
inst = ctx.ifInstr()
|
|
188
|
+
return IfSub(
|
|
189
|
+
negated=bool(inst.IFN()),
|
|
190
|
+
cond=self._atom(inst.condSource().sourceBit()),
|
|
191
|
+
target=self._atom(inst.labelRef().identifier()),
|
|
192
|
+
location=_token_location(inst),
|
|
193
|
+
)
|
|
194
|
+
|
|
195
|
+
def visitSubLdctd(self, ctx: BitScramblerParser.SubLdctdContext) -> LdctdSub:
|
|
196
|
+
inst = ctx.ldctdInstr()
|
|
197
|
+
mnemonic = _LDCTD_MNEMONICS[inst.ldctdMnemonic().start.type]
|
|
198
|
+
return LdctdSub(mnemonic.counter, mnemonic.halves, self._atom(inst.NUMBER()), _token_location(inst))
|
|
199
|
+
|
|
200
|
+
def visitSubLdcti(self, ctx: BitScramblerParser.SubLdctiContext) -> LdctiSub:
|
|
201
|
+
inst = ctx.ldctiInstr()
|
|
202
|
+
mnemonic = _LDCTI_MNEMONICS[inst.ldctiMnemonic().start.type]
|
|
203
|
+
return LdctiSub(mnemonic.counter, mnemonic.halves, _token_location(inst))
|
|
204
|
+
|
|
205
|
+
def visitSubAddcti(self, ctx: BitScramblerParser.SubAddctiContext) -> AddctiSub:
|
|
206
|
+
inst = ctx.addctiInstr()
|
|
207
|
+
mnemonic = _ADDCTI_MNEMONICS[inst.addctiMnemonic().start.type]
|
|
208
|
+
return AddctiSub(mnemonic.counter, mnemonic.halves, _token_location(inst))
|
|
209
|
+
|
|
210
|
+
def visitSubJmp(self, ctx: BitScramblerParser.SubJmpContext) -> JmpSub:
|
|
211
|
+
inst = ctx.jmpInstr()
|
|
212
|
+
return JmpSub(self._atom(inst.labelRef().identifier()), _token_location(inst))
|
|
213
|
+
|
|
214
|
+
def visitSubNop(self, ctx: BitScramblerParser.SubNopContext) -> NopSub:
|
|
215
|
+
return NopSub(_token_location(ctx.nopInstr()))
|
|
216
|
+
|
|
217
|
+
# Helpers --------------------------------------------------------------
|
|
218
|
+
|
|
219
|
+
@staticmethod
|
|
220
|
+
def _atom(ctx: ParserRuleContext) -> Atom:
|
|
221
|
+
return Atom(ctx.getText(), _token_location(ctx))
|
bsasm/cli.py
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: 2026 Espressif Systems (Shanghai) CO LTD
|
|
2
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
"""Command line interface of the BitScrambler assembler."""
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import re
|
|
7
|
+
|
|
8
|
+
import rich_click as click
|
|
9
|
+
from esp_pylib.logger import log
|
|
10
|
+
|
|
11
|
+
from bsasm.encoder import encode
|
|
12
|
+
from bsasm.errors import AssemblerError
|
|
13
|
+
from bsasm.model import Chipcfg
|
|
14
|
+
from bsasm.parsing import parse
|
|
15
|
+
from bsasm.sema import analyze
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def read_file(filename: str) -> str:
|
|
19
|
+
try:
|
|
20
|
+
with open(filename) as f:
|
|
21
|
+
return f.read()
|
|
22
|
+
except OSError as e:
|
|
23
|
+
# Raise the tool error instead of SystemExit: the exception hook
|
|
24
|
+
# filters SystemExit, so the IDE error handler would never see it.
|
|
25
|
+
raise AssemblerError(f'Error opening {filename}: {e}') from e
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def write_file(filename: str, data: bytes) -> None:
|
|
29
|
+
with open(filename, 'wb') as f:
|
|
30
|
+
f.write(data)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
@click.command(
|
|
34
|
+
context_settings={'help_option_names': ['-h', '--help']},
|
|
35
|
+
help='BitScrambler program assembler',
|
|
36
|
+
)
|
|
37
|
+
@click.argument('infile', type=click.Path(exists=True, dir_okay=False))
|
|
38
|
+
@click.argument('outfile', required=False)
|
|
39
|
+
@click.option(
|
|
40
|
+
'-c',
|
|
41
|
+
'chipcfg_path',
|
|
42
|
+
type=click.Path(exists=True, dir_okay=False),
|
|
43
|
+
help=('Set chip capabilities json file; if set, returns an error when an unsupported instruction is assembled'),
|
|
44
|
+
)
|
|
45
|
+
def main(infile: str, outfile: str | None, chipcfg_path: str | None) -> None:
|
|
46
|
+
chipcfg: Chipcfg
|
|
47
|
+
if chipcfg_path is not None:
|
|
48
|
+
try:
|
|
49
|
+
with open(chipcfg_path) as chipcfg_json:
|
|
50
|
+
chipcfg = json.load(chipcfg_json)
|
|
51
|
+
except json.JSONDecodeError as e:
|
|
52
|
+
raise AssemblerError(f'Invalid chip capabilities json {chipcfg_path}: {e}') from e
|
|
53
|
+
else:
|
|
54
|
+
chipcfg = {'chipname': 'chip', 'extra_instruction_groups': [], 'support_all': True}
|
|
55
|
+
|
|
56
|
+
if outfile is None:
|
|
57
|
+
# Same default output name as the original assembler: replace the
|
|
58
|
+
# first '.bsasm'-ish stretch of the input name with '.bsbin'.
|
|
59
|
+
outfile = re.sub('.bsasm', '', infile) + '.bsbin'
|
|
60
|
+
asm = read_file(infile)
|
|
61
|
+
program = analyze(parse(asm), chipcfg)
|
|
62
|
+
write_file(outfile, encode(program))
|
|
63
|
+
log.print(f'Written {len(program.insts)} instructions and {len(program.lut)} 32-bit words of LUT.')
|
bsasm/encoder.py
ADDED
|
@@ -0,0 +1,217 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: 2026 Espressif Systems (Shanghai) CO LTD
|
|
2
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
"""Encode a :class:`~bsasm.model.Program` into the .bsbin binary format.
|
|
4
|
+
|
|
5
|
+
The on-disk format is:
|
|
6
|
+
header (12 bytes = 3 32-bit words, self-describing length)
|
|
7
|
+
instructions (36 bytes each, 257 bits used)
|
|
8
|
+
LUT data (32-bit little-endian words)
|
|
9
|
+
|
|
10
|
+
The bit packing is byte-for-byte identical to the original assembler: bits
|
|
11
|
+
are appended to the stream one by one, LSB-first per field, filling each
|
|
12
|
+
byte from its most significant bit down.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
import struct
|
|
16
|
+
|
|
17
|
+
from bsasm.errors import AssemblerError
|
|
18
|
+
from bsasm.model import CounterSel
|
|
19
|
+
from bsasm.model import Halves
|
|
20
|
+
from bsasm.model import Instruction
|
|
21
|
+
from bsasm.model import LutWidth
|
|
22
|
+
from bsasm.model import MuxSource
|
|
23
|
+
from bsasm.model import Opcode
|
|
24
|
+
from bsasm.model import OpcodeKind
|
|
25
|
+
from bsasm.model import Program
|
|
26
|
+
from bsasm.model import check_sources_compatible
|
|
27
|
+
|
|
28
|
+
# If we have multiple BitScrambler versions, this'll indicate what hardware
|
|
29
|
+
# we're expecting to run on. Increase BITSCRAMBLER_BINARY_VER if the on-disk
|
|
30
|
+
# format ever changes incompatibly.
|
|
31
|
+
BITSCRAMBLER_BINARY_VER = 1
|
|
32
|
+
BITSCRAMBLER_HW_REV = 0
|
|
33
|
+
|
|
34
|
+
HEADER_FMT = '<BBBBHBBHBB'
|
|
35
|
+
HEADER_LEN_WORDS = 3
|
|
36
|
+
INSTRUCTION_BITS = 257
|
|
37
|
+
INSTRUCTION_PAD_BITS = 31 # pad to 36 bytes = 9 32-bit words
|
|
38
|
+
MAX_INSTS = 8
|
|
39
|
+
|
|
40
|
+
# Opcode base patterns (bits 16 upward), see the TRM opcode table.
|
|
41
|
+
_OP_BASES = {
|
|
42
|
+
OpcodeKind.ADD: 0x0000000,
|
|
43
|
+
OpcodeKind.IF: 0x0010000,
|
|
44
|
+
OpcodeKind.IFN: 0x0020000,
|
|
45
|
+
OpcodeKind.LDCTD: 0x0030000,
|
|
46
|
+
OpcodeKind.LDCTI: 0x0040000,
|
|
47
|
+
OpcodeKind.ADDCTI: 0x0050000,
|
|
48
|
+
OpcodeKind.LOOP: 0x2000000,
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
# Pseudo-slot in the mux map holding the IF/IFN condition source; its value
|
|
52
|
+
# goes into the opcode's src field instead of a CTL_MUX_SEL field.
|
|
53
|
+
_COND_SLOT = 32
|
|
54
|
+
|
|
55
|
+
# Mux inputs that the program never routes default to the fixed-low source.
|
|
56
|
+
_DEFAULT_LOW_INPUT = 94 # the 'l' input
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
class _BitWriter:
|
|
60
|
+
"""Appends bit fields to a stream, MSB-of-byte first.
|
|
61
|
+
|
|
62
|
+
Deliberately naive (bit by bit): the original assembler worked the same
|
|
63
|
+
way and the resulting byte order is what the hardware loader expects.
|
|
64
|
+
"""
|
|
65
|
+
|
|
66
|
+
def __init__(self) -> None:
|
|
67
|
+
self._data = bytearray()
|
|
68
|
+
self._cur = 0
|
|
69
|
+
self._pos = 0
|
|
70
|
+
|
|
71
|
+
def add_bits(self, value: int, bits: int) -> None:
|
|
72
|
+
v = value
|
|
73
|
+
for _ in range(bits):
|
|
74
|
+
self._cur >>= 1
|
|
75
|
+
if v & 1:
|
|
76
|
+
self._cur |= 0x80
|
|
77
|
+
v >>= 1
|
|
78
|
+
self._pos += 1
|
|
79
|
+
if self._pos == 8:
|
|
80
|
+
self._data.append(self._cur)
|
|
81
|
+
self._cur = 0
|
|
82
|
+
self._pos = 0
|
|
83
|
+
|
|
84
|
+
def size(self) -> int:
|
|
85
|
+
"""Size of the stream so far, in bits."""
|
|
86
|
+
return len(self._data) * 8 + self._pos
|
|
87
|
+
|
|
88
|
+
def to_bytes(self) -> bytes:
|
|
89
|
+
return bytes(self._data)
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def encode(program: Program) -> bytes:
|
|
93
|
+
"""Serialize a fully analyzed program into .bsbin bytes."""
|
|
94
|
+
insts = program.insts
|
|
95
|
+
if len(insts) > MAX_INSTS:
|
|
96
|
+
raise AssemblerError('Program has more than eight instructions.')
|
|
97
|
+
|
|
98
|
+
out = bytearray()
|
|
99
|
+
lut_words = _reformat_lut(program.lut, program.meta.lut_width)
|
|
100
|
+
|
|
101
|
+
out += struct.pack(
|
|
102
|
+
HEADER_FMT,
|
|
103
|
+
BITSCRAMBLER_BINARY_VER, # byte: binary format version
|
|
104
|
+
BITSCRAMBLER_HW_REV, # byte: expected hardware revision
|
|
105
|
+
HEADER_LEN_WORDS, # byte: header length in 32-bit words
|
|
106
|
+
len(insts), # byte: instruction count
|
|
107
|
+
len(lut_words), # short: LUT length in 32-bit words
|
|
108
|
+
program.meta.lut_width.encoding, # byte: LUT width setting
|
|
109
|
+
int(program.meta.prefetch), # byte: prefetch enabled/disabled
|
|
110
|
+
program.meta.trailing_bytes * 8, # short: trailing *bits* after EOF
|
|
111
|
+
program.meta.eof_on.value, # byte: eof_on
|
|
112
|
+
int(program.meta.loop_ends_on), # byte: LOOP end condition
|
|
113
|
+
)
|
|
114
|
+
|
|
115
|
+
for inst in insts:
|
|
116
|
+
out += _encode_inst(inst)
|
|
117
|
+
|
|
118
|
+
for word in lut_words:
|
|
119
|
+
out += struct.pack('<I', word & 0xFFFFFFFF)
|
|
120
|
+
|
|
121
|
+
return bytes(out)
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def _reformat_lut(lut: tuple[int, ...], lut_width: LutWidth) -> list[int]:
|
|
125
|
+
"""Pack LUT values into 32-bit words for the configured width."""
|
|
126
|
+
values = list(lut)
|
|
127
|
+
if lut_width == LutWidth.BITS8:
|
|
128
|
+
values.extend([0] * (-len(values) % 4))
|
|
129
|
+
return [
|
|
130
|
+
(values[i] & 255) | (values[i + 1] & 255) << 8 | (values[i + 2] & 255) << 16 | (values[i + 3] & 255) << 24
|
|
131
|
+
for i in range(0, len(values), 4)
|
|
132
|
+
]
|
|
133
|
+
if lut_width == LutWidth.BITS16:
|
|
134
|
+
values.extend([0] * (-len(values) % 2))
|
|
135
|
+
return [(values[i] & 65535) | (values[i + 1] & 65535) << 16 for i in range(0, len(values), 2)]
|
|
136
|
+
return values
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def _encode_inst(inst: Instruction) -> bytes:
|
|
140
|
+
bits = _BitWriter()
|
|
141
|
+
|
|
142
|
+
mux = dict(inst.mux)
|
|
143
|
+
op = inst.op
|
|
144
|
+
if op is None:
|
|
145
|
+
# An instruction without an opcode defaults to NOP, which is ADDA 0
|
|
146
|
+
# with both counter halves written back.
|
|
147
|
+
op = Opcode(kind=OpcodeKind.ADD, location=inst.location, counter=CounterSel.A, halves=Halves.FULL, value=0)
|
|
148
|
+
if op.cond_source is not None:
|
|
149
|
+
mux[_COND_SLOT] = op.cond_source
|
|
150
|
+
|
|
151
|
+
# Instruction-wide control bits: every routed source may require
|
|
152
|
+
# specific values; sources must agree pairwise, which is checked here
|
|
153
|
+
# over all routed inputs exactly like in the original assembler so the
|
|
154
|
+
# conflict diagnostics point at the same two operands.
|
|
155
|
+
# One loop over all 33 slots, exactly like in the original assembler:
|
|
156
|
+
# each routed slot's 7-bit selection goes at its own position in the
|
|
157
|
+
# stream; unrouted ones encode the fixed-low source.
|
|
158
|
+
flags = {'rel_addr': 0, 'ctrsel': 0, 'lutsel': 0}
|
|
159
|
+
for i in range(_COND_SLOT + 1):
|
|
160
|
+
if i not in mux:
|
|
161
|
+
if i < _COND_SLOT:
|
|
162
|
+
# Unrouted mux inputs select the fixed-low source.
|
|
163
|
+
bits.add_bits(_DEFAULT_LOW_INPUT, 7)
|
|
164
|
+
continue
|
|
165
|
+
# Checking each input against each following one reports exactly
|
|
166
|
+
# which two operands clash.
|
|
167
|
+
for j in range(i + 1, _COND_SLOT + 1):
|
|
168
|
+
if j in mux:
|
|
169
|
+
message = check_sources_compatible(mux[i], mux[j])
|
|
170
|
+
if message:
|
|
171
|
+
raise AssemblerError(_conflict_message(mux[i], mux[j], message))
|
|
172
|
+
src = mux[i]
|
|
173
|
+
if src.rel_addr is not None:
|
|
174
|
+
flags['rel_addr'] = int(src.rel_addr)
|
|
175
|
+
if src.ctrsel is not None:
|
|
176
|
+
flags['ctrsel'] = src.ctrsel
|
|
177
|
+
if src.lutsel is not None:
|
|
178
|
+
flags['lutsel'] = src.lutsel
|
|
179
|
+
if i < _COND_SLOT:
|
|
180
|
+
bits.add_bits(src.index, 7)
|
|
181
|
+
|
|
182
|
+
# Opcode field, 26 bits: bit 25 LOOP flag, 24 counter, 23/22 halves,
|
|
183
|
+
# 21..23 target, 16..20 sub-opcode, 0..15 immediate / 0..6 IF source.
|
|
184
|
+
opcode = _OP_BASES[op.kind]
|
|
185
|
+
if op.counter is CounterSel.B:
|
|
186
|
+
opcode |= 1 << 24
|
|
187
|
+
if op.halves is not None and op.halves != Halves.LOW:
|
|
188
|
+
opcode |= 1 << 23 # h
|
|
189
|
+
if op.halves is not None and op.halves != Halves.HIGH:
|
|
190
|
+
opcode |= 1 << 22 # l
|
|
191
|
+
if op.target_ip is not None:
|
|
192
|
+
opcode |= op.target_ip << 21
|
|
193
|
+
if op.kind == OpcodeKind.LOOP:
|
|
194
|
+
opcode |= (op.value or 0) << 5
|
|
195
|
+
opcode |= (op.ctr_add or 0) & 31
|
|
196
|
+
elif op.value is not None:
|
|
197
|
+
opcode |= op.value & 0xFFFF
|
|
198
|
+
if op.cond_source is not None:
|
|
199
|
+
opcode |= op.cond_source.index & 0x7F
|
|
200
|
+
bits.add_bits(opcode, 26)
|
|
201
|
+
|
|
202
|
+
bits.add_bits(inst.read.encoding, 2)
|
|
203
|
+
bits.add_bits(inst.write.encoding, 2)
|
|
204
|
+
bits.add_bits(flags['rel_addr'], 1)
|
|
205
|
+
bits.add_bits(flags['ctrsel'], 1)
|
|
206
|
+
bits.add_bits(flags['lutsel'], 1)
|
|
207
|
+
|
|
208
|
+
if bits.size() != INSTRUCTION_BITS:
|
|
209
|
+
raise AssemblerError(f'Internal error: instruction size is {bits.size()}!')
|
|
210
|
+
bits.add_bits(0, INSTRUCTION_PAD_BITS)
|
|
211
|
+
return bits.to_bytes()
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
def _conflict_message(first: MuxSource, second: MuxSource, message: str) -> str:
|
|
215
|
+
first_at = f'{first.location.describe()}: "{first.text}"'
|
|
216
|
+
second_at = f'{second.location.describe()}: "{second.text}"'
|
|
217
|
+
return f'{first_at} and {second_at}: {message}'
|
bsasm/errors.py
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: 2026 Espressif Systems (Shanghai) CO LTD
|
|
2
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
"""Error types and source locations for the BitScrambler assembler."""
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
|
|
7
|
+
from esp_pylib.errors import FatalError
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
@dataclass(frozen=True, slots=True)
|
|
11
|
+
class Location:
|
|
12
|
+
"""A position in the source file.
|
|
13
|
+
|
|
14
|
+
Lines and columns are counted from one, as users of other assemblers
|
|
15
|
+
expect. ``text`` is the token or sub-instruction the location points at,
|
|
16
|
+
ready to be quoted in diagnostics.
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
line: int
|
|
20
|
+
column: int
|
|
21
|
+
text: str = ''
|
|
22
|
+
|
|
23
|
+
def describe(self) -> str:
|
|
24
|
+
return f'line {self.line} column {self.column}'
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class AssemblerError(FatalError):
|
|
28
|
+
"""Base class for every diagnostic the assembler reports."""
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class AssemblerSyntaxError(AssemblerError):
|
|
32
|
+
"""Raised for lexical, syntactic and semantic problems in the source.
|
|
33
|
+
|
|
34
|
+
``first`` and ``second`` point at the offending source location(s); some
|
|
35
|
+
checks (like two incompatible mux inputs) naturally involve two places
|
|
36
|
+
and report both.
|
|
37
|
+
"""
|
|
38
|
+
|
|
39
|
+
def __init__(self, first: Location, message: str, second: Location | None = None) -> None:
|
|
40
|
+
if second is None:
|
|
41
|
+
msg = f'{first.describe()}: "{first.text}": {message}'
|
|
42
|
+
else:
|
|
43
|
+
msg = f'{first.describe()}: "{first.text}" and {second.describe()}: "{second.text}": {message}'
|
|
44
|
+
super().__init__(msg)
|
|
45
|
+
self.first = first
|
|
46
|
+
self.second = second
|
|
47
|
+
self.message = message
|