// SPDX-License-Identifier: MIT //! Run a Lynx Hardware Tests ROM (drhelius, MIT) to its results and judge them //! (`testrom.py`). //! //! The suites are built from source by the reference (its `scripts/build_lynx_tests.py`); //! each one's `run_tests` fills `g_results` before the result screen is drawn. This //! harness boots the ROM through the real boot ROM, runs until `run_tests` //! returns, reads `g_results` (address from the cc65 label file) and judges it //! with the suite's own expectation table, parsed from its `main.c`: //! //! - `k_expected_results`: one set of accepted values per result byte //! (`EXPECT(a, b, ...)`), grouped into tests by `k_test_offsets` / //! `k_test_counts` where the suite has them, else evenly; //! - `timers2`: a test passes when its result byte is 0. //! //! The expected values are the tests' author's record of real consoles (tier 3). //! //! Differences forced by Rust: the reference finds the built ROMs and the suite sources //! under its own repository; here they are read in place from the reference's checkout, //! `$LYNX_TESTS_BUILD` (default `../lynx-python/tests/test_roms/build` beside this //! repository) and `$LYNX_TESTS_SOURCE` (default `../lynx-python/reference/src/lynx-tests`). use std::collections::BTreeMap; use std::path::PathBuf; use regex::Regex; use crate::board::Lynx; use crate::bootrom; use crate::cart::load_path; use crate::machine::Machine; pub const TICKS_PER_SECOND: i64 = 16_000_000; fn root() -> PathBuf { PathBuf::from(env!("CARGO_MANIFEST_DIR")) } pub fn build_dir() -> PathBuf { std::env::var("LYNX_TESTS_BUILD") .map(PathBuf::from) .unwrap_or_else(|_| root().join("../lynx-python/tests/test_roms/build")) } pub fn source_dir() -> PathBuf { std::env::var("LYNX_TESTS_SOURCE") .map(PathBuf::from) .unwrap_or_else(|_| root().join("../lynx-python/reference/src/lynx-tests")) } #[derive(Clone, Debug)] pub struct Suite { pub name: String, pub results: usize, pub names: Vec, pub expected: Vec>, pub groups: Vec<(usize, usize)>, // (offset, count) per test pub zero_is_pass: bool, /// Sprite suites: per test a 16-bit Timer 1/3 duration window and two CRC bytes /// (video, collision), laid out timing low, high, CRC 1, CRC 2 (sprites*/main.c). pub timings: Vec<(i64, i64)>, } #[derive(Clone, Debug)] pub struct Outcome { pub suite: String, pub machine: String, pub results: Vec, pub passed: Vec, pub finished: bool, /// Sprite suites: the CRC checks alone (function, milestone 4) per test. pub function: Vec, } impl Outcome { pub fn summary(&self) -> String { let mut text = format!( "{}/{}", self.passed.iter().filter(|p| **p).count(), self.passed.len() ); if !self.function.is_empty() { text += &format!( " (CRCs {}/{})", self.function.iter().filter(|p| **p).count(), self.function.len() ); } text } } fn c_block(text: &str, name: &str) -> Option { let re = Regex::new(&format!(r"(?s){name}\s*\[[^\]]*\]\s*=\s*\{{(.*?)\}};")).unwrap(); re.captures(text).map(|c| c[1].to_string()) } fn ints(text: &str) -> Vec { let re = Regex::new(r"0x[0-9A-Fa-f]+|\b\d+\b").unwrap(); re.find_iter(text) .map(|m| { let v = m.as_str(); match v.strip_prefix("0x") { Some(h) => i64::from_str_radix(h, 16).unwrap(), None => v.parse().unwrap(), } }) .collect() } fn strip_comments(text: &str) -> String { Regex::new(r"(?s)/\*.*?\*/") .unwrap() .replace_all(text, "") .to_string() } fn expects(text: &str, macro_name: &str) -> Vec> { let re = Regex::new(&format!(r"{macro_name}\(([^)]*)\)")).unwrap(); re.captures_iter(text).map(|c| ints(&c[1])).collect() } pub fn parse_suite(name: &str) -> Suite { let text = std::fs::read_to_string(source_dir().join(name).join("main.c")) .unwrap_or_else(|e| panic!("{name}/main.c: {e}")); let defines: BTreeMap = Regex::new(r"#define\s+(\w+)\s+(\d+)") .unwrap() .captures_iter(&text) .map(|c| (c[1].to_string(), c[2].parse().unwrap())) .collect(); let tests = defines["TEST_COUNT"]; let results = defines.get("RESULT_COUNT").copied().unwrap_or(tests); let names_block = c_block(&text, "k_test_names").unwrap_or_default(); let names: Vec = Regex::new(r#""([^"]*)""#) .unwrap() .captures_iter(&names_block) .map(|c| c[1].to_string()) .collect(); let block = c_block(&text, "k_expected_results"); let timing_block = c_block(&text, "k_expected_timings"); if block.is_none() { if let Some(timing_block) = timing_block { let crcs = strip_comments(&c_block(&text, "k_expected_crcs").unwrap_or_default()); let timings: Vec<(i64, i64)> = expects(&timing_block, "EXPECT_RANGE16") .into_iter() .map(|v| (v[0], v[1])) .collect(); let crc_values = expects(&crcs, "EXPECT"); let mut expected = Vec::new(); for t in 0..tests { expected.extend([ vec![], vec![], crc_values[2 * t].clone(), crc_values[2 * t + 1].clone(), ]); } let groups = (0..tests).map(|t| (4 * t, 4)).collect(); return Suite { name: name.into(), results, names, expected, groups, zero_is_pass: false, timings, }; } let groups = (0..tests).map(|t| (t, 1)).collect(); return Suite { name: name.into(), results, names, expected: vec![], groups, zero_is_pass: true, timings: vec![], }; } let block = strip_comments(&block.unwrap()); let expected = expects(&block, "EXPECT"); let offsets = c_block(&text, "k_test_offsets"); let counts = c_block(&text, "k_test_counts"); let groups = match (offsets, counts) { (Some(o), Some(c)) => ints(&o) .into_iter() .zip(ints(&c)) .map(|(a, b)| (a as usize, b as usize)) .collect(), _ => { let per = expected.len() / tests; (0..tests).map(|t| (t * per, per)).collect() } }; Suite { name: name.into(), results, names, expected, groups, zero_is_pass: false, timings: vec![], } } pub fn symbols(name: &str) -> BTreeMap { let mut table = BTreeMap::new(); let text = std::fs::read_to_string(build_dir().join(name).join(format!("{name}.sym"))) .unwrap_or_default(); for line in text.lines() { let parts: Vec<&str> = line.split_whitespace().collect(); if parts.len() == 3 && parts[0] == "al" { table.insert( parts[2].trim_start_matches('.').to_string(), usize::from_str_radix(parts[1], 16).unwrap(), ); } } table } pub fn boot(name: &str, machine: Machine) -> Lynx { let description = load_path(&build_dir().join(name).join(format!("{name}.lnx")), None) .unwrap_or_else(|e| panic!("{e}")); let rom = bootrom::find(None).ok().flatten(); let mut board = Lynx::new( &description.payload, description.bank0_block, machine, rom.as_deref(), &[], 0, ); board.reset(); board } pub fn run(name: &str, machine: Machine, seconds: f64) -> Outcome { let suite = parse_suite(name); let labels = symbols(name); let (entry, results_at) = (labels["_run_tests"] as u16, labels["_g_results"]); let mut board = boot(name, machine); let limit = board.tick() + (seconds * TICKS_PER_SECOND as f64) as i64; while board.cpu.pc != entry && board.tick() < limit { board.step(); } let mut ret = None; if board.cpu.pc == entry { let s = board.cpu.s as usize; let ram = &board.hw().ram; let r = ((ram[0x100 + ((s + 1) & 0xFF)] as usize | ((ram[0x100 + ((s + 2) & 0xFF)] as usize) << 8)) + 1) & 0xFFFF; ret = Some(r as u16); while board.cpu.pc != r as u16 && board.tick() < limit { board.step(); } } let finished = matches!(ret, Some(r) if board.cpu.pc == r); let data = board.hw().ram[results_at..results_at + suite.results].to_vec(); let mut outcome = Outcome { suite: name.into(), machine: machine.name.into(), results: data.clone(), passed: vec![], finished, function: vec![], }; for (t, &(offset, count)) in suite.groups.iter().enumerate() { if !finished { // The results are untouched RAM (zeros); a suite whose expectations are // zero would otherwise "pass" without running. outcome.passed.push(false); if !suite.timings.is_empty() { outcome.function.push(false); } continue; } if suite.zero_is_pass { outcome.passed.push(data[offset] == 0); continue; } if !suite.timings.is_empty() { let crc_ok = suite.expected[offset + 2].contains(&(data[offset + 2] as i64)) && suite.expected[offset + 3].contains(&(data[offset + 3] as i64)); let (low, high) = suite.timings[t]; let duration = data[offset] as i64 | ((data[offset + 1] as i64) << 8); outcome.function.push(crc_ok); outcome .passed .push(crc_ok && low <= duration && duration <= high); continue; } let ok = (offset..offset + count) .all(|i| i < suite.expected.len() && suite.expected[i].contains(&(data[i] as i64))); outcome.passed.push(ok); } outcome } pub fn report(outcome: &Outcome) -> String { let suite = parse_suite(&outcome.suite); let mut lines = vec![format!( "{} on {}: {} tests pass{}", outcome.suite, outcome.machine, outcome.summary(), if outcome.finished { "" } else { " (run_tests did not return)" } )]; let hex = |v: &[u8]| { v.iter() .map(|b| format!("{b:02X}")) .collect::>() .join(" ") }; let alts = |v: &Vec| { v.iter() .map(|b| format!("{b:02X}")) .collect::>() .join("/") }; for (t, (&(offset, count), &ok)) in suite.groups.iter().zip(&outcome.passed).enumerate() { let name = suite .names .get(t) .cloned() .unwrap_or_else(|| format!("test {}", t + 1)); let got = hex(&outcome.results[offset..offset + count]); let mut want = String::new(); if !suite.timings.is_empty() { let (low, high) = suite.timings[t]; let duration = outcome.results[offset] as i64 | ((outcome.results[offset + 1] as i64) << 8); let crcs = format!( "{} {}", alts(&suite.expected[offset + 2]), alts(&suite.expected[offset + 3]) ); let crc = if outcome.function[t] { "CRC ok".to_string() } else { format!("CRC want {crcs}") }; want = format!(" time {duration:04X} in {low:04X}-{high:04X}? {crc}"); } else if !ok && !suite.expected.is_empty() { want = format!( " want {}", (offset..offset + count) .map(|i| suite .expected .get(i) .map(alts) .unwrap_or_else(|| "?".into())) .collect::>() .join(" ") ); } lines.push(format!( " {:2} {} {:<16} {got}{want}", t + 1, if ok { "PASS" } else { "FAIL" }, name )); } lines.join("\n") }