// SPDX-License-Identifier: MIT //! The conformance kit: manifests of bus events, and traces of what the chip drives. //! //! A port of this core proves itself by running each manifest in //! `examples/conformance` (here `tests/conformance`) and writing the trace below, then //! comparing it with the one committed beside the manifest (ay8910-python's //! docs/conformance.md). The committed traces were made by ay8910-python; the AY-3-8910 //! ones were checked against the die model when they were made (its scripts/make_examples.py). //! //! ```text //! ay8910-conformance trace MANIFEST.json # the trace, to stdout //! ay8910-conformance diff MANIFEST.json PORT.trace # the first line that differs //! ay8910-conformance check tests/conformance # every example, against its trace //! ``` //! //! Trace format, version 1: //! //! ```text //! # ay8910-trace 1 //! # NAME VARIANT //! L the three channels' DAC codes after input clock //! R a byte read, input clocks into the run //! P the levels the chip drives on ports A and B //! # end clocks events //! ``` //! //! An `L` line is written before the first clock (`clock` 0) and then after every //! input clock that leaves the codes different from the last line's; a `P` line //! likewise at 0 and whenever an event changes what the chip drives ($FF for a port //! that is an input). The codes hold between lines, so two equal traces are the same //! output at every input clock. //! //! A transcription of ay8910-python's `conformance.py` (at a3bb485). Where Rust forced a //! difference: //! //! - Python reads the manifest with its standard `json` module; this crate imports nothing, //! so a small JSON reader ([`Json`]) is here. It reads every manifest Python writes. A //! manifest whose fields have the wrong JSON types (a string for a number, say) is refused //! with an error, where Python might coerce or fail with another exception. //! - `trace_manifest` returns the lines as a `Vec` (Python yields them). //! - The command line is [`main`], with the arguments and the output passed in, and //! `src/bin/ay8910-conformance.rs` calls it; Python's `argparse` usage messages are not //! reproduced, but the commands, the output and the exit status (0, 1, 2) are. //! - The chip's port callables are its `port_*_in` levels and `port_*_out` queue //! (chip.rs's header), so the trace sets the levels at each `pins_*` event and drains the //! queue after each event, where Python's callables would have been called. use std::fmt; use std::io::{Read, Write}; use std::path::Path; use crate::chip::PSG; use crate::variants::variant as find_variant; pub const TRACE_HEADER: &str = "# ay8910-trace 1"; pub const MANIFEST_SCHEMA_VERSION: i64 = 1; /// Event kinds: which of `a` and `b` each uses (ay8910-python's docs/conformance.md). pub const KINDS: [(&str, &str); 9] = [ ("write", "register, value: an address byte and a data byte"), ("read", "register: an address byte and a read"), ("select", "the address byte alone"), ("data", "a data byte alone (in b)"), ("read_data", "a read alone"), ("reset", "/RESET"), ("pins_a", "the levels the outside drives onto port A"), ("pins_b", "the same for port B"), ( "divider", "the /SEL pin's effect: 1 or 2 input clocks per internal clock", ), ]; fn kind_names() -> String { KINDS .iter() .map(|(name, _)| *name) .collect::>() .join(", ") } /// One event, applied when `t` input clocks have run. #[derive(Clone, Debug, PartialEq, Eq)] pub struct Event { pub t: u64, pub kind: String, pub a: u8, pub b: u8, } impl Event { /// Python's `Event(t, kind, a, b)` with its `__post_init__` checks. pub fn new(t: i64, kind: &str, a: i64, b: i64) -> Result { if !KINDS.iter().any(|(name, _)| *name == kind) { return Err(format!("unknown event kind {kind:?} ({})", kind_names())); } if t < 0 || !(0..=0xFF).contains(&a) || !(0..=0xFF).contains(&b) { return Err(format!( "event out of range: Event(t={t}, kind={kind:?}, a={a}, b={b})" )); } Ok(Event { t: t as u64, kind: kind.to_string(), a: a as u8, b: b as u8, }) } } /// A run: the variant, the events in clock order, and how many clocks to run. #[derive(Clone, Debug, PartialEq, Eq)] pub struct Manifest { pub name: String, pub variant: String, pub events: Vec, pub clocks: u64, } impl Manifest { /// Python's `Manifest(name, variant, events, clocks)` with its `__post_init__` checks. pub fn new( name: &str, variant: &str, events: Vec, clocks: u64, ) -> Result { let Some(part) = find_variant(variant) else { let names: Vec = crate::VARIANTS.iter().map(|v| v.name.to_string()).collect(); return Err(format!( "unknown variant {variant:?} ({})", names.join(", ") )); }; if events.windows(2).any(|pair| pair[1].t < pair[0].t) { return Err("events must be in clock order".into()); } if events.last().is_some_and(|last| last.t > clocks) { return Err("an event falls after the end of the run".into()); } if !part.has_sel_pin && events.iter().any(|e| e.kind == "divider") { return Err(format!( "{variant} has no /SEL pin to change the divider with" )); } if events .iter() .any(|e| e.kind == "divider" && !matches!(e.a, 1 | 2)) { return Err("the divider is 1 or 2".into()); } Ok(Manifest { name: name.to_string(), variant: variant.to_string(), events, clocks, }) } /// The manifest's JSON form, one event to a line. pub fn to_json(&self) -> String { let events: Vec = self .events .iter() .map(|e| format!(" [{}, {}, {}, {}]", e.t, json_string(&e.kind), e.a, e.b)) .collect(); format!( "{{\n \"version\": {},\n \"name\": {},\n \"variant\": {},\n \"clocks\": {},\n \"events\": [\n{}\n ]\n}}\n", MANIFEST_SCHEMA_VERSION, json_string(&self.name), json_string(&self.variant), self.clocks, events.join(",\n"), ) } } /// The first line where two traces differ (1-based), and both lines. #[derive(Clone, Debug, PartialEq, Eq)] pub struct TraceDifference { pub line: usize, pub reference: String, pub external: String, } impl fmt::Display for TraceDifference { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( f, "traces differ at line {}\n reference: {}\n external: {}", self.line, self.reference, self.external ) } } /// Run `manifest` on this chip, returning the trace's lines (without newlines). pub fn trace_manifest(manifest: &Manifest) -> Vec { let part = find_variant(&manifest.variant).expect("a checked manifest names a part"); let mut chip = PSG::with_record(part, false); let mut outside = [0xFFu8, 0xFF]; let mut driven = [0xFFu8, 0xFF]; chip.port_a_in = Some(outside[0]); chip.port_b_in = Some(outside[1]); chip.port_a_out = true; chip.port_b_out = true; let mut lines = vec![ TRACE_HEADER.to_string(), format!("# {} {}", manifest.name, manifest.variant), ]; let mut last = chip.levels(); let mut last_driven = driven; lines.push(format!("L 0 {} {} {}", last[0], last[1], last[2])); lines.push(format!("P 0 {} {}", last_driven[0], last_driven[1])); let advance = |chip: &mut PSG, last: &mut [u8; 3], lines: &mut Vec, t: u64| { while chip.clock < t { chip.tick(); let now = chip.levels(); if now != *last { *last = now; lines.push(format!("L {} {} {} {}", chip.clock, now[0], now[1], now[2])); } } }; for event in &manifest.events { advance(&mut chip, &mut last, &mut lines, event.t); match event.kind.as_str() { "write" => chip.write_register(event.a, event.b), "read" => { chip.select(event.a); lines.push(format!("R {} {}", chip.clock, chip.read())); } "select" => chip.select(event.a), "data" => chip.write(event.b), "read_data" => lines.push(format!("R {} {}", chip.clock, chip.read())), "reset" => { let clock = chip.clock; chip.reset(); chip.clock = clock; } "pins_a" => { outside[0] = event.a; chip.port_a_in = Some(outside[0]); } "pins_b" => { outside[1] = event.a; chip.port_b_in = Some(outside[1]); } _ => chip.clock_divider = event.a, } for (register, value) in chip.take_port_changes() { driven[(register - crate::chip::PORT_A) as usize] = value; } if driven != last_driven { last_driven = driven; lines.push(format!( "P {} {} {}", chip.clock, last_driven[0], last_driven[1] )); } } advance(&mut chip, &mut last, &mut lines, manifest.clocks); lines.push(format!( "# end {} clocks {} events", chip.clock, manifest.events.len() )); lines } /// The first line where `external` differs from `reference`, or `None`. pub fn diff_traces(reference: R, external: E) -> Option where R: IntoIterator, R::Item: AsRef, E: IntoIterator, E::Item: AsRef, { let mut line = 0; let (mut ref_iter, mut ext_iter) = (reference.into_iter(), external.into_iter()); loop { line += 1; let reference = ref_iter .next() .map(|s| s.as_ref().trim_end_matches('\n').to_string()); let external = ext_iter .next() .map(|s| s.as_ref().trim_end_matches('\n').to_string()); if reference.is_none() && external.is_none() { return None; } if reference != external { // Python's `ref or "(end of trace)"`: an empty line reads as the end too. let shown = |line: Option| match line { Some(text) if !text.is_empty() => text, _ => "(end of trace)".to_string(), }; return Some(TraceDifference { line, reference: shown(reference), external: shown(external), }); } } } /// A manifest from its JSON form (ay8910-python's docs/conformance.md), strictly checked. pub fn manifest_from_json(text: &str) -> Result { manifest_from_value(&Json::parse(text)?) } /// Python's `manifest_from_dict`. pub fn manifest_from_value(value: &Json) -> Result { let Json::Object(fields) = value else { return Err("a manifest is a JSON object".into()); }; let mut unknown: Vec<&str> = fields .iter() .map(|(key, _)| key.as_str()) .filter(|key| !["version", "name", "variant", "events", "clocks"].contains(key)) .collect(); if !unknown.is_empty() { unknown.sort(); unknown.dedup(); return Err(format!("unknown manifest keys: {unknown:?}")); } let version = value.get("version"); if version.and_then(Json::as_int) != Some(MANIFEST_SCHEMA_VERSION) { return Err(format!("unsupported manifest version {version:?}")); } let mut events = Vec::new(); if let Some(items) = value.get("events") { let Json::Array(items) = items else { return Err("events is not a list".into()); }; for (index, item) in items.iter().enumerate() { let bad = || format!("event {index} is not [t, kind, a, b]"); let Json::Array(parts) = item else { return Err(bad()); }; if parts.len() != 4 { return Err(bad()); } let number = |part: &Json| part.as_int().ok_or_else(bad); let Json::String(kind) = &parts[1] else { return Err(format!( "unknown event kind {:?} ({})", parts[1], kind_names() )); }; events.push(Event::new( number(&parts[0])?, kind, number(&parts[2])?, number(&parts[3])?, )?); } } let text = |key: &str| match value.get(key) { Some(Json::String(s)) => Ok(s.clone()), Some(other) => Err(format!("{key} is not a string: {other:?}")), None => Err(format!("missing key {key:?}")), }; let clocks = match value.get("clocks") { Some(clocks) => clocks .as_int() .filter(|&c| c >= 0) .ok_or_else(|| format!("clocks is not a count: {clocks:?}"))?, None => return Err("missing key \"clocks\"".into()), }; Manifest::new(&text("name")?, &text("variant")?, events, clocks as u64) } pub fn load_manifest(path: &Path) -> Result { let text = std::fs::read_to_string(path).map_err(|e| format!("{}: {e}", path.display()))?; manifest_from_json(&text) } /// Every manifest in `directory` whose trace differs from the one beside it. pub fn check(directory: &Path) -> Result, String> { let mut paths: Vec<_> = std::fs::read_dir(directory) .map_err(|e| format!("{}: {e}", directory.display()))? .filter_map(|entry| entry.ok().map(|e| e.path())) .filter(|path| path.extension().is_some_and(|ext| ext == "json")) .collect(); paths.sort(); let mut failures = Vec::new(); for path in paths { let reference = std::fs::read_to_string(path.with_extension("trace")) .map_err(|e| format!("{}: {e}", path.display()))?; let manifest = load_manifest(&path)?; if diff_traces(reference.lines(), trace_manifest(&manifest)).is_some() { failures.push(path.file_stem().unwrap().to_string_lossy().into_owned()); } } Ok(failures) } /// `trace` writes the reference trace; `diff` reports the first difference; /// `check` runs every example in a directory. /// /// Exit status: 0 on success or equal traces, 1 on a difference, 2 on bad input. pub fn main(argv: &[String], out: &mut dyn Write) -> i32 { let usage = "usage: ay8910-conformance {trace MANIFEST [--out FILE] | diff MANIFEST TRACE | check DIRECTORY}"; let fail = |out: &mut dyn Write, message: &str| { let _ = writeln!(out, "error: {message}"); 2 }; let Some(command) = argv.first().map(String::as_str) else { return fail(out, usage); }; let rest = &argv[1..]; if command == "check" { let [directory] = rest else { return fail(out, usage); }; return match check(Path::new(directory)) { Ok(failures) => { for name in &failures { let _ = writeln!(out, "differs: {name}"); } let _ = writeln!(out, "{} differ", failures.len()); i32::from(!failures.is_empty()) } Err(message) => fail(out, &message), }; } let (manifest_path, trace_arg, out_file) = match (command, rest) { ("trace", [manifest]) => (manifest, None, None), ("trace", [manifest, flag, file]) if flag == "--out" => (manifest, None, Some(file)), ("diff", [manifest, trace]) => (manifest, Some(trace), None), _ => return fail(out, usage), }; let manifest = match load_manifest(Path::new(manifest_path)) { Ok(manifest) => manifest, Err(message) => return fail(out, &message), }; if command == "trace" { let text: String = trace_manifest(&manifest) .iter() .map(|line| format!("{line}\n")) .collect(); if let Some(file) = out_file { if let Err(e) = std::fs::write(file, text) { return fail(out, &format!("{file}: {e}")); } } else { let _ = out.write_all(text.as_bytes()); } return 0; } let trace_arg = trace_arg.expect("diff has a trace"); let mut text = String::new(); let read = if trace_arg == "-" { std::io::stdin().read_to_string(&mut text).map(|_| ()) } else { std::fs::read_to_string(trace_arg).map(|t| text = t) }; if let Err(e) = read { return fail(out, &format!("{trace_arg}: {e}")); } match diff_traces(trace_manifest(&manifest), text.lines()) { None => { let _ = writeln!(out, "{}: traces are identical", manifest.name); 0 } Some(difference) => { let _ = writeln!(out, "{}: {difference}", manifest.name); 1 } } } // -- a small JSON reader ----------------------------------------------------------------- /// A JSON value, as much of JSON as a manifest can hold (and the rest, for refusing it). #[derive(Clone, Debug, PartialEq)] pub enum Json { Null, Bool(bool), Number(f64), String(String), Array(Vec), /// Keys in the order written; a repeated key's last value wins, as in Python. Object(Vec<(String, Json)>), } impl Json { pub fn parse(text: &str) -> Result { let mut reader = Reader { bytes: text.as_bytes(), at: 0, }; let value = reader.value()?; reader.space(); if reader.at != reader.bytes.len() { return Err(format!("JSON: extra data at byte {}", reader.at)); } Ok(value) } /// An object's value for `key` (the last, if repeated). pub fn get(&self, key: &str) -> Option<&Json> { match self { Json::Object(fields) => fields.iter().rev().find(|(k, _)| k == key).map(|(_, v)| v), _ => None, } } /// A number that is a whole number. pub fn as_int(&self) -> Option { match *self { Json::Number(n) if n.fract() == 0.0 && n.abs() < 9.007_199_254_740_992e15 => { Some(n as i64) } _ => None, } } } struct Reader<'a> { bytes: &'a [u8], at: usize, } impl Reader<'_> { fn error(&self, what: &str) -> Result { Err(format!("JSON: {what} at byte {}", self.at)) } fn space(&mut self) { while self .bytes .get(self.at) .is_some_and(|b| b" \t\r\n".contains(b)) { self.at += 1; } } fn literal(&mut self, word: &str, value: Json) -> Result { if self.bytes[self.at..].starts_with(word.as_bytes()) { self.at += word.len(); Ok(value) } else { self.error("unexpected character") } } fn value(&mut self) -> Result { self.space(); match self.bytes.get(self.at) { None => self.error("unexpected end"), Some(b'{') => { self.at += 1; let mut fields = Vec::new(); self.space(); if self.bytes.get(self.at) == Some(&b'}') { self.at += 1; return Ok(Json::Object(fields)); } loop { self.space(); let key = self.string()?; self.space(); if self.bytes.get(self.at) != Some(&b':') { return self.error("expected ':'"); } self.at += 1; fields.push((key, self.value()?)); self.space(); match self.bytes.get(self.at) { Some(b',') => self.at += 1, Some(b'}') => { self.at += 1; return Ok(Json::Object(fields)); } _ => return self.error("expected ',' or '}'"), } } } Some(b'[') => { self.at += 1; let mut items = Vec::new(); self.space(); if self.bytes.get(self.at) == Some(&b']') { self.at += 1; return Ok(Json::Array(items)); } loop { items.push(self.value()?); self.space(); match self.bytes.get(self.at) { Some(b',') => self.at += 1, Some(b']') => { self.at += 1; return Ok(Json::Array(items)); } _ => return self.error("expected ',' or ']'"), } } } Some(b'"') => Ok(Json::String(self.string()?)), Some(b't') => self.literal("true", Json::Bool(true)), Some(b'f') => self.literal("false", Json::Bool(false)), Some(b'n') => self.literal("null", Json::Null), Some(_) => self.number(), } } fn number(&mut self) -> Result { let start = self.at; while self .bytes .get(self.at) .is_some_and(|b| b"+-.eE0123456789".contains(b)) { self.at += 1; } let text = std::str::from_utf8(&self.bytes[start..self.at]).unwrap_or(""); match text.parse::() { Ok(n) if !text.is_empty() => Ok(Json::Number(n)), _ => { self.at = start; self.error("bad number") } } } fn string(&mut self) -> Result { if self.bytes.get(self.at) != Some(&b'"') { return self.error("expected a string"); } self.at += 1; let mut out = String::new(); loop { let Some(&byte) = self.bytes.get(self.at) else { return self.error("unterminated string"); }; self.at += 1; match byte { b'"' => return Ok(out), b'\\' => { let Some(&escape) = self.bytes.get(self.at) else { return self.error("unterminated string"); }; self.at += 1; match escape { b'"' => out.push('"'), b'\\' => out.push('\\'), b'/' => out.push('/'), b'b' => out.push('\u{8}'), b'f' => out.push('\u{c}'), b'n' => out.push('\n'), b'r' => out.push('\r'), b't' => out.push('\t'), b'u' => { let hex = self .bytes .get(self.at..self.at + 4) .and_then(|h| std::str::from_utf8(h).ok()) .and_then(|h| u32::from_str_radix(h, 16).ok()); let Some(code) = hex else { return self.error("bad \\u escape"); }; self.at += 4; out.push(char::from_u32(code).unwrap_or('\u{FFFD}')); } _ => return self.error("bad escape"), } } _ => { // A UTF-8 sequence: copy its bytes whole. let start = self.at - 1; let mut end = self.at; while end < self.bytes.len() && (self.bytes[end] & 0xC0) == 0x80 { end += 1; } match std::str::from_utf8(&self.bytes[start..end]) { Ok(text) => out.push_str(text), Err(_) => return self.error("bad UTF-8"), } self.at = end; } } } } } /// A string as Python's `json.dumps` writes it (ASCII only, the usual escapes). pub fn json_string(text: &str) -> String { let mut out = String::from("\""); for ch in text.chars() { match ch { '"' => out.push_str("\\\""), '\\' => out.push_str("\\\\"), '\n' => out.push_str("\\n"), '\r' => out.push_str("\\r"), '\t' => out.push_str("\\t"), '\u{8}' => out.push_str("\\b"), '\u{c}' => out.push_str("\\f"), c if (c as u32) < 0x20 || (c as u32) > 0x7E => { let mut units = [0u16; 2]; for unit in c.encode_utf16(&mut units) { out.push_str(&format!("\\u{unit:04x}")); } } c => out.push(c), } } out.push('"'); out }