File size: 41,267 Bytes
d086025
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
# adafruit/adafruit_circuitpython_pioasm

## Project Overview

adafruit_circuitpython_pioasm is a small, pure-Python CircuitPython library that provides a simple assembler for converting Raspberry Pi PIO ('pioasm') assembly text into the encoded instruction bytes a PIO state machine can execute. It exists so CircuitPython users can write PIO programs for the RP2040 and RP2350 microcontrollers directly on-device or in Python, rather than invoking the C SDK's pioasm tool, and it pairs closely with the CircuitPython rp2pio module, which loads assembled programs into state machines. The project's scope is narrowly focused: it parses and assembles PIO assembly source text; it does not manage pins, clocks, DMA, or state machine runtime behavior itself. Its primary functionality is the Program class, which takes a text program, strips comments, processes assembler directives such as .program, .side_set, .wrap, .wrap_target, .pio_version, FIFO-type selection, and mov-status configuration, resolves labels (including publicly declared ones used by drivers like adafruit_pio's fifoutils), and emits the binary instruction words as an array of bytes, along with a pio_kwargs dictionary of settings ready to pass to a rp2pio.StateMachine constructor. A convenience assemble() function returns just the assembled bytes. Assembly is table-driven: constant lookup tables map mnemonics and condition codes (jmp conditions, in sources, out destinations, wait sources, mov sources/destinations/operations, set destinations) onto their encoded bit fields, with support for PIO version 0 and newer version 1 instructions and FIFO modes, and meaningful error messages for invalid syntax. The repository is structured as a standard Adafruit CircuitPython library: a single-module implementation in adafruit_pioasm.py, a docs/ directory with Sphinx documentation for Read the Docs, examples/ scripts such as a squarewave demo showing assembly and use with rp2pio, a tests/ suite covering assembly output, and tools/ for repo maintenance. Written originally by Scott Shawcroft for Adafruit Industries and MIT licensed, the library is distributed on PyPI as adafruit-circuitpython-pioasm and included in the Adafruit CircuitPython library bundle, serving as the foundation for higher-level CircuitPython drivers that rely on custom PIO programs.

Re-implement this repository from scratch so that the original test suite passes. The sections below document the language/environment, the project structure, the public API the tests exercise, and per-capability implementation guidance.

## Submission Constraints (read carefully — the evaluation depends on these)

This is a **closed-book** task. The graded test suite is **hidden** and will be
injected into the workspace at evaluation time. To be scored correctly you MUST
follow these rules:

1. **Do NOT create or modify any files under the test directories** (e.g.
   `tests/`, `test/`, `testing/`, or files named `test_*.py` / `conftest.py`).
   The grader injects its own test files at those paths; any file you place
   there will collide with the injected suite and cause the whole evaluation to
   score 0. Implement **only** the library/source code — never the tests.

2. **Your package MUST be importable by the name the tests use.** The hidden
   tests `import` your package by its documented top-level name (see the
   Project Directory Structure and API Usage Guide below). Provide a valid
   `pyproject.toml` / `setup.py` / `setup.cfg` and lay out your modules so that
   `pip install -e .` succeeds and the package imports cleanly. If your package
   is not installable/importable, every test errors out and the reward is 0.

3. **Match the documented module paths and public API exactly** (names,
   signatures, and any literal error/exception strings). Internal helpers not
   listed in the API guide may be implemented however you like.

## Install / Reconstruction Contract

Follow this contract before implementing the documented APIs:
- **Project root**: `/workspace/repo` at runtime; the submitted repository root is `.`.
- **Package/distribution name**: `adafruit-circuitpython-pioasm`
- **Package roots**: `.`
- **Install strategy**: `editable-install`
- **Import/entry**: use the package and public entry points listed in the API Usage Guide; do not invent a different top-level package.
- **Provision commands**:
  ```bash
  python3 -I -c 'import base64; from pathlib import Path; Path('"'"'/tmp/programgen-pip-compat-v1.py'"'"').write_bytes(base64.b64decode('"'"'aW1wb3J0IHN1YnByb2Nlc3MKaW1wb3J0IHN5cwoKZGVmIGluc3RhbGwoY29tbWFuZCwgcnVuPXN1YnByb2Nlc3MucnVuKToKICAgIHJlc3VsdCA9IHJ1bihjb21tYW5kLCBzdGRvdXQ9c3VicHJvY2Vzcy5QSVBFLCBzdGRlcnI9c3VicHJvY2Vzcy5TVERPVVQsIHRleHQ9VHJ1ZSkKICAgIG91dHB1dCA9IHJlc3VsdC5zdGRvdXQgb3IgJycKICAgIHN5cy5zdGRvdXQud3JpdGUob3V0cHV0KQogICAgc3lzLnN0ZG91dC5mbHVzaCgpCiAgICBpZiByZXN1bHQucmV0dXJuY29kZSA9PSAwOgogICAgICAgIHJldHVybiAwCiAgICBsZWdhY3kgPSAnaW52YWxpZCBtZXRhZGF0YScgaW4gb3V0cHV0Lmxvd2VyKCkgYW5kICdwbGVhc2UgdXNlIHBpcDwyNC4xJyBpbiBvdXRwdXQubG93ZXIoKQogICAgaWYgbm90IGxlZ2FjeSBvciBub3QgKDMsIDgpIDw9IHN5cy52ZXJzaW9uX2luZm9bOjJdIDw9ICgzLCAxMik6CiAgICAgICAgcmV0dXJuIHJlc3VsdC5yZXR1cm5jb2RlCiAgICBwcmludCgnW3Byb2dyYW1nZW5dIGxlZ2FjeSBkaXN0cmlidXRpb24gbWV0YWRhdGE6IHJldHJ5aW5nIHRoZSB1bmNoYW5nZWQgcmVxdWlyZW1lbnRzIHdpdGggcGlwPDI0LjEnLCBmbHVzaD1UcnVlKQogICAgY2hhbmdlZCA9IHJ1bihbc3lzLmV4ZWN1dGFibGUsICctbScsICdwaXAnLCAnaW5zdGFsbCcsICdwaXA8MjQuMSddKQogICAgaWYgY2hhbmdlZC5yZXR1cm5jb2RlOgogICAgICAgIHJldHVybiBjaGFuZ2VkLnJldHVybmNvZGUKICAgIHJldHVybiBydW4oY29tbWFuZCkucmV0dXJuY29kZQoKaWYgX19uYW1lX18gPT0gJ19fbWFpbl9fJzoKICAgIHJhaXNlIFN5c3RlbUV4aXQoaW5zdGFsbChzeXMuYXJndlsxOl0pKQo='"'"'))'
programgen_pip_install() { python3 -I /tmp/programgen-pip-compat-v1.py "$@"; }
export -f programgen_pip_install
  programgen_pip_install python3 -m pip install -U pip 'setuptools<82' wheel
  programgen_pip_install python3 -m pip install setuptools wheel setuptools-scm
  (
programgen_install_report="$(mktemp)"
trap 'rm -f "$programgen_install_report"' EXIT
SETUPTOOLS_SCM_PRETEND_VERSION=0.0.0 PDM_BUILD_SCM_VERSION=0.0.0 POETRY_DYNAMIC_VERSIONING_BYPASS=0.0.0 UV_DYNAMIC_VERSIONING_BYPASS=0.0.0 programgen_pip_install python3 -m pip install -e . --no-build-isolation --no-deps --report "$programgen_install_report"
python3 -c 'import json,subprocess,sys; report=json.load(open(sys.argv[1], encoding='"'"'utf-8'"'"')); requirements=list(dict.fromkeys(requirement for item in report.get('"'"'install'"'"', []) for requirement in item.get('"'"'metadata'"'"', {}).get('"'"'requires_dist'"'"', []))); subprocess.run([sys.executable, '"'"'-I'"'"', '"'"'/tmp/programgen-pip-compat-v1.py'"'"', sys.executable, '"'"'-m'"'"', '"'"'pip'"'"', '"'"'install'"'"', *requirements], check=True) if requirements else None' "$programgen_install_report"
)
  ```
- **Runtime setup**:
  ```bash
  {
    [ -e "$PWD"/README.rst ] || { mkdir -p "$(dirname "$PWD"/README.rst)"; : > "$PWD"/README.rst; };
    SETUPTOOLS_SCM_PRETEND_VERSION=0.0.0 PDM_BUILD_SCM_VERSION=0.0.0 POETRY_DYNAMIC_VERSIONING_BYPASS=0.0.0 UV_DYNAMIC_VERSIONING_BYPASS=0.0.0 SETUPTOOLS_SCM_WRITE_TO_SOURCE=1 python3 -m pip install -e "$PWD" --no-build-isolation --no-deps;
  }
  ```
- **Project root for installation**: `.`
- **Build-version environment**: `SETUPTOOLS_SCM_PRETEND_VERSION=0.0.0`, `PDM_BUILD_SCM_VERSION=0.0.0`, `POETRY_DYNAMIC_VERSIONING_BYPASS=0.0.0`, `UV_DYNAMIC_VERSIONING_BYPASS=0.0.0`
- **Test directory**: `examples`, `tests`
- **Test command**: `bash -lc 'set -uo pipefail
run=(python3 -m pytest -vv -o addopts= tests/test_all.py tests/test_in.py tests/test_label.py tests/test_misc.py tests/test_mov.py tests/test_nop.py tests/test_out.py tests/test_print_c_program.py tests/test_pseudo.py tests/test_radix.py tests/test_version.py tests/test_wrap.py)
if [ -n "${COVERAGE_FILE:-}" ]; then run=(python3 -m coverage run --source=. -m pytest -vv -o addopts= tests/test_all.py tests/test_in.py tests/test_label.py tests/test_misc.py tests/test_mov.py tests/test_nop.py tests/test_out.py tests/test_print_c_program.py tests/test_pseudo.py tests/test_radix.py tests/test_version.py tests/test_wrap.py); fi
collect=(python3 -m pytest -q -o addopts= tests/test_all.py tests/test_in.py tests/test_label.py tests/test_misc.py tests/test_mov.py tests/test_nop.py tests/test_out.py tests/test_print_c_program.py tests/test_pseudo.py tests/test_radix.py tests/test_version.py tests/test_wrap.py)
collected_output=$("${collect[@]}" --collect-only)
collect_rc=$?
if [ "$collect_rc" -ne 0 ] && [ "$collect_rc" -ne 5 ]; then
  printf "%s\n" "$collected_output" >&2
  printf "[programgen] test collection failed with exit code %s\n" "$collect_rc" >&2
  exit "$collect_rc"
fi
mapfile -t collected < <(printf "%s\n" "$collected_output" | sed -n '"'"'/::/p'"'"' | sed '"'"'s/[[:space:]]*$//'"'"')
if [ "${#collected[@]}" -gt 500 ]; then
  while IFS= read -r id; do run+=("--deselect=$id"); done < <(printf "%s\n" "${collected[@]}" | awk -F'"'"'::'"'"' -v limit=500 '"'"'{f=$1; n[f]++; idx[f,n[f]]=NR; all[NR]=$0; if(!(f in seen)){seen[f]=1; order[++m]=f}} END{d=1; c=0; while(c<limit){a=0; for(i=1;i<=m;i++){f=order[i]; if(d<=n[f]){keep[idx[f,d]]=1; c++; a=1; if(c>=limit) break}} if(!a) break; d++} for(r=1;r<=NR;r++) if(!(r in keep)) print all[r]}'"'"')
fi
"${run[@]}"; exit $?'`
- **Test startup**: run the exact test command above from the project root after installation; hidden tests are injected separately.

## Environment & Project Structure

- **Language**: python
- **Build system**: python
- **Test command**: `bash -lc set -uo pipefail
run=(python3 -m pytest -vv -o addopts= tests/test_all.py tests/test_in.py tests/test_label.py tests/test_misc.py tests/test_mov.py tests/test_nop.py tests/test_out.py tests/test_print_c_program.py tests/test_pseudo.py tests/test_radix.py tests/test_version.py tests/test_wrap.py)
if [ -n "${COVERAGE_FILE:-}" ]; then run=(python3 -m coverage run --source=. -m pytest -vv -o addopts= tests/test_all.py tests/test_in.py tests/test_label.py tests/test_misc.py tests/test_mov.py tests/test_nop.py tests/test_out.py tests/test_print_c_program.py tests/test_pseudo.py tests/test_radix.py tests/test_version.py tests/test_wrap.py); fi
collect=(python3 -m pytest -q -o addopts= tests/test_all.py tests/test_in.py tests/test_label.py tests/test_misc.py tests/test_mov.py tests/test_nop.py tests/test_out.py tests/test_print_c_program.py tests/test_pseudo.py tests/test_radix.py tests/test_version.py tests/test_wrap.py)
collected_output=$("${collect[@]}" --collect-only)
collect_rc=$?
if [ "$collect_rc" -ne 0 ] && [ "$collect_rc" -ne 5 ]; then
  printf "%s\n" "$collected_output" >&2
  printf "[programgen] test collection failed with exit code %s\n" "$collect_rc" >&2
  exit "$collect_rc"
fi
mapfile -t collected < <(printf "%s\n" "$collected_output" | sed -n '/::/p' | sed 's/[[:space:]]*$//')
if [ "${#collected[@]}" -gt 500 ]; then
  while IFS= read -r id; do run+=("--deselect=$id"); done < <(printf "%s\n" "${collected[@]}" | awk -F'::' -v limit=500 '{f=$1; n[f]++; idx[f,n[f]]=NR; all[NR]=$0; if(!(f in seen)){seen[f]=1; order[++m]=f}} END{d=1; c=0; while(c<limit){a=0; for(i=1;i<=m;i++){f=order[i]; if(d<=n[f]){keep[idx[f,d]]=1; c++; a=1; if(c>=limit) break}} if(!a) break; d++} for(r=1;r<=NR;r++) if(!(r in keep)) print all[r]}')
fi
"${run[@]}"; exit $?`

### Project Directory Structure

```
.gitattributes
.github/PULL_REQUEST_TEMPLATE/adafruit_circuitpython_pr.md
.github/workflows/build.yml
.github/workflows/failure-help-text.yml
.github/workflows/release_gh.yml
.github/workflows/release_pypi.yml
.gitignore
.pre-commit-config.yaml
.readthedocs.yaml
CODE_OF_CONDUCT.md
LICENSE
LICENSES/BSD-3-Clause.txt
LICENSES/CC-BY-4.0.txt
LICENSES/MIT.txt
LICENSES/Unlicense.txt
README.rst
README.rst.license
adafruit_pioasm.py
docs/_static/custom.css
docs/_static/favicon.ico
docs/_static/favicon.ico.license
docs/api.rst
docs/api.rst.license
docs/conf.py
docs/examples.rst
docs/examples.rst.license
docs/index.rst
docs/index.rst.license
docs/requirements.txt
docs/syntax.rst
docs/syntax.rst.license
examples/pioasm_7seg.py
examples/pioasm_7seg_fader.py
examples/pioasm_background_morse.py
examples/pioasm_blink.py
examples/pioasm_hello.py
examples/pioasm_i2s_codec.py
examples/pioasm_i2sout.py
examples/pioasm_led_brightness.py
examples/pioasm_neopixel.py
examples/pioasm_neopixel_bg.py
examples/pioasm_pdm.py
examples/pioasm_print_c_program.py
examples/pioasm_pulsegroup.py
examples/pioasm_rotaryencoder.py
examples/pioasm_rp2350_fifo.py
examples/pioasm_rxuart.py
examples/pioasm_simpletest.py
examples/pioasm_txuart.py
examples/pioasm_wrap.py
optional_requirements.txt
pyproject.toml
requirements.txt
ruff.toml
tools/make_all.py
```

## API Usage Guide

Each capability below lists the components the tests exercise with their exact signatures and behavior. Re-create these so the tests pass; internal helpers not listed here may be implemented freely.

### Capability: PIO program text parsing and directives

# Capability: PIO program text parsing and directives

`adafruit_pioasm.Program` turns a text program into three artifacts produced by one constructor pass: `assembled` (an `array.array("H")` of 16-bit instruction words), `public_labels` (a `dict` mapping `public` label names to instruction indexes), and `pio_kwargs` (directive-derived settings intended for `rp2pio.StateMachine`). Module-level `assemble(text)` is a thin wrapper returning only `.assembled` of a throwaway `Program`; `Program.from_file(filename, **kwargs)` reads a UTF-8 file and forwards `**kwargs` (e.g. `build_debuginfo`) to the constructor.

## Parsing pipeline

`Program.__init__(text_program, *, build_debuginfo=False)` runs two phases.

**Phase 1 — line classification.** The text is split on `"\n"`. Each line is truncated at the first `;` (`line.split(";")[0]`) and stripped; empty results are skipped. Remaining lines are classified in this order:

1. Directives matched by *prefix on the stripped line*: `.program`, `.pio_version`, `.origin`, `.wrap_target`, `.wrap`, `.side_set`, `.fifo`, `.mov_status`.
2. Directives matched by *exact first whitespace-separated word*: `.in`, `.out`, `.set`. These must stand alone as the first token.
3. Labels: any other line ending with `:`.
4. Everything else becomes an instruction string, appended to the instruction list, with the original line index appended to a parallel linemap.

Because comment stripping splits at the first semicolon, a `;` can never reach any operand. Because prefix matching is used, extra words after a directive name are either consumed as its arguments or ignored.

## Ordering constraints

Seven directives call an internal check that raises `RuntimeError(f"{words[0]} must be before first instruction")` once any instruction has been collected: `.pio_version`, `.origin`, `.fifo`, `.mov_status`, `.in`, `.out`, `.set`. The remaining directives have no position guard:

- `.program` may appear anywhere but only once; a second occurrence raises `RuntimeError("Multiple programs not supported")`. The recorded name is never emitted anywhere.
- `.side_set` may appear anywhere; its effect is global because the delay/side-set bit budget is computed only after phase 1 completes.
- `.wrap_target` and `.wrap` are position-free relative to other directives, but `.wrap` raises `RuntimeError("Cannot have .wrap as first instruction")` when no instruction precedes it.

## Labels

A label line's trailing colon is removed. If the (stripped) line begins with the exact prefix `"public "`, the remaining name is stored in both the internal label table and `public_labels`; otherwise it is internal only. The stored value is `len(instructions)` at that point — the index of the *next* instruction, so a label before the first instruction resolves to 0 and a label at end-of-file resolves to the instruction count. Redeclaring any label — public or not, or the same name once internal and once public — raises `SyntaxError(f"Duplicate label {repr(label)}")`. Only `public`-prefixed labels appear in `Program.public_labels`, which is an empty dict when none exist. References are resolved in phase 2, so forward references need no ordering.

## Directive semantics, defaults, and pio_kwargs emission

`pio_kwargs` always contains `sideset_enable` (bool, `False` unless `.side_set ... opt`). Every other key is emitted only when its directive was seen:

- `.pio_version N`: `N` must satisfy `0 <= N < 2` (radix-0 int). Emitted as `pio_version` only when nonzero. Version gates: v1 selects the extended mov-destination table (adds `pindirs`); `wait jmppin`, `wait irq next/prev`, `irq next/prev`, `mov rxfifo[...]` forms, FIFO types `txput`/`txget`/`putget`, and `.mov_status irq` all raise `RuntimeError(f"{instruction} requires .pio_version 1")` when the version is lower.
- `.origin N`: `0 <= N < 32`; emitted as `offset` when present (an internal `-1` sentinel means absent).
- `.wrap_target` / `.wrap`: `wrap_target` records the index of the instruction following the directive; `wrap` records the index of the last instruction before it. Both keys are omitted when the directives are absent, letting `StateMachine` defaults apply. `nop\n.wrap_target\nnop\nnop\n.wrap` yields `wrap=2, wrap_target=1`. Repeating either directive silently overwrites — last occurrence wins.
- `.side_set COUNT [opt] [pindirs]`: `COUNT` parsed with radix 0; `opt` and `pindirs` are detected as substrings anywhere in the line. `sideset_pin_count` is emitted only when `COUNT != 0`; `sideset_pindirs` only when true. The count drives `max_delay = 2**(5 - COUNT - enable) - 1`, bounding every `[delay]` in the program (`RuntimeError("Delay too long:")`); `opt` reserves one more bit for the enable flag, shrinking the delay range further.
- `.fifo TYPE`: `TYPE` must be one of `auto/txrx/tx/rx/txput/txget/putget`, else `RuntimeError(f"Invalid fifo type {fifo_type}")`; the put/get variants require v1. The default `auto` is never emitted, so `fifo_type` appears only for an explicit non-auto choice.
- `.mov_status`: two shapes plus a permissive fallback. `txfifo < N` / `rxfifo < N` (v0-compatible): the third word must be exactly `<`, and a missing `<` raises `RuntimeError(f"Invalid {line}")`; `0 <= N < 32`. `irq [next|prev] set N` (v1-only): optional `next`/`prev` contribute base bits `0x10`/`0x8`, then the word `set` is required — a missing `set` raises `RuntimeError(f"Invalid {line})")`, with a stray trailing `)` in the literal message — and `0 <= N < 8`; `mov_status_n = base | N`. Any other first word is accepted silently on v0 and emitted verbatim as `mov_status_type` with `mov_status_n` 0, so only the `<`/`set` syntax checks and the v1 gate on the `irq` form can raise. `mov_status_type` and `mov_status_n` are emitted together or not at all.
- `.out COUNT [left|right] [auto] [THRESHOLD]`: `1 <= COUNT < 33`; trailing options are order-sensitive (direction, then `auto`, then threshold with `1 <= threshold < 33`). `out_pin_count` is emitted only when `COUNT` is present and not 32; `out_shift_right` only when `left`/`right` given; `pull_threshold` only when a threshold given.
- `.in COUNT [left|right] [auto] [THRESHOLD]`: same shape, but the minimum count is 32 under `.pio_version 0` and 1 under version 1 — `.in 8` fails on v0 with a range error naming `.in count`. Emission mirrors `.out` (`in_pin_count`, `in_shift_right`, `push_threshold`).
- `.set COUNT`: must be exactly 5 on v0 (range `[5, 6)`) and 1–5 on v1; emitted as `set_pin_count` when present.

**Auto flags encode three states.** Merely seeing `.out` sets an internal `auto_pull = False`; the keyword `auto` upgrades it to `True`. So `auto_pull` appears in `pio_kwargs` for any `.out` directive — `False` meaning explicit-pull shifting, `True` meaning autopull — and is absent when there is no `.out`, leaving the `StateMachine` default in force. `.in` behaves identically for `auto_push`. The same three-state pattern applies to shift direction: omitting `left`/`right` omits `out_shift_right`/`in_shift_right` so the hardware default survives.

## Phase 2: per-instruction effects of parsing state

Instructions are encoded in source order. Two decorations are recognized positionally: a trailing bracketed `[delay]` token (radix-0 int; negative → `RuntimeError("Delay negative:")`; above `max_delay` → `RuntimeError("Delay too long:")`) and a trailing `side VALUE` pair (recognized only when it is second-to-last, `len(instruction) > 2`) requiring a nonzero sideset configuration (`RuntimeError("No side_set count set")`) and a value below `2**count` (`RuntimeError("Sideset value too large")`). Delay and side-set bits share the byte above the opcode; the `opt` flag occupies bit 4. Because these are positional, a line consisting only of `side 2` or `[5]` is classified as an instruction in phase 1 and fails with `RuntimeError("Unknown instruction: side")` / `"Unknown instruction: [5]"` — `side` is never a standalone mnemonic.

All numeric operands accept radix-0 integers (delays, side-set values, counts, thresholds, `.origin`, `.pio_version`, wait/irq indexes), so `0x10` and `16` are interchangeable.

Error types are consistent: `RuntimeError` for directive misuse, range violations, unknown mnemonics, and delay/side-set problems; `SyntaxError` for duplicate labels and unresolvable `jmp` targets; `ValueError` for unrecognized `jmp` conditions and `in`/`out`/`set`/`mov` source or destination names.

## Interaction with the rest of the library

`build_debuginfo=True` stores `(linemap, original_text)` on `Program.debuginfo` (`None` otherwise); `print_c_program(name, qualifier="const")` consumes it to interleave source lines as comments in a printed C array, defaulting `wrap` to `len(assembled) - 1` and `wrap_target` to `0` when the directives were absent. `public_labels` exists so drivers can locate named entry points without hardcoding offsets. `pio_kwargs` is designed for `rp2pio.StateMachine(program.assembled, ..., **program.pio_kwargs)`: absent directives produce absent keys, so hardware defaults apply untouched, while each explicit directive overrides exactly the setting it names.

#### Exact API Reference

#### `adafruit_pioasm.Program`

- **Import Path**: `from adafruit_pioasm import Program`
- **Required Test Import Paths**:
  - adafruit_pioasm.Program
- **Exact Test Import Statements**:
  - import adafruit_pioasm
- **Kind**: class
- **Signature**:

```python
class Program:
    assembled: array.array
    public_labels: dict[str, int]
    pio_kwargs: dict[str, Any]
    def __init__(self, text_program: str, *, build_debuginfo: bool=False) -> None
    @classmethod
    def from_file(cls, filename: str, **kwargs) -> 'Program'
    def print_c_program(self, name: str, qualifier: str='const') -> None
    debuginfo: Any
```

- **Raises** (implementation must reproduce these exact messages):
  - `Multiple programs not supported`
  - `Delay negative:`
  - `Delay too long:`
  - `No side_set count set`
  - `Sideset value too large`
  - `Invalid polarity`
  - `Count out of range`
  - `Cannot have .wrap as first instruction`
- **Behavior**: Encapsulates a program's instruction stream and configuration flags

#### `adafruit_pioasm`

- **Import Path**: `adafruit_pioasm`
- **Required Test Import Paths**:
  - adafruit_pioasm
- **Exact Test Import Statements**:
  - import adafruit_pioasm
- **Kind**: module
- **Behavior**: Module required during hidden-test collection.

### Capability: Core instruction assembly to encoded bytes

# Core instruction assembly to encoded bytes

## Purpose

This capability converts individual PIO instruction lines (`nop`, `jmp`, `wait`, `in`, `out`, `push`, `pull`, `mov`, `irq`, `set`) into the 16-bit machine words an RP2040/RP2350 PIO state machine executes. Two entry points expose it:

- `assemble(program_text)` — a one-shot helper that returns only the encoded instruction stream.
- `Program(text_program)` — the same encoding pass, but the resulting object also carries directive-derived configuration (`pio_kwargs`), `public_labels`, and the assembled stream in `assembled`.

`assemble` is exactly `Program(program_text).assembled`, so every encoding rule below applies to both. Both return an `array.array` of type code `"H"`: one unsigned 16-bit half-word per instruction, never a byte string, with one element per source instruction in source order. That array is what callers hand to `rp2pio.StateMachine` as its program.

## Two-pass pipeline, ordering, and state

`Program.__init__` first scans every line: strips `;`-comments and whitespace, resolves labels to *instruction indices* (not byte offsets), and buffers instruction lines. Only then does the encoding pass run over the buffered instructions in order. Consequences that matter for re-implementation:

- **Forward references work.** A `jmp` may target a label declared later in the program, because label lookup happens during encoding, after the whole label table is built.
- **Duplicate labels fail in the scan pass.** Declaring the same label twice raises `SyntaxError("Duplicate label ...")` before any instruction is encoded.
- **Directive placement is enforced, not position-free.** `.pio_version`, `.fifo`, `.origin`, `.in`, `.out`, `.set`, and `.mov_status` must precede the first instruction line; appearing after one raises `RuntimeError("<directive> must be before first instruction")`. `.side_set`, `.wrap`, and `.wrap_target` may appear anywhere, but `.wrap` cannot be the program's first line ("Cannot have .wrap as first instruction") and `.wrap`/`.wrap_target` record instruction indices at the directive's location, so the wrap offsets they yield depend on where they appear. Only the side-set geometry is applied globally to all instructions at encode time.
- **No partial results escape.** Encoding mutates a local list (append a base word, then OR operand fields into the last element); any error propagates out of the constructor before the object exists, and `assemble` never returns a truncated array.
- The final step of every instruction is `word |= delay << 8`, where `delay` is the shared delay/side-set field. This runs unconditionally, so delay and side-set compose with every opcode, including `nop`.

## Instruction word layout

Bits 15:13 are the opcode; bits 12:8 are delay/side-set; bits 7:0 are the operand. Per-opcode operand encoding:

- **`nop`** — a fixed base word `0b101_00000_010_00_010` (equivalently `mov y, y`). It accepts an optional delay/side-set like any instruction; it takes no operands, and any trailing tokens beyond the optional `[delay]` and `side` value are silently ignored — `nop foo` assembles to the same `mov y, y` word with no error, unlike every other mnemonic, which fails on malformed operands.
- **`jmp`** — condition index (from `""`, `!x`, `x--`, `!y`, `y--`, `x!=y`, `pin`, `!osre`) OR'd at bit 5; a bare `jmp target` uses condition index 0. The *last* token is the target: if it starts with a digit it is parsed as an absolute instruction address with `int(target, 0)`; otherwise it must match a label. Condition is only parsed when a middle token exists (`jmp x-- 3` is valid).
- **`wait`** — polarity (0 or 1) at bit 7; source `gpio`/`pin`/`irq` index at bit 5; index in the low bits. `irq` indices are limited to 0–7, `gpio`/`pin` to 0–31. The suffix `rel` sets bit 4 for a relative IRQ. `jmppin` (PIO v1 only) uses source code `0b11` and optionally takes `+ offset` with offset 0–3.
- **`in` / `out`** — source/destination index at bit 5; bit count in the low 5 bits. Counts must be 1–32; 32 encodes as `00000` via a `& 0x1F` mask, so the all-zero count means "32", not "0".
- **`push` / `pull`** — shared opcode. `pull` sets bit 7; `ifempty`/`iffull` as the second token sets bit 6 (both spellings set the same bit, and the encoder does not cross-check that `ifempty` is used with `push`); the blocking bit is bit 5.
- **`mov`** — destination at bit 5, source in bits 2:0, operator in bits 4:3. `!`/`~` prefixes (invert) set bit 3; `::` (bit-reverse) sets bit 4. `mov rxfifo[n], isr` and `mov osr, rxfifo[n]` use dedicated base words with the index (0–7, or `0b1000` for `[y]`) folded into the low bits; the source of an rxfifo write must be `isr` and the target of an rxfifo read must be `osr`.
- **`irq`** — `wait` sets bit 5, `clear` sets bit 6; `next`/`prev` (PIO v1) become type bits `0b11`/`0b01` at bit 3; the suffix `rel` switches to relative mode (type `0b10`); the IRQ index 0–7 occupies the low bits.
- **`set`** — destination at bit 5; immediate value 0–31 in the low 5 bits.

## Delay and side-set share one field

The 5-bit delay field also carries the side-set value. `max_delay` is `2**(5 - sideset_count - sideset_enable) - 1`: 31 with no side-set, 15 with `.side_set 1`, 7 with `.side_set 1 opt`. A delay exceeding it raises `RuntimeError("Delay too long:", ...)`, a negative one raises `RuntimeError("Delay negative:", ...)`. The sideset value must be `< 2**count` ("Sideset value too large") and `side` cannot be used at all without a `.side_set` directive ("No side_set count set"). The side-set value is shifted to sit just above the delay bits, so delay and side-set value together exactly fill bits (5 - sideset_enable - 1):0 — bits 4:0 with no `opt`, bits 3:0 with `opt`, where the opt flag occupies bit 4 — so the two independently checked bounds cannot jointly overflow.

## Defaults and non-obvious behaviors

- **`push`/`pull` block by default.** With no trailing token, or with the explicit token `block`, the block bit is set; only `noblock` leaves it clear. `push` and `push block` assemble identically.
- **Radix freedom.** Every numeric operand is parsed with `int(arg, 0)`, so `0x10`, `0b101`, and decimal literals are accepted interchangeably for delays, side-set values, counts, `set` data, wait polarity/index, `jmp` addresses, and IRQ indices.
- **Version and FIFO gating.** `wait jmppin`, `wait irq next/prev`, `irq next/prev`, `mov rxfifo[...]`, and version-1 FIFO modes raise `RuntimeError("... requires .pio_version 1")` unless the program declared `.pio_version 1`. The rxfifo `mov` forms are additionally gated on FIFO configuration: `mov rxfifo[n], isr` requires `.fifo txput` (or `putget`), and `mov osr, rxfifo[n]` requires `.fifo txget` (or `putget`); otherwise the encoder raises `RuntimeError("FIFO must be configured for '<dir>' or 'putget' for <line>")`. `mov pindirs, ...` is only valid under version 1, enforced by swapping to the version-1 destination table.
- **Invalid `mov` destinations raise an unwrapped error.** `in`, `out`, `set`, `jmp` conditions, and `mov` sources wrap lookup failures in `ValueError`s quoting the bad token (e.g. `Invalid in source 'foo'`). The `mov` destination lookup does not: a bad destination surfaces as the list's own `ValueError` (an "is not in list" message), unlike its neighbors.
- **`rel` conflicts.** `wait ... rel` and `irq ... rel` combined with `next`/`prev` raise `RuntimeError("cannot use next/prev with rel")`.
- **Missing operands are not specially diagnosed.** A mnemonic with too few tokens fails with a raw `IndexError` or a `ValueError` from integer parsing rather than a pioasm-specific message (e.g. a bare `wait` line). Only the `jmp`-target case degrades gracefully to `SyntaxError: Invalid jmp target '<token>'`.
- **Literal quirk in one message.** The `wait` gpio/pin/irq index range check passes a non-formatted template as the item name, so out-of-range indices produce messages shaped like `wait {instruction[2]} must be at least 0 and less than N, got X` — braces included — where N is 8 for `irq` and 32 for `gpio`/`pin`. The `jmppin` offset check is separate and uses a properly formatted `wait jmppin offset` message (limit 4, i.e. offsets 0–3).
- **Unknown mnemonics** raise `RuntimeError(f"Unknown instruction: {mnemonic}")`; anything the encoder could not classify fails here rather than being skipped.
- An operand that contains an operator split (via `!`, `~`, `::`) but does not *start* with one raises `RuntimeError("Invalid mov operator:", first_char)`; recognized operator prefixes are `!`, `~`, and `::`.

## How the pieces relate in a realistic workflow

For quick programs with no directive-driven hardware configuration, `assemble(text)` returns the ready-to-load array. For anything using `.side_set`, `.wrap`, FIFO modes, or public labels, construct `Program` instead: the same encoded stream lands in `program.assembled`, and `program.pio_kwargs` carries the side-set geometry, shift configuration, and wrap offsets that the state-machine constructor needs to decode the stream correctly. The distinction is consequential: `assemble` still *encodes* side-set bits into the delay field (the geometry affects `max_delay` and bit placement), but it discards the configuration, so the receiving driver would not know sideset decoding is enabled. The encoding itself is position-independent — the same instruction line yields the same word regardless of program position; only `jmp` targets and `irq rel` are context-sensitive, and both resolve through the label table or relative flag rather than through absolute placement.

Error ordering is two-phase. All scan-pass errors — directive misuse (including the must-be-before-first-instruction rule, invalid FIFO types, and directive range violations) and duplicate labels — are raised during the scan, before any instruction is encoded, so such an error on a later line always preempts a malformed instruction earlier in the source. Within the encoding pass, instruction errors surface top-to-bottom, so the first malformed instruction line determines which error surfaces.

#### Exact API Reference

#### `adafruit_pioasm.assemble`

- **Import Path**: `from adafruit_pioasm import assemble`
- **Required Test Import Paths**:
  - adafruit_pioasm.assemble
- **Exact Test Import Statements**:
  - import adafruit_pioasm
- **Signature**:

```python
def assemble(program_text: str) -> array.array
```
- **Behavior**: Converts pioasm text to encoded instruction bytes

## Detailed Implementation Nodes

### Node: PIO program text parsing and directives

# Functional constraints

- `Program(text_program, *, build_debuginfo=False)`; `build_debuginfo` is keyword-only. Outputs: `assembled` (`array.array("H")`, one 16-bit word per instruction, source order), `public_labels` (`dict[str, int]`), `pio_kwargs` (`dict`), `debuginfo` (`(linemap, text)` tuple or `None`).
- Line handling: split on `\n`, cut at first `;`, strip, skip empties. Labels end with `:`; their value is the index of the next instruction (end-of-file label = instruction count). Duplicates raise `SyntaxError`; only the `public ` prefix populates `public_labels`.
- Ordering: `.pio_version`, `.origin`, `.fifo`, `.mov_status`, `.in`, `.out`, `.set` must precede the first instruction (`RuntimeError "... must be before first instruction"`); `.program` is unique; `.wrap` needs a preceding instruction; `.side_set`, `.wrap_target`, `.wrap` are position-free, repeats overwrite (last wins).
- `pio_kwargs` always contains `sideset_enable`; all other keys are conditional: `offset`, `pio_version` (only when ≠ 0), `sideset_pin_count` (count ≠ 0), `sideset_pindirs`, `wrap`, `wrap_target`, `fifo_type` (≠ `auto`), `mov_status_type` + `mov_status_n` (together), `set_pin_count`, `out_pin_count` / `in_pin_count` (omitted when count is None or 32), `out_shift_right` / `in_shift_right`, `auto_pull` / `auto_push`, `pull_threshold` / `push_threshold`.
- Three-state option flags: any `.out` sets `auto_pull=False`, `auto` sets `True`, no directive omits the key; same for `.in` → `auto_push`. Omitting `left`/`right` omits the shift-direction key.
- `.side_set COUNT [opt] [pindirs]`: `opt`/`pindirs` are substring checks; count sets `max_delay = 2**(5 - count - enable) - 1` for all `[delay]` tokens; `opt` consumes one delay bit (bit 4 is the enable flag).
- Ranges: `.pio_version` 0–1; `.origin` 0–31; `.out` count 1–32; `.in` count ≥ 32 on v0 but ≥ 1 on v1; `.set` count exactly 5 on v0, 1–5 on v1; thresholds 1–32; wait gpio/pin index < 32, irq index < 8; `.mov_status txfifo|rxfifo < N` with N < 32, `irq [next|prev] set N` (v1) with N < 8 and base bits `0x10`/`0x8` OR'd in.
- `.fifo` accepts `auto txrx tx rx txput txget putget`; the last three require `.pio_version 1`, as do `wait jmppin`, `wait irq next/prev`, `irq next/prev`, and `mov rxfifo[...]`.
- All integers parse with radix 0 (`0x10` valid); `;` comments mean `;` can never appear in an operand.
- Error typing: `RuntimeError` for directive misuse/ranges/unknown instruction/delay/side-set; `SyntaxError` for duplicate labels and bad `jmp` targets; `ValueError` for invalid condition and source/destination mnemonics.
- `assemble(text)` returns only `Program(text).assembled`; `Program.from_file(filename, **kwargs)` opens UTF-8 and forwards kwargs (e.g. `build_debuginfo=True`).

Example (directive collection, labels, wrap indexes):

```python
import adafruit_pioasm

p = adafruit_pioasm.Program("""\
.program demo
.side_set 1 opt
public start:
    set x, 3
.wrap_target
    nop side 1 [3]
    nop side 0
.wrap""")
assert p.public_labels == {"start": 0}
assert p.pio_kwargs == {"sideset_enable": True, "sideset_pin_count": 1,
                        "wrap": 2, "wrap_target": 1}
```

### Node: Core instruction assembly to encoded bytes

# Implementation notes: instruction encoding

Functional constraints

- `assemble(program_text)` is defined as `Program(program_text).assembled`; one implementation of the encoding serves both APIs.
- Output is `array.array("H", ...)`; element *k* is the 16-bit word for the *k*-th instruction line (comments and directives excluded from the count).
- Word layout: bits 15:13 opcode, 12:8 delay/side-set, 7:0 operand. Base words: `nop`=mov y,y fixed; `jmp`=0b000; `wait`=0b001; `in`=0b010; `out`=0b011; `push`/`pull`=0b100 (pull adds 0x80); `mov`=0b101 (rxfifo forms use dedicated 0b100 base words); `irq`=0b110; `set`=0b111.
- Operand indexes come from module tables: `CONDITIONS` (index<<5), `IN_SOURCES`, `OUT_DESTINATIONS`, `WAIT_SOURCES` (<<5), `MOV_DESTINATIONS_V0/V1` (<<5, table chosen by `.pio_version`), `MOV_SOURCES`, `MOV_OPS` (<<3), `SET_DESTINATIONS` (<<5). An unused table slot is `None`, so mnemonic names mapping to it fail lookups.
- Counts: `in`/`out` count must be 1–32 and are masked with `& 0x1F` (32 → 0b00000); `set` data 0–31; `irq`/`wait irq` index 0–7; `wait gpio/pin` index 0–31; `wait jmppin` offset 0–3; rxfifo index 0–7 or `[y]` → 0b1000.
- push/pull: block bit set unless the trailing token is `noblock`; `ifempty`/`iffull` in the operand position sets the condition bit regardless of push vs. pull.
- mov operators: prefix `!`/`~` → bit 3 (invert), `::` → bit 4 (reverse); the split-detached form (operator as its own token before the source) resolves through `MOV_OPS` and yields the same bits.
- Delay/side-set: trailing `[n]` token is the delay (`int(n, 0)`, bounded by `2**(5-sideset_count-sideset_enable)-1`); `side v` requires `.side_set`, value `< 2**count`, placed at bit `5 - count - opt`; `opt` flag at bit 4; delay and side-set value together fill bits (5 - sideset_enable - 1):0; combined field OR'd as `<< 8` last.
- Error classes: `SyntaxError` for duplicate labels (scan pass) and invalid jmp targets (encode pass); `ValueError` (with quoted token) for invalid jmp condition, in source, out destination, set destination, mov source; raw `ValueError` (unwrapped) for invalid mov destination; `RuntimeError` for unknown mnemonic, range violations, polarity, delay bounds, sideset misuse, `rel`/`next`/`prev` conflicts, FIFO-configuration mismatches, and any version-1 instruction under `.pio_version 0`.
- Version gating: `wait jmppin`, `wait irq next|prev`, `irq next|prev`, `mov rxfifo[...]` require `.pio_version 1`; rxfifo `mov` forms additionally require a matching `.fifo` type (`txput`/`putget` for `mov rxfifo[n], isr`, `txget`/`putget` for `mov osr, rxfifo[n]`, else `RuntimeError("FIFO must be configured for ...")`); `mov pindirs` works only via the V1 destination table.
- Encoding is order-dependent only through the label table (built before encoding) and directive state (`.side_set` geometry, `.pio_version`, `fifo_type`); forward `jmp` label references are legal. Directive placement is itself checked during the scan: `.pio_version`, `.fifo`, `.origin`, `.in`, `.out`, `.set`, `.mov_status` must precede the first instruction (`RuntimeError("<directive> must be before first instruction")` otherwise), while `.side_set`/`.wrap`/`.wrap_target` are position-sensitive only through the instruction indices they record.
- Error ordering is two-phase: all scan-pass errors (directives, duplicate labels) preempt any instruction-encoding error regardless of line position; within the encode pass, instruction errors surface top-to-bottom.

Example (≤15 lines)

```python
import adafruit_pioasm

words = adafruit_pioasm.assemble(
    """
    .side_set 1 opt
    public loop:
        set x, 0x1f     [3]
        jmp x-- loop    side 1
    """
)
assert words.typecode == "H"
assert words[0] == 0b111_00011_001_11111  # set x,31 ; delay 3
assert words[1] == 0b000_11000_010_00000  # jmp x--, addr 0 ; side 1 (opt bit 4)
```