#!/usr/bin/env python3 # SPDX-License-Identifier: MIT """Run a scenario on spc700-python and write its boundary trace (the reference's half). reference_trace.py SCENARIO.json [--out TRACE.jsonl] The same scenario format as ``src/bin/trace.rs`` (conformance/README.md), run on the reference core through its own ``DebugSession`` with access tracking, each record its own ``step_record_to_dict``, written as its ``write_trace`` writes one (sorted keys, no spaces), less the instruction's ``mnemonic`` and ``operands`` (its docs/trace-schema.md: a producer in another language omits both). ``SPC700_PYTHON`` names the checkout. """ from __future__ import annotations import argparse import json import os import sys from dataclasses import replace from pathlib import Path sys.path.insert(0, str(Path(os.environ["SPC700_PYTHON"]) / "src")) from spc700_python import SPC700 # noqa: E402 from spc700_python.debug import DebugSession # noqa: E402 from spc700_python.harness import _SELF_BRANCHES, Harness # noqa: E402 from spc700_python.trace import step_record_to_dict # noqa: E402 REGISTERS = ("a", "x", "y", "sp", "pc", "psw") def fill_random(memory: bytearray, seed: int) -> None: """A 32-bit xorshift, one byte per step (src/bin/trace.rs's fill_random).""" state = seed | 1 for address in range(len(memory)): state ^= (state << 13) & 0xFFFFFFFF state ^= state >> 17 state ^= (state << 5) & 0xFFFFFFFF memory[address] = state >> 24 def spctest_script(harness: Harness) -> None: """run_spctest's setup and on_write for its first program (spc700_python.harness).""" harness.ports_in[1] = 1 harness.ports_in[2], harness.ports_in[3] = 0xFF, 0xFF failing: list[int] = [] def on_write(port: int, value: int) -> None: if port == 3 and not failing: pass # the report's test list: not part of the trace elif port == 0 and value == 1: harness.finished = True elif port == 0 and value == 2: failing.append(harness.ports_out[1]) harness.ports_in[1] = 2 elif port == 0 and value == 3: harness.finished = True harness.on_port_write = on_write def records(path: Path): scenario = json.loads(path.read_text()) harness = None if "program" in scenario: program = scenario["program"] file = Path(program["file"]) harness = Harness() harness.load_file((file if file.is_absolute() else path.parent / file).read_bytes(), program["org"]) if program.get("spctest"): spctest_script(harness) cpu, peek = harness.cpu, harness.peek else: memory = bytearray(0x10000) if "fill" in scenario: fill_random(memory, scenario["fill"]["seed"]) for block in scenario.get("memory", ()): for offset, byte in enumerate(bytes.fromhex(block["hex"])): memory[(block["address"] + offset) & 0xFFFF] = byte cpu = SPC700(memory.__getitem__, memory.__setitem__) peek = memory.__getitem__ registers = scenario.get("registers", {}) for name in REGISTERS: if name in registers: setattr(cpu, name, registers[name]) between: dict[int, list[dict]] = {} for event in scenario.get("events", ()): between.setdefault(event["step"], []).append(event) session = DebugSession(cpu, peek_byte=peek, track_accesses=scenario.get("accesses", True)) until_stop = harness is not None and scenario.get("until_stop", False) for sequence in range(scenario["steps"]): if until_stop and (harness.finished or cpu.stopped): break for event in between.get(sequence, ()): if event["action"] == "reset": cpu.reset() elif event["action"] == "jump": state = cpu.capture_state() cpu.restore_state(replace(state, pc=event["pc"], psw=event["psw"], stopped=False)) else: raise ValueError(f"unknown action {event['action']}") pc = cpu.pc yield session.step() if until_stop and cpu.pc == pc and cpu.opcode in _SELF_BRANCHES: break def main() -> int: parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument("scenario", type=Path) parser.add_argument("--out", type=Path) args = parser.parse_args() stream = args.out.open("w") if args.out else sys.stdout with stream: for record in records(args.scenario): encoded = step_record_to_dict(record) instruction = encoded["instruction"] if instruction is not None: del instruction["mnemonic"], instruction["operands"] stream.write(json.dumps(encoded, separators=(",", ":"), sort_keys=True) + "\n") return 0 if __name__ == "__main__": sys.exit(main())