Download tasks/data/forward/adafruit__adafruit_circuitpython_pioasm.4c47f96/instruction.md from Lego-X/ProgramGen: direct link, hf CLI and curl.
- Browser
- Download file 41.3 kB
-
https://huggingface.co/datasets/Lego-X/ProgramGen/resolve/main/tasks/data/forward/adafruit__adafruit_circuitpython_pioasm.4c47f96/instruction.md
- Command line
-
hf download hf://datasets/Lego-X/ProgramGen/tasks/data/forward/adafruit__adafruit_circuitpython_pioasm.4c47f96/instruction.md
-
curl -L -o instruction.md https://huggingface.co/datasets/Lego-X/ProgramGen/resolve/main/tasks/data/forward/adafruit__adafruit_circuitpython_pioasm.4c47f96/instruction.md
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:
Do NOT create or modify any files under the test directories (e.g.
tests/,test/,testing/, or files namedtest_*.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.Your package MUST be importable by the name the tests use. The hidden tests
importyour package by its documented top-level name (see the Project Directory Structure and API Usage Guide below). Provide a validpyproject.toml/setup.py/setup.cfgand lay out your modules so thatpip install -e .succeeds and the package imports cleanly. If your package is not installable/importable, every test errors out and the reward is 0.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/repoat 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:
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:
{ [ -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:
- Directives matched by prefix on the stripped line:
.program,.pio_version,.origin,.wrap_target,.wrap,.side_set,.fifo,.mov_status. - Directives matched by exact first whitespace-separated word:
.in,.out,.set. These must stand alone as the first token. - Labels: any other line ending with
:. - 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:
.programmay appear anywhere but only once; a second occurrence raisesRuntimeError("Multiple programs not supported"). The recorded name is never emitted anywhere..side_setmay appear anywhere; its effect is global because the delay/side-set bit budget is computed only after phase 1 completes..wrap_targetand.wrapare position-free relative to other directives, but.wrapraisesRuntimeError("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:Nmust satisfy0 <= N < 2(radix-0 int). Emitted aspio_versiononly when nonzero. Version gates: v1 selects the extended mov-destination table (addspindirs);wait jmppin,wait irq next/prev,irq next/prev,mov rxfifo[...]forms, FIFO typestxput/txget/putget, and.mov_status irqall raiseRuntimeError(f"{instruction} requires .pio_version 1")when the version is lower..origin N:0 <= N < 32; emitted asoffsetwhen present (an internal-1sentinel means absent)..wrap_target/.wrap:wrap_targetrecords the index of the instruction following the directive;wraprecords the index of the last instruction before it. Both keys are omitted when the directives are absent, lettingStateMachinedefaults apply.nop\n.wrap_target\nnop\nnop\n.wrapyieldswrap=2, wrap_target=1. Repeating either directive silently overwrites — last occurrence wins..side_set COUNT [opt] [pindirs]:COUNTparsed with radix 0;optandpindirsare detected as substrings anywhere in the line.sideset_pin_countis emitted only whenCOUNT != 0;sideset_pindirsonly when true. The count drivesmax_delay = 2**(5 - COUNT - enable) - 1, bounding every[delay]in the program (RuntimeError("Delay too long:"));optreserves one more bit for the enable flag, shrinking the delay range further..fifo TYPE:TYPEmust be one ofauto/txrx/tx/rx/txput/txget/putget, elseRuntimeError(f"Invalid fifo type {fifo_type}"); the put/get variants require v1. The defaultautois never emitted, sofifo_typeappears 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<raisesRuntimeError(f"Invalid {line}");0 <= N < 32.irq [next|prev] set N(v1-only): optionalnext/prevcontribute base bits0x10/0x8, then the wordsetis required — a missingsetraisesRuntimeError(f"Invalid {line})"), with a stray trailing)in the literal message — and0 <= N < 8;mov_status_n = base | N. Any other first word is accepted silently on v0 and emitted verbatim asmov_status_typewithmov_status_n0, so only the</setsyntax checks and the v1 gate on theirqform can raise.mov_status_typeandmov_status_nare emitted together or not at all..out COUNT [left|right] [auto] [THRESHOLD]:1 <= COUNT < 33; trailing options are order-sensitive (direction, thenauto, then threshold with1 <= threshold < 33).out_pin_countis emitted only whenCOUNTis present and not 32;out_shift_rightonly whenleft/rightgiven;pull_thresholdonly when a threshold given..in COUNT [left|right] [auto] [THRESHOLD]: same shape, but the minimum count is 32 under.pio_version 0and 1 under version 1 —.in 8fails 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 asset_pin_countwhen 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:
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 supportedDelay negative:Delay too long:No side_set count setSideset value too largeInvalid polarityCount out of rangeCannot 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 inassembled.
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
jmpmay 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_statusmust precede the first instruction line; appearing after one raisesRuntimeError("<directive> must be before first instruction")..side_set,.wrap, and.wrap_targetmay appear anywhere, but.wrapcannot be the program's first line ("Cannot have .wrap as first instruction") and.wrap/.wrap_targetrecord 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
assemblenever returns a truncated array. - The final step of every instruction is
word |= delay << 8, wheredelayis the shared delay/side-set field. This runs unconditionally, so delay and side-set compose with every opcode, includingnop.
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 word0b101_00000_010_00_010(equivalentlymov y, y). It accepts an optional delay/side-set like any instruction; it takes no operands, and any trailing tokens beyond the optional[delay]andsidevalue are silently ignored —nop fooassembles to the samemov y, yword 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 barejmp targetuses condition index 0. The last token is the target: if it starts with a digit it is parsed as an absolute instruction address withint(target, 0); otherwise it must match a label. Condition is only parsed when a middle token exists (jmp x-- 3is valid).wait— polarity (0 or 1) at bit 7; sourcegpio/pin/irqindex at bit 5; index in the low bits.irqindices are limited to 0–7,gpio/pinto 0–31. The suffixrelsets bit 4 for a relative IRQ.jmppin(PIO v1 only) uses source code0b11and optionally takes+ offsetwith 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 as00000via a& 0x1Fmask, so the all-zero count means "32", not "0".push/pull— shared opcode.pullsets bit 7;ifempty/iffullas the second token sets bit 6 (both spellings set the same bit, and the encoder does not cross-check thatifemptyis used withpush); 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], israndmov osr, rxfifo[n]use dedicated base words with the index (0–7, or0b1000for[y]) folded into the low bits; the source of an rxfifo write must beisrand the target of an rxfifo read must beosr.irq—waitsets bit 5,clearsets bit 6;next/prev(PIO v1) become type bits0b11/0b01at bit 3; the suffixrelswitches to relative mode (type0b10); 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/pullblock by default. With no trailing token, or with the explicit tokenblock, the block bit is set; onlynoblockleaves it clear.pushandpush blockassemble identically.- Radix freedom. Every numeric operand is parsed with
int(arg, 0), so0x10,0b101, and decimal literals are accepted interchangeably for delays, side-set values, counts,setdata, wait polarity/index,jmpaddresses, and IRQ indices. - Version and FIFO gating.
wait jmppin,wait irq next/prev,irq next/prev,mov rxfifo[...], and version-1 FIFO modes raiseRuntimeError("... requires .pio_version 1")unless the program declared.pio_version 1. The rxfifomovforms are additionally gated on FIFO configuration:mov rxfifo[n], isrrequires.fifo txput(orputget), andmov osr, rxfifo[n]requires.fifo txget(orputget); otherwise the encoder raisesRuntimeError("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
movdestinations raise an unwrapped error.in,out,set,jmpconditions, andmovsources wrap lookup failures inValueErrors quoting the bad token (e.g.Invalid in source 'foo'). Themovdestination lookup does not: a bad destination surfaces as the list's ownValueError(an "is not in list" message), unlike its neighbors. relconflicts.wait ... relandirq ... relcombined withnext/prevraiseRuntimeError("cannot use next/prev with rel").- Missing operands are not specially diagnosed. A mnemonic with too few tokens fails with a raw
IndexErroror aValueErrorfrom integer parsing rather than a pioasm-specific message (e.g. a barewaitline). Only thejmp-target case degrades gracefully toSyntaxError: Invalid jmp target '<token>'. - Literal quirk in one message. The
waitgpio/pin/irq index range check passes a non-formatted template as the item name, so out-of-range indices produce messages shaped likewait {instruction[2]} must be at least 0 and less than N, got X— braces included — where N is 8 forirqand 32 forgpio/pin. Thejmppinoffset check is separate and uses a properly formattedwait jmppin offsetmessage (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 raisesRuntimeError("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:
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_debuginfois 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 orNone).- 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 raiseSyntaxError; only thepublicprefix populatespublic_labels. - Ordering:
.pio_version,.origin,.fifo,.mov_status,.in,.out,.setmust precede the first instruction (RuntimeError "... must be before first instruction");.programis unique;.wrapneeds a preceding instruction;.side_set,.wrap_target,.wrapare position-free, repeats overwrite (last wins). pio_kwargsalways containssideset_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
.outsetsauto_pull=False,autosetsTrue, no directive omits the key; same for.in→auto_push. Omittingleft/rightomits the shift-direction key. .side_set COUNT [opt] [pindirs]:opt/pindirsare substring checks; count setsmax_delay = 2**(5 - count - enable) - 1for all[delay]tokens;optconsumes one delay bit (bit 4 is the enable flag).- Ranges:
.pio_version0–1;.origin0–31;.outcount 1–32;.incount ≥ 32 on v0 but ≥ 1 on v1;.setcount exactly 5 on v0, 1–5 on v1; thresholds 1–32; wait gpio/pin index < 32, irq index < 8;.mov_status txfifo|rxfifo < Nwith N < 32,irq [next|prev] set N(v1) with N < 8 and base bits0x10/0x8OR'd in. .fifoacceptsauto txrx tx rx txput txget putget; the last three require.pio_version 1, as dowait jmppin,wait irq next/prev,irq next/prev, andmov rxfifo[...].- All integers parse with radix 0 (
0x10valid);;comments mean;can never appear in an operand. - Error typing:
RuntimeErrorfor directive misuse/ranges/unknown instruction/delay/side-set;SyntaxErrorfor duplicate labels and badjmptargets;ValueErrorfor invalid condition and source/destination mnemonics. assemble(text)returns onlyProgram(text).assembled;Program.from_file(filename, **kwargs)opens UTF-8 and forwards kwargs (e.g.build_debuginfo=True).
Example (directive collection, labels, wrap indexes):
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 asProgram(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 isNone, so mnemonic names mapping to it fail lookups. - Counts:
in/outcount must be 1–32 and are masked with& 0x1F(32 → 0b00000);setdata 0–31;irq/wait irqindex 0–7;wait gpio/pinindex 0–31;wait jmppinoffset 0–3; rxfifo index 0–7 or[y]→ 0b1000. - push/pull: block bit set unless the trailing token is
noblock;ifempty/iffullin 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 throughMOV_OPSand yields the same bits. - Delay/side-set: trailing
[n]token is the delay (int(n, 0), bounded by2**(5-sideset_count-sideset_enable)-1);side vrequires.side_set, value< 2**count, placed at bit5 - count - opt;optflag at bit 4; delay and side-set value together fill bits (5 - sideset_enable - 1):0; combined field OR'd as<< 8last. - Error classes:
SyntaxErrorfor 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; rawValueError(unwrapped) for invalid mov destination;RuntimeErrorfor unknown mnemonic, range violations, polarity, delay bounds, sideset misuse,rel/next/prevconflicts, 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; rxfifomovforms additionally require a matching.fifotype (txput/putgetformov rxfifo[n], isr,txget/putgetformov osr, rxfifo[n], elseRuntimeError("FIFO must be configured for ..."));mov pindirsworks only via the V1 destination table. - Encoding is order-dependent only through the label table (built before encoding) and directive state (
.side_setgeometry,.pio_version,fifo_type); forwardjmplabel references are legal. Directive placement is itself checked during the scan:.pio_version,.fifo,.origin,.in,.out,.set,.mov_statusmust precede the first instruction (RuntimeError("<directive> must be before first instruction")otherwise), while.side_set/.wrap/.wrap_targetare 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)
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)