//! A resumable, untraced run of a manifest: the loop of z80-rust-fast's //! `z80-bench` (cpm trap, halt check, `step()`), sliced into budgets so a //! Web Worker can report progress and stream console output between slices. use serde_json::Value; use z80_rust::conformance::{ handle_cpm_trap, manifest_from_json, ConformanceHost, HostProfile, Manifest, }; use z80_rust::Z80; /// Replace `{"address": A, "file": NAME}` memory segments with inline data, /// so a manifest that references a file runs where there is no file system. /// `files` maps a name to its bytes; an unknown name is an error. pub fn inline_files( manifest_json: &str, mut files: impl FnMut(&str) -> Option>, ) -> Result { let mut value: Value = serde_json::from_str(manifest_json).map_err(|error| format!("manifest: {error}"))?; if let Some(segments) = value.get_mut("memory").and_then(Value::as_array_mut) { for segment in segments { let Some(name) = segment .get("file") .and_then(Value::as_str) .map(str::to_owned) else { continue; }; let bytes = files(&name).ok_or_else(|| format!("memory.file {name}: not provided"))?; let object = segment.as_object_mut().unwrap(); object.remove("file"); object.insert("data".into(), Value::String(hex(&bytes))); } } Ok(value) } fn hex(bytes: &[u8]) -> String { let mut out = String::with_capacity(bytes.len() * 2); for byte in bytes { out.push_str(&format!("{byte:02x}")); } out } /// One slice's outcome. `instructions` and `t_states` are running totals. #[derive(Clone, Debug, PartialEq, Eq)] pub struct Progress { pub instructions: u64, pub t_states: u64, /// Console bytes the program wrote during this slice. pub output: Vec, /// `None` while the run continues; otherwise why it stopped. pub stopped: Option, } impl Progress { pub fn to_json(&self) -> String { serde_json::json!({ "instructions": self.instructions, "t_states": self.t_states, "output": String::from_utf8_lossy(&self.output), "stopped": self.stopped, }) .to_string() } } pub struct Runner { cpu: Z80, cpm: bool, stop_on_halt: bool, max_steps: u64, instructions: u64, t_states: u64, stopped: Option, name: String, } impl Runner { pub fn new( manifest_json: &str, files: impl FnMut(&str) -> Option>, ) -> Result { let value = inline_files(manifest_json, files)?; let manifest: Manifest = manifest_from_json(&value, None)?; let mut cpu = Z80::new(ConformanceHost::new(&manifest)); cpu.restore_state(&manifest.initial); Ok(Runner { cpu, cpm: manifest.host == HostProfile::CpmMinimal, stop_on_halt: manifest.stop.on_halt, max_steps: manifest.stop.max_steps, instructions: 0, t_states: 0, stopped: None, name: manifest.name, }) } pub fn name(&self) -> &str { &self.name } pub fn instructions(&self) -> u64 { self.instructions } pub fn t_states(&self) -> u64 { self.t_states } /// Run up to `budget` more instructions. The stop-check order is /// `z80-bench`'s: step budget, cpm trap, halt, then `step()`. pub fn run(&mut self, budget: u64) -> Progress { let mut ran: u64 = 0; while self.stopped.is_none() { if self.instructions == self.max_steps { self.stopped = Some("max_steps".into()); break; } if ran == budget { break; } if self.cpm { match handle_cpm_trap(&mut self.cpu) { Ok(true) => { self.stopped = Some("cpm_exit".into()); break; } Ok(false) => {} Err(error) => { self.stopped = Some(format!("error: {error}")); break; } } } if self.stop_on_halt && self.cpu.halted { self.stopped = Some("halted".into()); break; } match self.cpu.step() { Ok(t) => { self.t_states += u64::from(t); self.instructions += 1; ran += 1; } Err(fault) => { self.stopped = Some(format!("fault: {fault}")); break; } } } Progress { instructions: self.instructions, t_states: self.t_states, output: std::mem::take(&mut self.cpu.bus.output), stopped: self.stopped.clone(), } } }