""" test_stack_effect.py — The static stack-effect checker: prove it HUNTS. WHY THIS EXISTS: The trapnet (test_trapnet.py) catches stack bugs DYNAMICALLY — a stray DROP has to actually execute on a specific input before the underflow guard fires. Dragon 2 (README.md §"The dragon encyclopedia") slipped through precisely because no input path the tests exercised hit the underflowing branch: three stray DROPs took the data stack to depth -1, but the tests asserted only on the final stack value and forgave the process of getting there. This file is the STATIC net: walk a colon word's body IR and prove stack depth is consistent on EVERY branch path, BEFORE execution. It is the type-soundness proof (Progress + Preservation) the creed gestures at — done cheaply, by hand-derivation, over the structured IR the builder already has. THE CONTRACT (the checker must conform to this — tests written FIRST): check_colon(body, labels, entries_by_cfa, effect_table) -> list[Violation] body the structured IR: 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 a word effect_table {word_name: (d_pop, d_push, r_pop, r_push)} — the signed stack effect of each primitive/colon word the body threads A Violation is (cell_index, kind, depth, message). kinds: 'underflow' — a primitive popped deeper than the stack had 'unbalanced-exit' — EXIT reached with data depth != entry depth, or return-stack imbalance 'branch-merge-mismatch' — two paths arriving at a label disagree on depth WE HUNT, WE DON'T PASS: The headline test reconstructs Dragon 2 — the EXACT buggy INTERPRET body (three stray DROPs from the 0BRANCH-pops-vs-peeks misread) — and asserts the checker flags it. If the checker returns clean on the buggy body, the checker is broken; that is the failure mode these tests watch for. The green tests (real INTERPRET/QUIT/DOT pass clean) are the no-false-positive controls. """ import pytest from src.build_kernel import build from src.stack_effect import check_colon, Violation, EFFECT_TABLE, ENTRY_DATA_DEPTH # ── the canonical kernel: build once, reuse the IR + address map ────────── @pytest.fixture(scope="module") def kernel(): image, addr_map, kb = build(base=0x4690) # entries_by_cfa: cfa_int -> word_name. Built from kb.entries (code words # + colon words). The checker resolves each ('cell', v) through this. entries_by_cfa = {cfa: name for name, cfa in kb.entries.items()} return kb, entries_by_cfa # The effect table + entry-depth map are imported from src/stack_effect (the # canonical type-signature source of truth, promoted from this file). Tests # that need a MUTATED table (e.g. a hypothetical Dragon-2 reconstruction # that weakens an entry) copy-on-write: {**EFFECT_TABLE, "DROP": (0,0,0,0)}. # Today every test uses the canonical table read-only. # ═══════════════════════════════════════════════════════════════════════════ # GREEN: the real colon words pass clean (no false positives) # ═══════════════════════════════════════════════════════════════════════════ class TestRealColonWordsAreClean: """The no-false-positive control. The shipping INTERPRET/QUIT/DOT had their dragons slain (Dragon 2 was the stray-DROP fix); the checker MUST return zero violations on them. A violation here means the checker's effect table or branch-merge logic is wrong, not that the kernel regressed.""" def test_interpret_is_clean(self, kernel): kb, entries_by_cfa = kernel body, labels = kb.colon_bodies["INTERPRET"] violations = check_colon(body, labels, entries_by_cfa, EFFECT_TABLE) assert violations == [], ( f"INTERPRET flagged (should be clean — Dragon 2 was fixed):\n" + "\n".join(f" {v}" for v in violations)) def test_quit_is_clean(self, kernel): kb, entries_by_cfa = kernel body, labels = kb.colon_bodies["QUIT"] violations = check_colon(body, labels, entries_by_cfa, EFFECT_TABLE) assert violations == [], ( f"QUIT flagged (should be clean):\n" + "\n".join(f" {v}" for v in violations)) @pytest.mark.xfail( reason=( "KNOWN LIMITATION (not a kernel bug): DOT's digit-reversal uses a " "variable-iteration >R/R> loop — push N digits via >R, pop N+1 via " "R> (digits + sentinel). The net rstack effect is 0, PROVEN at " "runtime by test_r_stack_hunt.py (the balance invariant is that " "file's purpose). But this integer-depth worklist cannot unroll a " "variable-count loop, so it sees an apparent imbalance at EXIT and " "a cascade through emit_digit. This is the documented boundary " "between the static checker (Dragon-2 class: stray DROPs in " "straight-line/branch code) and the runtime trapnet (loop balance, " "input-dependent effects). See stack_effect.py LIMITATIONS.")) def test_dot_is_clean(self, kernel): kb, entries_by_cfa = kernel body, labels = kb.colon_bodies["."] # `.` enters with its argument on the stack (entry_data=1). violations = check_colon(body, labels, entries_by_cfa, EFFECT_TABLE, entry_data=ENTRY_DATA_DEPTH["."]) assert violations == [], ( f". flagged (should be clean — uses >R/R> for digit reversal, " f"return stack must balance; entry_data=1 for its arg):\n" + "\n".join(f" {v}" for v in violations)) # ═══════════════════════════════════════════════════════════════════════════ # THE HUNT: reconstruct Dragon 2, assert the checker catches it # ═══════════════════════════════════════════════════════════════════════════ class TestDragon2StrayDropsAreCaught: """Dragon 2 (README.md §"The dragon encyclopedia"): three stray DROPs from a misread 0BRANCH contract. The comments assumed 0BRANCH PEEKS the flag (so a trailing DROP "removes it"); it POPS. So three DROPs each removed a value that no longer existed — data-stack depth went to -1, unchecked, on branches the tests never exercised. This reconstructs the EXACT buggy body and asserts the checker flags it. If the checker returns clean here, the checker is dead weight — that is the failure mode under test. This is the test that HUNTS, not passes.""" def _dragon2_body(self, entries_by_cfa): """The buggy INTERPRET body: the corrected sequence with the three stray DROPs re-added at their documented positions. Corrected body cells (the watchmaker fix): [0] WORD [1] LIT [2] PAD [3] C@ [4] 0= [5] 0BRANCH→not_empty [6] EXIT [7] FIND(not_empty) [8] 0BRANCH→try_number [9] EXECUTE [10] BRANCH→loop [11] NUMBER(try_number) [12] 0BRANCH→skip [13] BRANCH→loop [14] DROP(skip) [15] BRANCH→loop Buggy version re-adds: - a DROP after the first 0BRANCH (the "drop the 0" misread) - a DROP after the second 0BRANCH (the "drop the flag" misread) - the skip-path DROP becomes DROP DROP (one extra) """ E = entries_by_cfa # cfa_int -> name; we build IR keyed by NAME via a reverse lookup # Build a name->cfa view for fixture construction. by_name = {name: cfa for cfa, name in E.items()} W = by_name["WORD"]; LIT = by_name["LIT"]; CAT = by_name["C@"] ZE = by_name["0="]; ZB = by_name["0BRANCH"]; EX = by_name["EXIT"] F = by_name["FIND"]; XQ = by_name["EXECUTE"]; BR = by_name["BRANCH"] N = by_name["NUMBER"]; D = by_name["DROP"]; PAD = 0x00805000 body = [] def cell(v): body.append(('cell', v)); return len(body) - 1 def br(t, z): body.append(('br', (t, z))); return len(body) - 1 def label(n): labels[n] = len(body) labels = {} # loop: label('loop') cell(W) # WORD d=0 cell(LIT); cell(PAD) # LIT PAD d=1 cell(CAT) # C@ d=1 cell(ZE) # 0= d=1 cell(ZB); br('not_empty', True) # POP flag d=0 (0BRANCH pops) cell(D) # ← DRAGON: stray "drop the 0" d=-1 cell(EX) label('not_empty') cell(F) # FIND d=0 cell(ZB); br('try_number', True) # POP flag d=-1 (underflow already) cell(XQ) # EXECUTE cell(BR); br('loop', False) label('try_number') cell(N) # NUMBER d=0->2 (but path already broken) cell(ZB); br('skip', True) # POP flag cell(D) # ← DRAGON: stray "drop the flag" cell(BR); br('loop', False) label('skip') cell(D); cell(D) # ← DRAGON: DROP DROP (was DROP) cell(BR); br('loop', False) return body, labels def test_checker_flags_dragon2(self, kernel): _, entries_by_cfa = kernel body, labels = self._dragon2_body(entries_by_cfa) violations = check_colon(body, labels, entries_by_cfa, EFFECT_TABLE) kinds = {v.kind for v in violations} assert violations, ( "CHECKER IS BROKEN: the Dragon-2 buggy body (three stray DROPs, " "depth -1) returned CLEAN. The checker must flag at least one " "'underflow' violation on this body — that is its entire purpose.") assert "underflow" in kinds, ( f"Dragon 2 should produce an 'underflow' violation; got kinds " f"{kinds}.\n{[str(v) for v in violations]}") def test_checker_localizes_the_first_underflow(self, kernel): """The creed: don't just say 'broken', say WHERE. The first underflow is the stray DROP right after the first 0BRANCH — the checker should point at that cell index, so the human (or the dragon-doc) lands on the exact instruction.""" _, entries_by_cfa = kernel body, labels = self._dragon2_body(entries_by_cfa) violations = check_colon(body, labels, entries_by_cfa, EFFECT_TABLE) underflows = [v for v in violations if v.kind == "underflow"] assert underflows, "no underflow violation — see test_checker_flags_dragon2" # Recount the fixture: each IR item is ONE slot (the branch is a single # ('br',...) item, not opcode+offset). So: # [0]WORD [1]LIT [2]PAD [3]C@ [4]0= [5]0BRANCH [6]br-item [7]DROP(stray) # The stray DROP is at index 7; 0BRANCH already popped the flag at [5], # so the DROP at [7] pops from depth 0 → underflow. first = underflows[0] assert first.cell_index == 7, ( f"first underflow should be the stray DROP @ index 7, " f"got index {first.cell_index} (depth {first.depth}): {first}") # ═══════════════════════════════════════════════════════════════════════════ # HUNT: the return-stack imbalance (the DOT/EXIT invariant) # ═══════════════════════════════════════════════════════════════════════════ class TestReturnStackImbalanceIsCaught: """EXIT pops the saved IP from the return stack. If a colon word does >R without a matching R> before EXIT, the return stack is unbalanced and EXIT corrupts IP — the kernel faults or runs wild. This is the invariant test_r_stack_hunt.py checks at RUNTIME; the static checker must catch it at BUILD time. Reconstruct an unbalanced body and assert the flag.""" def test_unbalanced_r_branch_is_caught(self, kernel): _, entries_by_cfa = kernel by_name = {n: c for c, n in entries_by_cfa.items()} # : BROKEN 5 >R EXIT ; — >R without R>, then EXIT. rstack depth 1 # at EXIT but must be 0. body = [ ('cell', by_name["LIT"]), ('cell', 5), ('cell', by_name[">R"]), ('cell', by_name["EXIT"]), ] labels = {} violations = check_colon(body, labels, entries_by_cfa, EFFECT_TABLE) kinds = {v.kind for v in violations} assert violations, ( "CHECKER IS BROKEN: '>R EXIT' without a balancing R> returned " "CLEAN. The return-stack imbalance must be flagged.") assert "unbalanced-exit" in kinds, ( f"expected 'unbalanced-exit' kind, got {kinds}")