""" kernel_builder.py — Assembles the complete FORTH kernel image. Takes all Layer 0 primitives (clang-assembled, individually tested) and lays them out in memory at fixed addresses, building a linked dictionary that Layer 1 FORTH words can search. Output: a single .bin file that goes in the code cave at 0x004690. """ import struct from src.clang_asm import assemble_body from src.thumb_asm import ThumbAsm # ── SRAM address contract ──────────────────────────────────────────────── # These are SRAM addresses the kernel reads/writes, INDEPENDENT of the flash # base (which is relocateable via KernelBuilder(base=)). Pinned here as module # constants so the firmware_patcher's SPP shim and the kernel agree by # construction (the shim stages INPUT/INLEN/INIDX and drains OUTBUF/OUTLEN; # if either side moved an address without the other, the contract breaks # silently — the same Dragon-3 class). Mirrors the local pins in # build_layer1_primitives; if you change one, change both. RAM_BASE = 0x00800000 S_LATEST = RAM_BASE + 0x3000 # dict head pointer S_DP = RAM_BASE + 0x3004 # dictionary pointer (free dict region) S_STATE = RAM_BASE + 0x3008 # interpret/compile flag S_DICT = RAM_BASE + 0x4000 # free dict region (DP's home base) S_PAD = RAM_BASE + 0x5000 # scratch / token buffer S_OUTBUF = RAM_BASE + 0x6000 # EMIT accumulates TOS bytes here S_OUTLEN = RAM_BASE + 0x6100 # OUTBUF byte count S_IPSAVE = RAM_BASE + 0x7000 # CALL scratch (IP-save cell) S_INPUT = RAM_BASE + 0x1000 # 256B token-source buffer (WORD scans here) S_INLEN = RAM_BASE + 0x1100 # INPUT byte count S_INIDX = RAM_BASE + 0x1104 # INPUT scan cursor class KernelBuilder: """ Builds the complete FORTH kernel image. Memory layout (relative to cave base 0x004690): 0x0000: NEXT (inner interpreter) 0x0010: DOCOL, EXIT (threading words) 0x0030: LIT, DROP, DUP, SWAP, OVER, ROT (stack) 0x00C0: +, -, @, !, C@, C! (arithmetic + memory) 0x0140: 0=, 0<, < (comparison) 0x0180: BRANCH, 0BRANCH (control flow) 0x01A0: KEY, EMIT (I/O) 0x0200: , HERE (dictionary) 0x0240: Dictionary entries (linked list) 0x0400: Thread data for Layer 1 FORTH words base: absolute address where offset 0 of the image lands. Defaults to 0 (device: the OTA patch relocates the whole image to the cave at 0x004690, so offset 0 → 0x004690). For the Unicorn test harness, pass a NONZERO base (e.g. 0x100): the harness maps the image at FLASH_BASE=0 and starts with emu_start(begin, until=0), and Unicorn treats until=0 as 'stop when PC reaches 0'. With NEXT at offset 0, every branch-to-NEXT would hit PC=0 and halt immediately — so the test image needs NEXT at a nonzero absolute address. base shifts every placement + branch target uniformly, keeping the internal layout identical to the device image. """ def __init__(self, base=0): self.base = base self.asm = ThumbAsm() self.code = bytearray(0x1800) # working space (fits cave's 6.5KB) self.next_addr = 0x0000 # next free OFFSET (base added on placement) self.words = {} # name -> (addr, body_bytes) [absolute code addrs] # sources: name -> the ASM source string passed to add_code_word / # add_next, BEFORE 'b NEXT' is appended. Canonical home for the body # text of every code word, so tests import `kb.sources[name]` instead # of re-transcribing it (the root cause of the test/prod body drift: # the source was inline in the add_code_word call and discarded after # assembly). Recorded AFTER successful assembly so a bad source still # raises; pure addition — the assembled bytes (what ships) are # unchanged, this just retains the input that produced them. self.sources = {} self.dict_entries = [] # list of (name, code_addr, prev_entry_addr) # Colon/entry machinery (mirrors forth_hunt.ImageKit). cfa cells and # colon bodies are laid after all code words. entries: name -> cfa-cell # address (what EXECUTE/threads consume). colon_addrs: name -> colon # cfa-cell address (subset of entries that are colon words). self.entries = {} # name -> cfa-cell absolute address self.colon_addrs = {} # name -> colon cfa-cell absolute address # colon_bodies: name -> (body, labels) — the STRUCTURED IR BEFORE # flattening, retained for the static stack-effect checker # (src/stack_effect.py). body is a list of ('cell', val) | # ('br', (target_label, is_zero)); labels maps name -> body index. # Populated only by lay_colon callers that pass ir=(body, labels). self.colon_bodies = {} self._entry_region = None # set by lay_entries/lay_colon def add_code_word(self, name, body_source, addr=None, branch_to_next=True): """Add a machine-code primitive at a fixed or auto-assigned address. branch_to_next: append 'b NEXT' after the body. True for normal primitives that fall through to NEXT. False for words that end in their own control transfer (EXECUTE ends in bx r0; CALL ends in a manual b NEXT after IP restore). Mirrors forth_hunt.ImageKit.add. `addr` is an OFFSET within the image (base-relative). The body is assembled against its absolute address (self.base + addr) so any PC-relative internal branches encode correctly, and the trailing b NEXT targets NEXT's absolute address (self.base, since NEXT lives at offset 0). words[name] records the ABSOLUTE code address.""" if addr is None: # Align to 4 bytes, auto-assign self.next_addr = (self.next_addr + 3) & ~3 addr = self.next_addr abs_addr = self.base + addr body = assemble_body(body_source, base_addr=abs_addr) if branch_to_next: # Append branch to NEXT (absolute: self.base, at offset 0). branch = self.asm.b(self.base, abs_addr + len(body)) full = body + branch else: full = body self.code[addr:addr + len(full)] = full self.words[name] = (abs_addr, full) # Retain the pre-`b NEXT` source — canonical input for tests (see # self.sources docstring). branch_to_next's appended branch is a build # detail, not part of the word's semantics, so sources excludes it. self.sources[name] = body_source self.next_addr = max(self.next_addr, addr + len(full)) return abs_addr def add_next(self, addr=0x0000): """Install the threaded NEXT inner interpreter at offset `addr` (absolute: self.base + addr).""" next_src = ( "ldr.w r9, [r12]\n" "add.w r12, r12, #4\n" "ldr.w r0, [r9]\n" "bx r0\n" ) body = assemble_body(next_src, base_addr=self.base + addr) self.code[addr:addr + len(body)] = body self.words["NEXT"] = (self.base + addr, body) self.sources["NEXT"] = next_src self.next_addr = max(self.next_addr, addr + len(body)) return self.base + addr def build_all_primitives(self): """Build all Layer 0 primitives. NEXT and DOCOL are pinned at fixed offsets (0x0000 and 0x0010): DOCOL's address is load-bearing — the runtime compiler (':' primitive) embeds DOCOL|Thumb as colon words' code field, so DOCOL must not move. Every other Layer-0 word auto-spaces from `next_addr` (size-derived, the same scheme Layer 1 uses). This fixes a real latent bug: the old hand-fixed addresses (EXIT@0x18, KEY@0x1a8, ...) assumed 8-byte slots, but DOCOL is 14B and EMIT is 10B — so EXIT overlapped DOCOL and KEY overlapped EMIT. EXIT's first instruction clobbered DOCOL's `add r12,r9,#4` (the body-entry instruction), so DOCOL never set IP to the colon body and INTERPRET died instantly. Size-check-only __main__ never caught it; running the image did. Auto-spacing makes the bug class structurally impossible, matching the Layer-1 fix (handoff #3).""" # Inner interpreter — pinned at 0x0000. self.add_next(0x0000) # Threading — DOCOL pinned at 0x0010 (its addr is embedded by ':'). self.add_code_word("DOCOL", "sub.w r10, r10, #4\n" "str.w r12, [r10]\n" "add.w r12, r9, #4\n", addr=0x0010) # EXIT and everything below auto-space (addr=None → next aligned slot). self.add_code_word("EXIT", "ldr.w r12, [r10]\n" "add.w r10, r10, #4\n") # Literals self.add_code_word("LIT", "ldr.w r0, [r12]\n" "add.w r12, r12, #4\n" "sub.w r11, r11, #4\n" "str.w r0, [r11]\n") # Stack ops self.add_code_word("DROP", "add.w r11, r11, #4\n") self.add_code_word("DUP", "ldr.w r0, [r11]\n" "sub.w r11, r11, #4\n" "str.w r0, [r11]\n") self.add_code_word("SWAP", "ldrd r0, r1, [r11]\n" "strd r1, r0, [r11]\n") self.add_code_word("OVER", "ldrd r0, r1, [r11]\n" "str.w r1, [r11, #-4]!\n") self.add_code_word("ROT", "ldrd r0, r1, [r11]\n" # r0=TOS=c, r1=b "ldr.w r2, [r11, #8]\n" # r2=a (3rd) "strd r2, r0, [r11]\n" # [r11]=a, [r11+4]=c "str.w r1, [r11, #8]\n") # [r11+8]=b # Return-stack moves — foundational FORTH words, absent until now (the # kernel used PAD workarounds). >R/R> move a value between the data # stack (R11) and the return stack (R10), both growing DOWN. Bodies # lifted VERBATIM from test_r_stack_hunt.py (14 tests green, including # the balance invariant EXIT requires and the LIFO-reversal property # `.` exploits for digit buffering). Bug-A lesson: ship the hunted body. # DRAGON: the return stack holds the saved IP during a colon word, so # every >R MUST be balanced by an R> before EXIT — else EXIT pops a user # value as IP and jumps into garbage. Standard FORTH discipline; the # compiler enforces it for `:`, hand-built colon words hand-verify it. self.add_code_word(">R", "ldr.w r0, [r11]\n" "add.w r11, r11, #4\n" "sub.w r10, r10, #4\n" "str.w r0, [r10]\n") self.add_code_word("R>", "ldr.w r0, [r10]\n" "add.w r10, r10, #4\n" "sub.w r11, r11, #4\n" "str.w r0, [r11]\n") # Arithmetic — ldrd loads both operands in one insn (Thumb-2 ldrd is # 4B vs 2× ldr.w=8B); str.w pre-indexed pops+writes in one insn. # ARMv7-M permits word alignment for Thumb-2 ldrd/strd (the strict # 8-byte alignment check is an ARMv7-A MMU concern, not v7-M). self.add_code_word("+", "ldrd r0, r1, [r11]\n" "adds r0, r0, r1\n" "str.w r0, [r11, #4]!\n") self.add_code_word("-", "ldrd r0, r1, [r11]\n" "subs r0, r1, r0\n" "str.w r0, [r11, #4]!\n") # NEGATE ( n -- -n ) — 0 - n. Used by `.` to flip sign for magnitude. self.add_code_word("NEGATE", "movs r0, #0\n" "ldr.w r1, [r11]\n" "subs r0, r0, r1\n" "str.w r0, [r11]\n") # UM/MOD ( divisor dividend -- remainder quotient ), unsigned. # Software shift-subtract restoring division — the ATS2831 has no # hardware UDIV/SDIV (verified: zero occurrences in 1.18MB of Divoom's # own firmware). This is the one primitive `.` needs to peel decimal # digits: `10 SWAP UM/MOD` from ( mag -- ) gives ( rem quot ); rem is # the next digit, quot feeds the next iteration. # Body lifted VERBATIM from the proven test_divmod_hunt.py UMMOD_SRC # (17 tests + 200-example hypothesis sweep green) — Bug-A lesson: the # body that ships must be the body that was hunted. Register plan: # r0=dividend(→becomes quotient), r1=divisor, r2=remainder, r3=counter. # Dividend shifts FIRST so its MSB lands in C; rem's shift feeds that # C into rem's LSB (reversing this order was the first hunt bug — it # fed a stale carry in and produced 0 for nearly every input). # DIVIDE-BY-ZERO DRAGON (documented, not patched): divisor=0 → every # trial subtract of 0 "succeeds" (no borrow) → quotient=0xFFFFFFFF, # remainder=dividend. `.` only ever divides by the constant 10, so a # user can only hit this by hand-calling UM/MOD with 0. self.add_code_word("UM/MOD", "ldrd r0, r1, [r11]\n" "add.w r11, r11, #8\n" "movs r2, #0\n" "movs r3, #32\n" "_dv_loop:\n" "adds r0, r0, r0\n" "adcs r2, r2, r2\n" "subs.w r2, r2, r1\n" "bcc _dv_restore\n" "orr.w r0, r0, #1\n" "b _dv_next\n" "_dv_restore:\n" "add.w r2, r2, r1\n" "_dv_next:\n" "subs r3, r3, #1\n" "bne _dv_loop\n" "sub.w r11, r11, #4\n" "str.w r2, [r11]\n" "sub.w r11, r11, #4\n" "str.w r0, [r11]\n") # Memory self.add_code_word("@", "ldr.w r0, [r11]\n" "ldr.w r0, [r0]\n" "str.w r0, [r11]\n") self.add_code_word("!", "ldrd r0, r1, [r11]\n" "add.w r11, r11, #8\n" "str.w r0, [r1]\n") self.add_code_word("C@", "ldr.w r0, [r11]\n" "ldrb.w r0, [r0]\n" "str.w r0, [r11]\n") self.add_code_word("C!", "ldrd r0, r1, [r11]\n" "add.w r11, r11, #8\n" "strb.w r0, [r1]\n") # Comparison self.add_code_word("0=", "ldr.w r0, [r11]\n" "clz r0, r0\n" "lsr.w r0, r0, #5\n" "rsbs r0, r0, #0\n" "str.w r0, [r11]\n") self.add_code_word("0<", "ldr.w r0, [r11]\n" "asr.w r0, r0, #31\n" "str.w r0, [r11]\n") self.add_code_word("<", "ldrd r0, r1, [r11]\n" "cmp r1, r0\n" "sbc.w r0, r0, r0\n" "str.w r0, [r11, #4]!\n") # Control flow self.add_code_word("BRANCH", "ldr.w r0, [r12]\n" "add.w r12, r12, #4\n" "add.w r12, r12, r0\n") self.add_code_word("0BRANCH", "ldr.w r1, [r11]\n" "add.w r11, r11, #4\n" "ldr.w r0, [r12]\n" "add.w r12, r12, #4\n" "cmp r1, #0\n" "it eq\n" "addeq r12, r12, r0\n") # ── I/O ── buffer-backed KEY/EMIT. The stubs are gone: these are the # real primitives, ported from the proven bodies in test_io_and_dict.py # (EMIT) and test_key.py (KEY). EMIT appends TOS byte to OUTBUF and # bumps OUTLEN — the host/device drains OUTBUF when it wants. KEY reads # the next byte from its own KEYBUF triple (a char-at-a-time channel, # distinct from the token INPUT buffer WORD/INTERPRET drain) and pushes # it; when KEYBUF is empty KEY pushes -1 (0xFFFFFFFF) as a documented # "no byte available" sentinel — non-blocking in the simulator (Unicorn # can't block) and a clear spin-hook for the device. # SRAM LAYOUT (each buffer gets a 256B region with its len/idx cells # PAST it — same lesson as Dragon 3: putting KEYLEN at KEYBUF+4 makes # any ≥4-byte input overwrite the length. INPUT/INLEN already follows # this at +0x1000/+0x1100): OUTBUF +0x6000, OUTLEN +0x6100; # KEYBUF +0x6200, KEYLEN +0x6300, KEYIDX +0x6304. # OUTLEN/KEYIDX are reached by offset ([base,#0x100]/[base,#4]), not by # name, so they have no local — the canonical map is the S_* module # constants above. OUTBUF/KEYBUF/KEYLEN are named here because the # bodies reference them directly. OUTBUF = 0x00806000 KEYBUF = 0x00806200 KEYLEN = 0x00806300 # EMIT ( byte -- ) body lifted from test_io_and_dict.py:70-79. # OUTBUF@0x6000 and OUTLEN@0x6100 are 0x100 apart — load OUTBUF-base # once (r3) and reach OUTLEN via [r3,#0x100]. Saves a mov pair (8B). self.add_code_word("EMIT", f"""\ ldr.w r0, [r11] @ r0 = TOS (byte to emit) add.w r11, r11, #4 @ pop movw r3, #{OUTBUF & 0xFFFF} movt r3, #{(OUTBUF >> 16) & 0xFFFF} @ r3 -> OUTBUF (OUTLEN is [r3,#0x100]) ldr.w r2, [r3, #0x100] @ r2 = OUTLEN strb.w r0, [r3, r2] @ OUTBUF[OUTLEN] = byte adds r2, r2, #1 str.w r2, [r3, #0x100] @ OUTLEN++ """) # KEY ( -- byte | -1 ) body lifted from test_key.py:58-67 + sentinel. # KEYLEN@0x6300 and KEYIDX@0x6304 are consecutive — load KEYLEN-base # once (r2) and reach both. Saves a mov pair (8B). self.add_code_word("KEY", f"""\ movw r2, #{KEYLEN & 0xFFFF} movt r2, #{(KEYLEN >> 16) & 0xFFFF} @ r2 -> KEYLEN (KEYIDX is [r2,#4]) ldr.w r3, [r2] @ r3 = KEYLEN ldr.w r1, [r2, #4] @ r1 = KEYIDX cmp r1, r3 bge _k_empty @ KEYIDX >= KEYLEN -> push -1 movw r5, #{KEYBUF & 0xFFFF} movt r5, #{(KEYBUF >> 16) & 0xFFFF} ldrb.w r3, [r5, r1] @ r3 = KEYBUF[KEYIDX] adds r1, r1, #1 str.w r1, [r2, #4] @ KEYIDX++ b _k_push _k_empty: mov.w r3, #-1 @ sentinel: no byte available _k_push: sub.w r11, r11, #4 str.w r3, [r11] @ push byte (or -1) """) return self def build_layer1_primitives(self): """Layer 1 primitives: EXECUTE, NUMBER, the compiler (CREATE/,/:/;), and CALL/DUMP. These were each hunted in test/test_*_hunt.py and proven against the threaded NEXT model. Addresses auto-assign from where build_all_primitives left off. SRAM layout (matches the hunt library + dictionary.py): LATEST @ RAM_BASE+0x3000, DP @ +0x3004, STATE @ +0x3008 PAD @ +0x5000, OUTBUF @ +0x6000, IPSAVE @ +0x7000 (CALL scratch) INPUT @ +0x1000 (256B buffer), INLEN @ +0x1100, INIDX @ +0x1104 (INLEN/INIDX moved past the buffer — see the hunt docs: the old +0x1008 sat INSIDE the buffer and any input >8B clobbered INLEN.) NOTE: DOCOL is pinned at offset 0x0010 (load-bearing — ':' embeds its addr as colon words' code field). EXIT auto-spaces past DOCOL. Both addresses are COMPUTED from self.words (DOCOL_CODE/EXIT_CODE below) so ':' and ';' stay correct regardless of where EXIT lands. The runtime dictionary entry for EXIT is built later, so ';' writes EXIT's code address (Thumb-set) as the literal it compiles.""" LATEST = 0x00803000 DP = 0x00803004 PAD = 0x00805000 OUTBUF = 0x00806000 IPSAVE = 0x00807000 INPUT = 0x00801000 INLEN = 0x00801100 # DOCOL/EXIT code addresses, COMPUTED from the laid-out words (not # hardcoded). Hardcoding 0x0011/0x0019 was a latent bug: it assumed # EXIT@0x18, but EXIT auto-spaces past DOCOL now. Deriving from # self.words keeps ':' and ';' correct regardless of layout. DOCOL_CODE = self.words["DOCOL"][0] | 1 # DOCOL addr, Thumb bit set EXIT_CODE = self.words["EXIT"][0] | 1 # EXIT addr, Thumb bit set def mov(addr, reg=1): return (f"movw r{reg}, #{addr & 0xFFFF}\n" f"movt r{reg}, #{(addr >> 16) & 0xFFFF}\n") # ── EXECUTE ── ends in bx r0 (NO b NEXT). r9 invariant. self.add_code_word("EXECUTE", "ldr.w r9, [r11]\n" "add.w r11, r11, #4\n" "ldr.w r0, [r9]\n" "bx r0\n", branch_to_next=False) # ── NUMBER ── parse PAD counted string, push (value flag). ~46B. self.add_code_word("NUMBER", f"""\ {mov(PAD)} @ r1 -> PAD ldrb.w r2, [r1] @ r2 = length adds r1, r1, #1 @ r1 = first char movs r0, #0 @ accumulator movs r3, #0 @ index movs r5, #0 @ flag (guilty until proven) _n_loop: cmp r3, r2 bge _n_ok ldrb.w r4, [r1, r3] cmp r4, #0x30 blt _n_fail cmp r4, #0x39 bgt _n_fail sub.w r4, r4, #0x30 add.w r0, r0, r0, lsl #2 add.w r0, r0, r0 add.w r0, r0, r4 adds r3, r3, #1 b _n_loop _n_ok: cmp r2, #0 beq _n_fail mov.w r5, #-1 _n_fail: @ push ( value, flag ) via strd double-push (4B vs 12B for 2× sub/str). @ strd Rt,Ra,[Rn,#-8]! stores Rt→[new Rn](TOS), Ra→[Rn+4]. So the FIRST @ operand lands at TOS. Contract is ( value flag ) = flag on top, so r5 @ (flag) is the first operand, r0 (value) the second. strd r5, r0, [r11, #-8]! """) # ── CREATE ── lay a dict header at DP, link to LATEST, update LATEST. # LATEST@0x3000 and DP@0x3004 are consecutive — load LATEST-base once # into r7 (free until the pad loop reuses it) and reach DP via [r7,#4]. # Saves 3× mov pairs (24B) vs reloading each address every reference. self.add_code_word("CREATE", f"""\ {mov(LATEST, 7)} @ r7 -> LATEST (DP is [r7,#4]) ldr.w r2, [r7, #4] @ r2 = current DP mov r8, r2 @ r8 = new entry addr ldr.w r3, [r7] @ r3 = current LATEST str.w r3, [r2] @ header[0] = link adds r2, r2, #4 {mov(PAD, 1)} @ r1 -> PAD ldrb.w r3, [r1] @ r3 = name length strb.w r3, [r2] @ namelen adds r2, r2, #1 adds r4, r1, #1 @ r4 = PAD+1 movs r5, #0 _c_copy: cmp r5, r3 bge _c_pad ldrb.w r6, [r4, r5] strb.w r6, [r2] adds r2, r2, #1 adds r5, r5, #1 b _c_copy _c_pad: adds r6, r2, #3 bic r6, r6, #3 cmp r2, r6 beq _c_late movs r0, #0 strb.w r0, [r2] adds r2, r2, #1 b _c_pad _c_late: str.w r2, [r7, #4] @ DP = code-field slot str.w r8, [r7] @ LATEST = new entry """) # ── , (COMMA) ── write TOS to [DP], DP += 4, pop. self.add_code_word(",", f"""\ {mov(DP)} ldr.w r2, [r1] ldr.w r0, [r11] str.w r0, [r2] adds r2, r2, #4 str.w r2, [r1] add.w r11, r11, #4 """) # ── : (COLON) ── assumes CREATE just ran (DP at code-field slot): # write DOCOL|Thumb as code field, advance DP to body, STATE=1. # DP@0x3004 and STATE@0x3008 are consecutive — hold DP-base in r4 # (free in this body) so STATE is [r4,#4]; saves 2× mov pairs vs # reloading DP/STATE each reference. self.add_code_word(":", f"""\ {mov(DP, 4)} @ r4 -> DP (STATE is [r4,#4]) ldr.w r2, [r4] @ r2 = code-field slot {mov(DOCOL_CODE)} str.w r1, [r2] @ code field = DOCOL|Thumb adds r2, r2, #4 str.w r2, [r4] @ DP = body start movs r3, #1 str.w r3, [r4, #4] @ STATE = 1 """) # ── ; (SEMICOLON) ── compile EXIT code-field ref, STATE=0. # Same DP/STATE adjacency — hold DP-base in r4. self.add_code_word(";", f"""\ {mov(DP, 4)} @ r4 -> DP (STATE is [r4,#4]) ldr.w r2, [r4] {mov(EXIT_CODE)} str.w r1, [r2] @ [DP] = EXIT code ref adds r2, r2, #4 str.w r2, [r4] movs r3, #0 str.w r3, [r4, #4] @ STATE = 0 """) # ── CALL ── pop target, save IP across BLX, restore, b NEXT. # IP (r12) is caller-saved per AAPCS, so firmware WILL clobber it. We # stash it in a fixed SRAM cell (IPSAVE) for the duration of the call. # # The scratch register addressing the cell MUST be reloaded AFTER the # BLX, not held across it: r0-r3 are caller-saved, so a real firmware # function is free to clobber r2. Holding r2 across the call (the # original design) works only because the trophy stub clobbers r12 but # not r2 — a false sense of security. An r2-clobbering stub crashes # CALL (ldr r12,[r2] reads garbage → fault). The movw/movt pair encodes # the immediate, so reloading it after BLX is immune to any caller-saved # clobber. r4 (callee-saved) is free in our r9-r12 convention too, but # we don't rely on that convention — the reload is unconditionally safe. # +4B over the single-load version; 5276B headroom absorbs it. self.add_code_word("CALL", f"""\ ldr.w r0, [r11] add.w r11, r11, #4 {mov(IPSAVE, 2)} str.w r12, [r2] @ save IP (r12 caller-saved; firmware clobbers it) blx r0 {mov(IPSAVE, 2)} ldr.w r12, [r2] @ reload scratch addr (caller-saved) then restore IP """) # b NEXT appended by default # ── DUMP ── ( addr len -- ): hex bytes addr..addr+len to OUTBUF. # The nibble→hex conversion is the size hotspot: it ran twice (high # then low nibble) as a 5-insn cmp/blt/add#55/b/add#48 ladder. Saved # 12B by switching to add-#48-then-conditionally-add-#7: '0'..'9' map # with just the +48, and the 'a'-'9' gap (7) is added only when the # +48 result reaches 0x3A ('9'+1). 4 insns/nibble vs 5, ×2 nibbles. self.add_code_word("DUMP", f"""\ ldr.w r3, [r11] @ len add.w r11, r11, #4 ldr.w r2, [r11] @ addr add.w r11, r11, #4 {mov(OUTBUF, 4)} @ r4 = write ptr movs r5, #0 _d_loop: cmp r5, r3 bge _d_done ldrb.w r6, [r2, r5] lsr.w r7, r6, #4 add.w r7, r7, #48 @ high nibble -> '0'..'?' ('0'+nibble) cmp r7, #58 @ past '9'? blt _d_hout add.w r7, r7, #7 @ close the 'a'-'9' gap -> 'a'..'f' _d_hout: strb.w r7, [r4] adds r4, r4, #1 and.w r7, r6, #15 add.w r7, r7, #48 @ low nibble -> '0'..'?' cmp r7, #58 blt _d_lout add.w r7, r7, #7 _d_lout: strb.w r7, [r4] adds r4, r4, #1 adds r5, r5, #1 b _d_loop _d_done: movs r7, #0 strb.w r7, [r4] """) # ── WORD ── skip spaces, copy next token to PAD[1..], PAD[0]=len. # Was two separate loops (_w_skip + _w_copy) that each duplicated the # bounds-check + delimiter-read. Merged into one scan loop: r4 (token # length) doubles as the in-token flag — 0 means still skipping leading # spaces, >0 means copying a token. A space with r4==0 is skipped; a # space with r4>0 ends the token. One bounds check, one char read. # SRAM addrs match the hunt layout (test_word_find_hunt.WORD_SRC). # INLEN@0x1100 / INIDX@0x1104 are consecutive — load INLEN-base once # (r0) and reach INIDX via [r0,#4]. PAD-base recovery: r3 ends at # PAD+1, so `subs r3,#1` recovers PAD (4B vs 8B reload). self.add_code_word("WORD", f"""\ {mov(INLEN, 0)} @ r0 -> INLEN (INIDX is [r0,#4]) ldr.w r5, [r0] @ r5 = INPUT_LEN ldr.w r1, [r0, #4] @ r1 = INPUT_IDX {mov(INPUT, 6)} @ r6 -> INPUT_BUF {mov(PAD, 3)} @ r3 -> PAD adds r3, r3, #1 @ r3 = PAD+1 (write pos) movs r4, #0 @ r4 = token length (0 = still skipping spaces) _w_scan: cmp r1, r5 bge _w_done ldrb.w r2, [r6, r1] cmp r2, #0x20 beq _w_space strb.w r2, [r3] @ non-space: copy into PAD adds r3, r3, #1 adds r4, r4, #1 adds r1, r1, #1 b _w_scan _w_space: cmp r4, #0 bne _w_done @ in-token space -> token ends adds r1, r1, #1 @ leading space -> skip b _w_scan _w_done: str.w r1, [r0, #4] @ save updated INPUT_IDX @ r3 ended at PAD+1+len (write pos); r4=len. PAD-base = r3-len, then -1. sub.w r3, r3, r4 @ r3 = PAD+1 strb.w r4, [r3, #-1] @ PAD[0] = token length """) # ── FIND ── walk LATEST, match PAD counted string; push (cfa -1) | (0). # Ported verbatim from test_word_find_hunt.FIND_SRC. The TERMINATOR # dragon: both found/miss paths converge on _find_done and # branch_to_next=True appends a correct absolute b NEXT (NOT a literal # `b 0x100`, which clang encodes as a PC-relative offset = wrong). self.add_code_word("FIND", f"""\ {mov(LATEST, 7)} @ r7 -> LATEST var ldr.w r0, [r7] @ r0 = current entry (walk from LATEST) {mov(PAD, 1)} @ r1 -> PAD ldrb.w r2, [r1] @ r2 = PAD token length adds r7, r1, #1 @ r7 = PAD+1 base (r7 free after the LATEST @ load above; HOISTED out of _f_cmp where @ add.w r6,r1,#1 was recomputed every char) _f_loop: cmp r0, #0 beq _f_notfound ldrb.w r3, [r0, #4] @ r3 = entry name length cmp r3, r2 bne _f_next movs r4, #0 @ compare index _f_cmp: cmp r4, r3 bge _f_found add.w r5, r0, #5 @ r5 = entry name ptr ldrb.w r5, [r5, r4] ldrb.w r6, [r7, r4] @ PAD+1 char via hoisted base cmp r5, r6 bne _f_next adds r4, r4, #1 b _f_cmp _f_next: ldr.w r0, [r0] @ follow link b _f_loop _f_found: @ r0 = entry address. cfa = entry + 4 + 1 + namelen, padded to 4. @ Tightened: was 5 insns (add#4; adds#1; adds r3; adds#3; bic) → 4 @ (add#5; add r3; add#3; bic). entry+5+namelen, then round up to 4. add.w r8, r0, #5 @ entry + 4 + 1 add.w r8, r8, r3 @ + namelen add.w r9, r8, #3 bic r8, r9, #3 @ pad to 4 @ push ( cfa, -1 ) via strd double-push (4B vs 16B for 2× sub/str pairs). @ strd Rt,Ra,[Rn,#-8]! stores Rt→[new Rn](TOS), Ra→[Rn+4]. Contract is @ ( cfa -1 ) = -1 on top, so r6 (-1) is the FIRST operand, r8 (cfa) second. mov.w r6, #-1 strd r6, r8, [r11, #-8]! b _find_done @ converge — b NEXT appended below _f_notfound: sub.w r11, r11, #4 movs r6, #0 str.w r6, [r11] @ push 0 (miss flag; cfa slot absent) _find_done: """) # ── REFILL ─ the delivery-agnostic seam. QUIT (below) calls REFILL # before each INTERPRET to move bytes from the char-input channel into # the token buffer WORD scans. REFILL copies KEYBUF[0..KEYLEN-1] into # INPUT, sets INLEN=KEYLEN + INIDX=0 (the contract write_input gives # WORD), then drains KEYBUF (KEYLEN=0, KEYIDX=0) so the next REFILL # reads fresh bytes. In the simulator the harness pre-fills KEYBUF; on # device THIS BODY is the one thing that swaps — to a CALL into the # firmware's SPP RX routine that fills KEYBUF directly. Same SRAM # contract, different source. No other primitive changes for live I/O. # INPUT +0x1000 (256B), INLEN +0x1100, INIDX +0x1104 (build_all_primitives). KEYBUF_R = 0x00806200 KEYLEN_R = 0x00806300 # KEYIDX is KEYLEN_R + 4 (consecutive) self.add_code_word("REFILL", f"""\ {mov(KEYLEN_R, 0)} @ r0 -> KEYLEN (KEYIDX is [r0,#4]; held throughout) ldr.w r3, [r0] @ r3 = KEYLEN (copy count) {mov(KEYBUF_R, 1)} @ r1 -> KEYBUF (src) {mov(INPUT, 2)} @ r2 -> INPUT (dst) movs r4, #0 @ r4 = i _r_loop: cmp r4, r3 bge _r_done ldrb.w r5, [r1, r4] @ r5 = KEYBUF[i] strb.w r5, [r2, r4] @ INPUT[i] = KEYBUF[i] adds r4, r4, #1 b _r_loop _r_done: {mov(INLEN, 6)} @ r6 -> INLEN (INIDX is [r6,#4]) str.w r3, [r6] @ INLEN = KEYLEN movs r5, #0 str.w r5, [r6, #4] @ INIDX = 0 str.w r5, [r0] @ KEYLEN = 0 (drain — next REFILL reads fresh) str.w r5, [r0, #4] @ KEYIDX = 0 """) return self # ── HALT ──────────────────────────────────────────────────────────── def add_halt(self): """Install HALT as a `b .` spin (infinite loop) at an auto-assigned code address, then lay its cfa cell so threads can name it. The trapnet's reached_halt check looks for PC at the spin address. Exposes self.halt_cfa (the cfa-cell address for threads) and self.halt_spin (the raw code address, for reached_halt comparison).""" # Pick an aligned OFFSET past everything laid so far. off = (self.next_addr + 3) & ~3 spin = self.asm.b_self() self.code[off:off + len(spin)] = spin spin_abs = self.base + off self.words["HALT"] = (spin_abs, spin) self.next_addr = max(self.next_addr, off + len(spin)) self.halt_spin = spin_abs # Lay the cfa cell right after the spin (offset-indexed in code[]). cfa_off = (self.next_addr + 3) & ~3 struct.pack_into('R/R> (LIFO reversal for correct print order), EMIT, 0BRANCH. No inlined loops, no register juggling — the watchmaker composition. ALGORITHM (the body mirrors the proven test_dot_hunt.build_dot_image; Bug-A lesson: ship the hunted body): DUP 0< IF '-' EMIT NEGATE THEN sign DUP 0= IF '0' EMIT ELSE special-case 0 256 >R sentinel (never a digit) BEGIN DUP WHILE peel while quotient ≠ 0 10 SWAP UM/MOD SWAP >R digit → rstack (LSB first) REPEAT DROP BEGIN R> DUP 256 <> WHILE pop until sentinel (MSB first) 48 + EMIT digit → ASCII, emit REPEAT DROP THEN 32 EMIT trailing space SENTINEL discipline: 256 pushed before peeling, 256+digits all popped before EXIT — every >R balanced. EXIT-safe (no rstack residue that EXIT would misread as IP). Hunted in test_dot_hunt.py (13 tests green, incl. the rstack-balanced invariant). Requires: build_layer1_primitives has laid UM/MOD, >R, R>, EMIT, etc. Sets self.dot_cfa.""" needed = ["DUP", "0<", "0=", "LIT", "EMIT", "NEGATE", ">R", "R>", "UM/MOD", "SWAP", "DROP", "+", "-", "0BRANCH", "BRANCH", "EXIT"] for n in needed: if n not in self.entries: self.lay_entry(n) E = self.entries # Char/sentinel constants (match the hunt). MINUS = 0x2D # '-' ZERO = 0x30 # '0' SPACE = 0x20 # trailing space SENT = 256 # sentinel (> 9, never a digit value) body = [] labels = {} def cell(v): body.append(('cell', v)); return len(body) - 1 def branch_cell(target_label, is_zero): body.append(('br', (target_label, is_zero))); return len(body) - 1 def label(nm): labels[nm] = len(body) # : . ( n -- ) STACK DISCIPLINE: 0BRANCH POPS its flag. Every cell's # depth effect annotated, consistent on every branch path. cell(E['DUP']); cell(E['0<']) # DUP 0< ( n f ) d=2 cell(E['0BRANCH']); branch_cell('pos', True) # POP f; if 0 skip d=1 cell(E['LIT']); cell(MINUS); cell(E['EMIT']) # '-' EMIT ( n ) d=1 cell(E['NEGATE']) # NEGATE ( |n| ) d=1 label('pos') # ( mag ) d=1 cell(E['DUP']); cell(E['0=']) # DUP 0= ( mag f ) d=2 cell(E['0BRANCH']); branch_cell('peel', True) # POP f; if 0 skip d=1 cell(E['LIT']); cell(ZERO); cell(E['EMIT']) # '0' EMIT ( mag ) d=1 cell(E['BRANCH']); branch_cell('space', False) # -> space ( mag ) d=1 label('peel') # ( mag ) d=1 cell(E['LIT']); cell(SENT); cell(E['>R']) # 256 >R ( mag ) d=1 R:256 label('peel_loop') # ( q ) d=1 cell(E['DUP']) # DUP ( q q ) d=2 cell(E['0BRANCH']); branch_cell('peel_done', True) # POP q; if 0 -> done d=1 cell(E['LIT']); cell(10) # 10 ( q 10 ) d=2 cell(E['SWAP']); cell(E['UM/MOD']) # SWAP UM/MOD( rem q' )d=2 cell(E['SWAP']); cell(E['>R']) # SWAP >R ( q' ) d=1 R:+digit cell(E['BRANCH']); branch_cell('peel_loop', False) # loop ( q' ) d=1 label('peel_done') # ( 0 ) d=1 cell(E['DROP']) # DROP ( -- ) d=0 R:digits label('emit_loop') # ( -- ) d=0 cell(E['R>']) # R> ( x ) d=1 cell(E['DUP']) # DUP ( x x ) d=2 cell(E['LIT']); cell(SENT) # 256 ( x x 256)d=3 cell(E['-']) # - ( x x-256)d=2 cell(E['0=']) # 0= ( x f ) d=2 f=-1 if sentinel cell(E['0BRANCH']); branch_cell('emit_digit', True) # POP f; f==0(digit)->branch; f=-1(sentinel)->fallthrough cell(E['DROP']) # DROP ( -- ) d=0 (sentinel path) cell(E['BRANCH']); branch_cell('space', False) # -> space label('emit_digit') # ( x ) d=1 cell(E['LIT']); cell(ZERO); cell(E['+']); cell(E['EMIT']) # '0' + EMIT( -- ) d=0 cell(E['BRANCH']); branch_cell('emit_loop', False) # loop label('space') # ( -- ) d=0 R:empty cell(E['LIT']); cell(SPACE); cell(E['EMIT']) # ' ' EMIT ( -- ) d=0 cell(E['EXIT']) cells = [] for i, item in enumerate(body): if item[0] == 'cell': cells.append(item[1]) else: target_label, _ = item[1] target_idx = labels[target_label] off = (target_idx - (i + 1)) * 4 cells.append(off & 0xFFFFFFFF) self.dot_cfa = self.lay_colon(".", cells, ir=(body, labels)) return self.dot_cfa def stats(self): """Print kernel size statistics.""" used = self.next_addr print(f"Kernel image: {used}B / 6512B ({used*100//6512}%)") print(f"Code words: {len(self.words)} Colon words: {len(self.colon_addrs)}") print(f"Headroom: {6512 - used}B") if hasattr(self, "interpret_cfa"): print(f"INTERPRET colon @ 0x{self.interpret_cfa:04x}") if hasattr(self, "halt_cfa"): print(f"HALT spin @ 0x{self.halt_spin:04x} (cfa 0x{self.halt_cfa:04x})") return used if __name__ == "__main__": kb = KernelBuilder() kb.build_all_primitives() kb.build_layer1_primitives() kb.add_halt() kb.build_interpret() kb.build_quit() kb.stats() print() for name in sorted(kb.words.keys()): addr, body = kb.words[name] print(f" {name:<8} @ 0x{addr:04x} ({len(body)}B)") print() for name in sorted(kb.colon_addrs.keys()): print(f" :{name:<8} @ 0x{kb.colon_addrs[name]:04x} (colon word)")