Something went wrong. Try again.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314"""stack_effect.py — Static stack-effect checker for colon words.
THE WHY: The trapnet (src/harness.py) catches stack bugs DYNAMICALLY: a stray DROP must actually execute on an input that hits the underflowing branch before the underflow guard fires. Dragon 2 (README.md §"The dragon encyclopedia") survived because no test input exercised the buggy branch — three stray DROPs took the data stack to depth -1, but the tests asserted only on the final stack value.
This module is the STATIC net: walk a colon word's structured body IR and prove stack depth is consistent on EVERY branch path, BEFORE execution. It is a cheap hand-derived type-soundness check (Progress: no primitive pops deeper than the stack has; Preservation: every path through a branch lands at the target label at the same depth; the EXIT invariant: data and return stacks are balanced when control leaves the word).
THE INPUT (the structured IR the builder retains in kb.colon_bodies[name]): body list of ('cell', cfa_int) | ('br', (target_label, is_zero)) labels {label_name: body_index} entries_by_cfa {cfa_int: word_name} — resolves a cell value to its word effect_table {word_name: (d_pop, d_push, r_pop, r_push)} — signed effect
THE ALGORITHM: Forward walk, tracking (data_depth, rstack_depth) as integers. Cell index is the program point. At a branch source, record the depth at the target label; the FIRST path to a label establishes the expected depth, every later arriving path must agree (branch-merge-mismatch otherwise). Linear fall-through into a labeled position counts as an arriving path too. EXIT requires data_depth == 0 and rstack_depth == 0 relative to entry.
LIT/BRANCH/0BRANCH each consume the immediately-following cell as DATA (a literal value or a branch offset), not as an opcode — the walker skips it. 0BRANCH additionally pops one data flag (the Dragon-2 root cause).
LIMITATIONS (deliberate, documented not patched — the boundary between thisstatic net and the runtime trapnet): - Conditional effects (FIND returns 1 OR 2 cells; NUMBER pushes 2 OR faults) are modeled by their MAX push count and the documented pop count. A word whose runtime behavior diverges from its declared effect is the trapnet's job to catch, not this checker's. The two nets compose; they don't replace each other. - VARIABLE-ITERATION LOOPS that push/pop the stacks a net-zero but input-dependent number of times (DOT's >R/R> digit-reversal: push N digits + 1 sentinel, pop N+1) are NOT soundly checkable by an integer-depth worklist — the worklist can't unroll the loop, so it reports a false positive at EXIT. The runtime trapnet (test_r_stack_hunt.py) proves the balance on real inputs; that is the sound check for this class. The DOT test is xfailed with this reason. Widening to an abstract-depth lattice (sign/zero) would close this; documented as future work, not patched here. - No termination proof (QUIT loops forever by design — not a bug). - Code words (machine-code primitives) are out of scope; they're individually hunted in assembly with edge-case + property tests."""from dataclasses import dataclass
@dataclass(frozen=True)class Violation: """One stack-effect violation found by check_colon.""" cell_index: int # index into body where the violation is detected kind: str # 'underflow' | 'unbalanced-exit' | 'branch-merge-mismatch' depth: int # the offending data-stack depth (or rstack if rstack_kind) message: str # human-readable, names the word/label involved
def __str__(self): return (f"[{self.cell_index}] {self.kind} (d={self.depth}): " f"{self.message}")
# Primitives whose body cell is followed by an inline DATA cell (a literal or# a branch offset) that the walker must skip rather than treat as an opcode.# LIT pushes the inline value; BRANCH/0BRANCH read the inline offset. The# inline cell has NO stack effect of its own._DATA_AFTER = {"LIT", "BRANCH", "0BRANCH"}
# ── Canonical stack-effect table (the type-signature source of truth) ────# (d_pop, d_push, r_pop, r_push) for every primitive/colon word the checker# may encounter. Hand-derived from the ( -- ) stack-comments in kernel_builder# and the trapnet's runtime observations; promoted here from# test/test_stack_effect.py so every future consumer of check_colon gets the# same signatures instead of re-deriving them. The builder's comments remain# the source this is transcribed from; extending check_colon to assert every# primitive is listed here is the natural control-error (TODO).EFFECT_TABLE = { # ── data-stack pure ── "DROP": (1, 0, 0, 0), "DUP": (1, 2, 0, 0), "SWAP": (2, 2, 0, 0), "OVER": (2, 3, 0, 0), "ROT": (3, 3, 0, 0), "+": (2, 1, 0, 0), "-": (2, 1, 0, 0), # used by DOT's sentinel check (value - 256) "@": (1, 1, 0, 0), "!": (2, 0, 0, 0), "C@": (1, 1, 0, 0), "C!": (2, 0, 0, 0), "0=": (1, 1, 0, 0), "0<": (1, 1, 0, 0), "<": (2, 1, 0, 0), "NEGATE": (1, 1, 0, 0), "UM/MOD": (2, 2, 0, 0), # ( divisor dividend -- rem quot ) "EMIT": (1, 0, 0, 0), # ── return-stack movers (the two-stack model lives here) ── ">R": (1, 0, 0, 1), # data -> return "R>": (0, 1, 1, 0), # return -> data # ── stack-neutral / structural ── "WORD": (0, 0, 0, 0), # writes PAD, no data-stack effect "FIND": (0, 1, 0, 0), # ( -- cfa | 0 ) [conditional push count] "EXECUTE": (1, 0, 0, 0), # pops the cfa it runs "NUMBER": (0, 2, 0, 0), # ( -- value flag ) "REFILL": (0, 0, 0, 0), "EXIT": (0, 0, 0, 0), # structural — checker handles EXIT specially "LIT": (0, 1, 0, 0), # checker handles the inline data cell "BRANCH": (0, 0, 0, 0), # reads the inline offset cell; no stack effect "0BRANCH": (1, 0, 0, 0), # POPS its flag (the Dragon-2 root cause) + reads offset # ── colon words that get threaded by other colon words ── # QUIT threads INTERPRET; INTERPRET is stack-neutral (drains input, leaves # whatever the parsed words pushed — modeled as neutral because the # checker can't see input-dependent effects; the trapnet owns that). "INTERPRET": (0, 0, 0, 0),}
# Per-word entry signatures (the data-stack depth the word expects on entry).# Most colon words enter at depth 0; `.` enters at depth 1 (it consumes its# argument n). This is the word's CALLING contract, distinct from its body's# internal effects. Keys not present default to 0.ENTRY_DATA_DEPTH = { ".": 1, # ( n -- ): consumes its argument}
def check_colon(body, labels, entries_by_cfa, effect_table=EFFECT_TABLE, entry_data=0, entry_rstack=0): """Statically check one colon word's body IR for stack-effect violations.
Returns a list of Violation (empty = clean). See module docstring for the model and its deliberate limitations.
entry_data / entry_rstack: the depth of the data and return stacks AT ENTRY to the word (the word's own signature). `.` enters with entry_data=1 (it consumes its argument n); INTERPRET/QUIT enter with 0/0. The EXIT invariant checks that control leaves with stacks balanced BACK to these entry depths (so a word that pushes garbage and exits is caught), and the underflow check is relative to entry (a DUP at index 0 with entry_data=0 is a real underflow; with entry_data=1 it's fine — that's `.`'s arg).
The walk is a worklist over (cell_index, data_depth, rstack_depth). Branch sources fork the worklist; labels merge. A label's expected depth is set by the first path to reach it; subsequent paths must agree. This catches Dragon 2 (stray DROPs → underflow) and the >R/R> imbalance (EXIT with a non-empty return stack) alike. """ violations = []
def name_of(cfa): return entries_by_cfa.get(cfa)
# entry point: index 0, stacks at the word's signature depths start = (0, entry_data, entry_rstack, "entry") worklist = [start] # label_depths[label] = (data_depth, rstack_depth, first_path_desc) — set # by the first arrival; later arrivals are checked against it. label_depths = {} # visited (index, data, rstack) — prevents infinite loops on cyclic bodies # (QUIT loops forever at runtime, but its IR is finite; the worklist must # terminate). A re-arrival at the same (index, data, rstack) state adds # no information. seen = set() # branch sources by target label, for error messages # branch_sources[label] = list of (src_index, data_depth_at_branch) branch_sources = {}
while worklist: index, d, r, path = worklist.pop() if index >= len(body): # Falling off the end of the body without an EXIT/branch. For a # well-formed colon word this is the implicit end; require balanced # stacks back to the entry signature. if d != entry_data or r != entry_rstack: violations.append(Violation( cell_index=index, kind="unbalanced-exit", depth=d, message=(f"body ended at index {index} with data depth " f"{d} / rstack {r} (path: {path}) — expected " f"{entry_data}/{entry_rstack} (entry signature)"))) continue key = (index, d, r) if key in seen: continue seen.add(key)
item = body[index] if item[0] == 'br': target, is_zero = item[1] target_idx = labels[target] branch_sources.setdefault(target, []).append((index, d)) # 0BRANCH pops a flag (the Dragon-2 root cause); BRANCH does not. if is_zero: if d < 1: violations.append(Violation( cell_index=index, kind="underflow", depth=d, message=(f"0BRANCH→{target} pops a flag but data depth " f"is {d} (path: {path})"))) new_d = d # don't go negative in the model; report and continue else: new_d = d - 1 else: new_d = d # Both the taken and not-taken paths are possible. The not-taken # path falls through to index+1 (the offset cell is consumed as # data, so the next OPCODE is index+2). The taken path lands at # target_idx. # BRANCH is unconditional: only the taken path exists. 0BRANCH is # conditional: both exist (flag popped either way; the pop happens # before the branch decision). if not is_zero: # unconditional BRANCH: only the taken path. Record fall-through # as impossible (don't add it). _arrive(target_idx, target, new_d, r, f"{path}→br@{index}", label_depths, violations, branch_sources) worklist.append((target_idx, new_d, r, f"{path}→br@{index}")) else: # 0BRANCH: both paths. Taken (flag was nonzero) and not-taken # (flag was zero) both pop the flag, both proceed at new_d. _arrive(target_idx, target, new_d, r, f"{path}→0br-taken@{index}", label_depths, violations, branch_sources) worklist.append((target_idx, new_d, r, f"{path}→0br-taken@{index}")) fallthrough = index + 2 # skip the offset cell worklist.append((fallthrough, new_d, r, f"{path}→0br-fall@{index}")) continue
# item is ('cell', cfa) — an opcode. Resolve and apply its effect. cfa = item[1] name = name_of(cfa) if name is None: # An opcode-position cell whose value isn't a known cfa. This is # either a real bug (corrupted body) or the walker mis-counted and # landed on a data cell. Report as underflow-class for visibility. violations.append(Violation( cell_index=index, kind="underflow", depth=d, message=(f"opcode cell {cfa:#x} at index {index} is not a " f"known cfa (path: {path}) — walker mis-count or " f"corrupted body"))) continue
if name == "EXIT": if d != entry_data or r != entry_rstack: violations.append(Violation( cell_index=index, kind="unbalanced-exit", depth=d, message=(f"EXIT at index {index} with data depth {d} / " f"rstack {r} (path: {path}) — must return to " f"{entry_data}/{entry_rstack} (entry signature); " f"an unbalanced >R/R> corrupts the popped IP"))) # EXIT leaves the word; no fall-through. continue
eff = effect_table.get(name) if eff is None: # Unknown effect — can't check. Report as a gap (not a violation # per se, but the checker can't vouch for this word). We DO # continue past it (assume neutral) so the rest of the body is # still checked; the gap is recorded so the effect table can be # extended. violations.append(Violation( cell_index=index, kind="underflow", depth=d, message=(f"word '{name}' at index {index} has no effect-table " f"entry (path: {path}) — extend EFFECT_TABLE"))) worklist.append((index + 1, d, r, path)) continue
d_pop, d_push, r_pop, r_push = eff # underflow check (Progress) if d < d_pop: violations.append(Violation( cell_index=index, kind="underflow", depth=d, message=(f"{name} at index {index} pops {d_pop} data but " f"depth is {d} (path: {path})"))) if r < r_pop: violations.append(Violation( cell_index=index, kind="underflow", depth=r, message=(f"{name} at index {index} pops {r_pop} return-stack " f"but rstack depth is {r} (path: {path})"))) new_d = d - d_pop + d_push new_r = r - r_pop + r_push
# Advance. LIT/BRANCH/0BRANCH consume the next cell as data. advance = 2 if name in _DATA_AFTER else 1 worklist.append((index + advance, new_d, new_r, path))
return violations
def _arrive(target_idx, target_label, d, r, path, label_depths, violations, branch_sources): """Record a path arriving at a labeled position. The first arrival sets the expected depth; later arrivals must agree. This is the Preservation invariant across branch merges.""" if target_label not in label_depths: label_depths[target_label] = (d, r, path) return exp_d, exp_r, first_path = label_depths[target_label] if d != exp_d or r != exp_r: # gather all known sources for a precise message srcs = branch_sources.get(target_label, []) src_str = ", ".join(f"@{i}(d={dd})" for i, dd in srcs) or "none" violations.append(Violation( cell_index=target_idx, kind="branch-merge-mismatch", depth=d, message=(f"label '{target_label}' reached at data depth {d}/" f"rstack {r} (path: {path}) but first arrival was " f"{exp_d}/{exp_r} (path: {first_path}); sources: {src_str}")))