// SPDX-License-Identifier: MIT //! Run lockstep scripts on this crate and print the trace scripts/lockstep_ref.py prints for //! pokey-python (the script and trace formats are in that file's docstring). //! //! pokey-trace SCRIPT [SCRIPT ...] [--out-dir DIR] use std::cell::RefCell; use std::collections::HashMap; use std::fs; use std::path::{Path, PathBuf}; use std::rc::Rc; use pokey::rc::PotRC; use pokey::{Look, State, C012294, LINEAR, POKEY}; #[derive(Default)] struct Shared { events: Vec, pot_calls: u64, } struct Tracer { out: Vec, shared: Rc>, last: Option, repeat: u64, chip: Option, saved: Option, } fn h(x: f64) -> String { format!("{:016x}", x.to_bits()) } fn list>(values: &[T]) -> String { if values.is_empty() { return "-".to_string(); } values .iter() .map(|v| (*v).into().to_string()) .collect::>() .join(",") } fn bools(values: &[bool]) -> String { values .iter() .map(|v| (*v as u8).to_string()) .collect::>() .join(",") } fn state_line(chip: &POKEY) -> String { let s = chip.snapshot(); let audc_q = if s.audc_q.is_empty() { "-".to_string() } else { s.audc_q .iter() .map(|e| { e.iter() .map(|v| v.to_string()) .collect::>() .join(",") }) .collect::>() .join(";") }; let fields: Vec = vec![ s.sid.to_string(), s.bclk_in.to_string(), s.clock.to_string(), list(&s.audf), list(&s.audc), s.audctl.to_string(), s.skctl.to_string(), s.irqen.to_string(), s.w_reg.to_string(), s.w_val.to_string(), s.latched.to_string(), (s.irq as u8).to_string(), s.serin.to_string(), s.ser_overrun.to_string(), s.frame_error.to_string(), s.kbcode.to_string(), s.kb_overrun.to_string(), s.key_held.to_string(), s.shift_latch.to_string(), s.ctrl_latch.to_string(), s.break_prev.to_string(), s.scan_code.to_string(), s.kb_state.to_string(), s.kb_compare.to_string(), list(&s.pot), s.pot_count.to_string(), (s.pot_scan as u8).to_string(), s.pot_step.to_string(), s.allpot.to_string(), (s.dump_active as u8).to_string(), s.c15.to_string(), s.c64.to_string(), (s.clocks_init as u8).to_string(), list(&s.count), list(&s.pend), bools(&s.fired), bools(&s.fired_prev), s.stimer_q.to_string(), s.resync_q.to_string(), s.sod_bit.to_string(), s.oclk_ff.to_string(), s.bclk_ff.to_string(), list(&s.gate5), list(&s.passed), list(&s.passed_prev), s.poly4.to_string(), s.poly5.to_string(), list(&s.ff), list(&s.hp), s.stimer_set.to_string(), audc_q, s.poly17.to_string(), ]; format!("S {}", fields.join(" ")) } fn levels_text(l: (u8, u8, u8, u8)) -> String { format!("{},{},{},{}", l.0, l.1, l.2, l.3) } impl Tracer { fn new() -> Self { Tracer { out: Vec::new(), shared: Rc::new(RefCell::new(Shared::default())), last: None, repeat: 0, chip: None, saved: None, } } fn flush_ticks(&mut self) { if let Some(last) = self.last.take() { if self.repeat == 1 { self.out.push(format!("T {last}")); } else { self.out.push(format!("T*{} {last}", self.repeat)); } self.repeat = 0; } } fn emit(&mut self, line: String) { self.flush_ticks(); self.out.push(line); } fn flush_events(&mut self) { let events = std::mem::take(&mut self.shared.borrow_mut().events); for line in events { self.emit(line); } } fn tick_line(&mut self) { self.flush_events(); let chip = self.chip.as_ref().unwrap(); let bclk = match chip.bclk_out() { None => "-".to_string(), Some(v) => v.to_string(), }; let calls = std::mem::take(&mut self.shared.borrow_mut().pot_calls); let line = format!( "{} {} {} {} {} {} {} {} {}", levels_text(chip.levels()), chip.irq as u8, chip.scan_code, chip.dump_active as u8, chip.sod(), chip.oclk(), bclk, h(chip.mix()), calls ); if self.last.as_deref() == Some(line.as_str()) { self.repeat += 1; } else { self.flush_ticks(); self.last = Some(line); self.repeat = 1; } } fn wire_pots(&mut self, mut level: Box bool>) { let shared = Rc::clone(&self.shared); self.chip.as_mut().unwrap().pot_level = Box::new(move |n, look| { shared.borrow_mut().pot_calls += 1; level(n, look) }); } fn keys_from(&self, table: HashMap, default: u8) -> Box u8> { let shared = Rc::clone(&self.shared); Box::new(move |code| { shared.borrow_mut().events.push(format!("k {code}")); *table.get(&code).unwrap_or(&default) }) } fn run(mut self, text: &str) -> Vec { for line in text.lines() { let parts: Vec<&str> = line.split_whitespace().collect(); if parts.is_empty() { continue; } let (op, args) = (parts[0], &parts[1..]); let int = |i: usize| -> u64 { args[i].parse().unwrap() }; match op { "new" => { let variant = match args[0] { "C012294" => C012294.clone(), "LINEAR" => LINEAR.clone(), other => panic!("unknown variant {other}"), }; let mut chip = POKEY::new(variant, int(1) != 0); let s = Rc::clone(&self.shared); chip.on_irq = Some(Box::new(move |level| { s.borrow_mut().events.push(format!("I {}", level as u8)) })); let s = Rc::clone(&self.shared); chip.on_dump = Some(Box::new(move |level, _look| { s.borrow_mut().events.push(format!("D {}", level as u8)) })); chip.key_response = self.keys_from(HashMap::new(), 0); self.chip = Some(chip); self.wire_pots(Box::new(|_n, _look| false)); } "power" => { let seed = if args[0] == "-" { None } else { Some(int(0)) }; self.chip.as_mut().unwrap().power_on(seed); self.flush_events(); } "w" => self .chip .as_mut() .unwrap() .write(int(0) as u8, int(1) as u8), "r" => { let value = self.chip.as_mut().unwrap().read(int(0) as u8); self.flush_events(); self.emit(format!("r {} {value}", args[0])); } "t" => { for _ in 0..int(0) { self.chip.as_mut().unwrap().tick(); self.tick_line(); } } "P" => { let mask = int(0); self.wire_pots(Box::new(move |n, _look| (mask >> n) & 1 != 0)); } "PR" => { let targets: Vec> = args .iter() .map(|a| { if *a == "-" { None } else { Some(a.parse().unwrap()) } }) .collect(); let rc = Rc::new(RefCell::new(PotRC::new( self.chip.as_ref().unwrap(), Some(targets), ))); let level = Rc::clone(&rc); self.wire_pots(Box::new(move |n, look| level.borrow_mut().level(n, look))); let s = Rc::clone(&self.shared); self.chip.as_mut().unwrap().on_dump = Some(Box::new(move |on, look| { s.borrow_mut().events.push(format!("D {}", on as u8)); rc.borrow_mut().dumped(on, look); })); } "K" => { let default = int(0) as u8; let table: HashMap = args[1..] .iter() .map(|a| { let (c, r) = a.split_once(':').unwrap(); (c.parse().unwrap(), r.parse().unwrap()) }) .collect(); let keys = self.keys_from(table, default); self.chip.as_mut().unwrap().key_response = keys; } "S" => self.chip.as_mut().unwrap().sid = int(0) as u8, "B" => self.chip.as_mut().unwrap().bclk_in = int(0) as u8, "save" => self.saved = Some(self.chip.as_ref().unwrap().snapshot()), "load" => { let saved = self.saved.clone().unwrap(); self.chip.as_mut().unwrap().restore(&saved); self.flush_events(); } "state" => { let line = state_line(self.chip.as_ref().unwrap()); self.emit(line); } "take" => { let taken = self.chip.as_mut().unwrap().take_outputs(); let body = if taken.is_empty() { "-".to_string() } else { taken .iter() .map(|l| levels_text(*l)) .collect::>() .join(";") }; self.emit(format!("take {} {body}", taken.len())); } other => panic!("unknown op {other:?}"), } } self.flush_events(); self.flush_ticks(); self.out } } fn main() { let mut args: Vec = std::env::args().skip(1).collect(); let mut out_dir: Option = None; if let Some(i) = args.iter().position(|a| a == "--out-dir") { out_dir = Some(PathBuf::from(&args[i + 1])); args.drain(i..i + 2); } for name in &args { let text = fs::read_to_string(name).expect("read script"); let result = Tracer::new().run(&text).join("\n") + "\n"; match &out_dir { None => print!("{result}"), Some(dir) => { let stem = Path::new(name).file_stem().unwrap().to_string_lossy(); fs::write(dir.join(format!("{stem}.trace")), result).expect("write trace"); } } } }