Something went wrong. Try again.
Something went wrong. Try again.
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087"""kernel_builder.py — Assembles the complete FORTH kernel image.
Takes all Layer 0 primitives (clang-assembled, individually tested) andlays them out in memory at fixed addresses, building a linked dictionarythat Layer 1 FORTH words can search.
Output: a single .bin file that goes in the code cave at 0x004690."""import structfrom src.clang_asm import assemble_bodyfrom 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 = 0x00800000S_LATEST = RAM_BASE + 0x3000 # dict head pointerS_DP = RAM_BASE + 0x3004 # dictionary pointer (free dict region)S_STATE = RAM_BASE + 0x3008 # interpret/compile flagS_DICT = RAM_BASE + 0x4000 # free dict region (DP's home base)S_PAD = RAM_BASE + 0x5000 # scratch / token bufferS_OUTBUF = RAM_BASE + 0x6000 # EMIT accumulates TOS bytes hereS_OUTLEN = RAM_BASE + 0x6100 # OUTBUF byte countS_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 countS_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('<I', self.code, cfa_off, spin_abs | 1) cfa_abs = self.base + cfa_off self.entries["HALT"] = cfa_abs self.halt_cfa = cfa_abs self.next_addr = max(self.next_addr, cfa_off + 4) return self
# ── colon / entry machinery (mirrors forth_hunt.ImageKit) ─────────── def lay_entry(self, name): """Lay a single cfa cell = (words[name] addr | 1) at the next aligned image OFFSET. The cell value is the ABSOLUTE code address (Thumb-set). Records entries[name] = ABSOLUTE cfa address (what EXECUTE consumes and colon-body cells reference).""" if name not in self.words: raise KeyError(f"lay_entry: no code word named {name!r}") off = (self.next_addr + 3) & ~3 code_addr = self.words[name][0] # already absolute struct.pack_into('<I', self.code, off, code_addr | 1) cfa_abs = self.base + off self.entries[name] = cfa_abs self.next_addr = max(self.next_addr, off + 4) return cfa_abs
def lay_colon(self, name, body_cells, ir=None): """Lay a colon word: cfa cell = DOCOL|1 (absolute DOCOL addr), then body cells (each a u32: an absolute cfa/entry address or a literal). Records entries[name] + colon_addrs[name] = ABSOLUTE cfa address.
body_cells: list of u32 values, already-resolved (absolute entry addresses or literals like S_PAD / a branch offset). The caller resolves branch offsets against cell positions BEFORE calling this.
ir: optional (body, labels) — the structured IR the caller built BEFORE flattening to body_cells. Retained in self.colon_bodies[name] for the static stack-effect checker. None = not retained (callers that don't pass it simply aren't checked).""" if ir is not None: body_ir, labels_ir = ir self.colon_bodies[name] = (list(body_ir), dict(labels_ir)) off = (self.next_addr + 3) & ~3 docol_thumb = self.words["DOCOL"][0] | 1 # DOCOL absolute addr | Thumb struct.pack_into('<I', self.code, off, docol_thumb) cur = off + 4 for cell in body_cells: struct.pack_into('<I', self.code, cur, cell & 0xFFFFFFFF) cur += 4 cfa_abs = self.base + off self.entries[name] = cfa_abs self.colon_addrs[name] = cfa_abs self.next_addr = max(self.next_addr, cur) return cfa_abs
# ── INTERPRET ── the colon word the whole architecture builds toward ── def build_interpret(self): """Build INTERPRET as a colon word referencing kernel-map cfas.
The body is the corrected, trapnet-proven sequence from test_interpret_colon_hunt.build_interpret_image: WORD/LIT/C@/0=/0BRANCH loop, FIND-or-NUMBER dispatch, no stray DROPs (0BRANCH pops the flag it tests). Branch offsets are CELL-INDEX-relative — `off = (target_idx - (i+1)) * 4` — so they're identical regardless of memory map. Only the CFA references are regenerated to this builder's entries[...].
Requires: all primitives the body names are already laid as entries (call lay_entry for each). Sets self.interpret_cfa.""" # Primitives the body references, as cfa cells. Lay them now if not # already present (idempotent: lay_entry overwrites the recorded addr, # but we skip if already laid to keep addresses stable). needed = ["WORD", "LIT", "C@", "0=", "0BRANCH", "EXIT", "FIND", "EXECUTE", "BRANCH", "NUMBER", "DROP"] for n in needed: if n not in self.entries: self.lay_entry(n) E = self.entries
# Build the body symbolically with label/branch placeholders, then # resolve. Identical structure to the proven hunt version. body = [] # ('cell', val) | ('br', (label, is_zero)) 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)
# S_PAD — the address NUMBER reads from / WORD writes to. Matches the # hunt layout (RAM_BASE + 0x5000); declared locally to keep this body # self-contained against future SRAM-layout drift. S_PAD = 0x00805000
# : INTERPRET # STACK DISCIPLINE: 0BRANCH POPS its flag (does not peek). Every cell's # effect is annotated with the resulting depth, consistent on every # branch path. The trapnet (assert_clean) verifies this each run. label('loop') cell(E['WORD']) # WORD ( -- ) d=0 cell(E['LIT']); cell(S_PAD) # LIT PAD ( -- pad ) d=1 cell(E['C@']) # C@ ( -- len ) d=1 cell(E['0=']) # 0= ( -- flag ) d=1 cell(E['0BRANCH']); branch_cell('not_empty', True) # POP flag cell(E['EXIT']) label('not_empty') cell(E['FIND']) # ( -- cfa -1 ) | ( -- 0 ) cell(E['0BRANCH']); branch_cell('try_number', True) # POP flag cell(E['EXECUTE']) # found: POP cfa, run d=0 cell(E['BRANCH']); branch_cell('loop', False) label('try_number') # miss path: empty stack (0BRANCH popped the 0). NO stray DROP. cell(E['NUMBER']) # ( -- value flag ) cell(E['0BRANCH']); branch_cell('skip', True) # POP flag cell(E['BRANCH']); branch_cell('loop', False) # valid: loop w/ value label('skip') # garbage path: NUMBER left ( -- value ). Drop the ONE value. cell(E['DROP']) cell(E['BRANCH']); branch_cell('loop', False)
# Resolve branch offsets (cell-index-relative, map-independent) + flatten. 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 # IP already past offset cell cells.append(off & 0xFFFFFFFF)
self.interpret_cfa = self.lay_colon("INTERPRET", cells, ir=(body, labels)) return self.interpret_cfa
# ── QUIT ── the outer prompt loop, the kernel's entry point ────────── def build_quit(self): """Build QUIT as a colon word: the outer interpreter loop.
INTERPRET (above) drains the token buffer until WORD returns an empty token, then EXITs — it does NOT re-arm itself or refill input. QUIT is the layer above it that turns one-shot INTERPRET into a live prompt: REFILL move KEYBUF bytes into INPUT, set INLEN/INIDX ( -- ) INTERPRET drain INPUT token by token until empty → EXIT ( -- ) BRANCH →quit loop forever REFILL is the single delivery-agnostic seam: in the simulator the harness pre-fills KEYBUF; on device REFILL's body swaps to a CALL into the firmware SPP RX routine. No other primitive changes for live I/O.
Requires: build_interpret() has run (sets self.interpret_cfa) and REFILL is laid as a code word (build_layer1_primitives). Sets self.quit_cfa — the kernel ENTRY POINT (what a reset vector / exploit payload jumps to).""" needed = ["REFILL"] for n in needed: if n not in self.entries: self.lay_entry(n) if "INTERPRET" not in self.colon_addrs: raise RuntimeError("build_quit: call build_interpret() first") E = self.entries # INTERPRET's cfa is a colon-word cfa (DOCOL-prefixed); use the same # entry address the colon machinery recorded. interp_cfa = self.colon_addrs["INTERPRET"]
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)
# : QUIT ( -- , loops forever ) label('quit') cell(E['REFILL']) # REFILL ( -- ) refill INPUT from KEYBUF cell(interp_cfa) # INTERPRET ( -- ) drain INPUT until empty → EXIT cell(E['BRANCH']); branch_cell('quit', False) # loop forever
# Resolve branch offsets (cell-index-relative, map-independent). 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.quit_cfa = self.lay_colon("QUIT", cells, ir=(body, labels)) return self.quit_cfa
# ── DOT (.) ── print signed decimal. THE DEMO WORD ────────────────── def build_dot(self): """Build . (DOT) as a colon word: print TOS as signed-decimal ASCII to OUTBUF, followed by a trailing space.
. ( n -- )
This is the visible-output word — without it `3 4 +` leaves 7 silently on the stack; `3 4 + .` sends '7 ' to OUTBUF (drained to SPP by the shim). Composes only proven primitives via threaded NEXT: UM/MOD (digit peel), >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)")