use std::path::Path;
use crate::expect::{equal_value, equal_value_with, error_code, is_error_expect, parse_expect};
use crate::runner::{report, Runner};
use crate::spec::{load_spec, Column, Row, SpecFile};
use crate::{Error, Result};
#[derive(Clone)]
pub struct Register {
runner: Runner,
runtime: String,
runtimes: Vec<String>,
}
impl Register {
pub fn new(runner: Runner, runtime: &str, runtimes: &[&str]) -> Self {
Register {
runner,
runtime: runtime.to_string(),
runtimes: runtimes.iter().map(|name| name.to_string()).collect(),
}
}
fn check(&self) -> Result<()> {
if self.runtime.is_empty() {
return Err(Error("Register: runtime is required".to_string()));
}
if self.runtimes.len() < 2 {
return Err(Error(format!(
"Register: a divergence needs at least two runtimes, got {:?}",
self.runtimes
)));
}
if !self.runtimes.contains(&self.runtime) {
return Err(Error(format!(
"Register: runtimes must include {:?}, got {:?}",
self.runtime, self.runtimes
)));
}
Ok(())
}
fn check_columns(&self, row: &Row) -> Result<()> {
for name in &self.runtimes {
if row.index_of(name).is_none() {
return Err(Error(format!(
"no column named {name:?} (Register runtimes)"
)));
}
}
Ok(())
}
fn same_expectation(&self, a: &str, b: &str, row: &Row) -> bool {
if a == b {
return true;
}
if is_error_expect(a) || is_error_expect(b) {
if !is_error_expect(a) || !is_error_expect(b) {
return false;
}
return match (error_code(a), error_code(b)) {
(Ok(code_a), Ok(code_b)) => code_a == code_b,
_ => false,
};
}
let read = |cell: &str| -> Result<_> {
match self.runner.parse_expected_hook() {
Some(hook) => hook(cell, row),
None => parse_expect(cell),
}
};
let (Ok(value_a), Ok(value_b)) = (read(a), read(b)) else {
return false;
};
match self.runner.normalize_hook() {
Some(normalize) => equal_value_with(&value_a, &value_b, normalize),
None => equal_value(&value_a, &value_b),
}
}
pub fn check_row(&self, row: &Row, input: &str) -> Result<()> {
self.check()?;
self.check_columns(row)
.map_err(|error| Error(format!("{}: {error}", row.location())))?;
let mine = row.named(&self.runtime).to_string();
let others: Vec<(String, String)> = self
.runtimes
.iter()
.filter(|name| **name != self.runtime)
.map(|name| (name.clone(), row.named(name).to_string()))
.collect();
if others
.iter()
.all(|(_, cell)| self.same_expectation(cell, &mine, row))
{
return Err(Error(format!(
"{}: every runtime column means {mine:?}, so this row records no divergence \
and can never fail meaningfully. Delete it, or correct the cells to what \
the runtimes actually do.",
row.location()
)));
}
let runner = self
.runner
.reading(Column::Name(self.runtime.clone()))
.parsing_once();
let Err(mismatch) = runner.check_row(row, input, &mine) else {
return Ok(());
};
let converged: Vec<&(String, String)> = others
.iter()
.filter(|(_, cell)| runner.check_row(row, input, cell).is_ok())
.collect();
if converged.is_empty() {
return Err(mismatch);
}
let names: Vec<&str> = converged.iter().map(|(name, _)| name.as_str()).collect();
if converged.len() == others.len() {
return Err(Error(format!(
"{}: this divergence is CLOSED. {} now produces what the {} column(s) record \
({:?}), not its own ({mine:?}).\n \
This is the register working: a fixed divergence fails as loudly as a \
regressed one, so the row cannot outlive it.\n \
DELETE this row. Do not edit it to match: that would record a divergence \
that no longer exists, which is what this mechanism exists to prevent.",
row.location(),
self.runtime,
names.join(", "),
converged[0].1
)));
}
let live: Vec<&str> = others
.iter()
.filter(|other| !converged.iter().any(|c| c.0 == other.0))
.map(|(name, _)| name.as_str())
.collect();
Err(Error(format!(
"{}: this divergence is PARTIALLY closed. {} now agrees with {}, but not with {}.\n \
Do NOT delete this row: it still records a live disagreement between the \
runtimes that have not converged.\n \
UPDATE the {} column to what it now produces, instead of {mine:?}.",
row.location(),
self.runtime,
names.join(", "),
live.join(", "),
self.runtime
)))
}
pub fn run_spec(&self, spec: &SpecFile) -> Result<Vec<String>> {
self.check()?;
let reading = self.runner.reading(Column::Name(self.runtime.clone()));
reading.check_spec(spec)?;
self.check_columns(&spec.rows[0])
.map_err(|error| Error(format!("{}: {error}", spec.file)))?;
let input_col = spec.rows[0].resolve(self.runner.input_column())?;
Ok(spec
.rows
.iter()
.filter_map(|row| {
let input = row.unesc(input_col);
self.check_row(row, &input).err().map(|error| error.0)
})
.collect())
}
pub fn run_file(&self, path: impl AsRef<Path>) -> Result<Vec<String>> {
self.check()?;
self.run_spec(&load_spec(path, self.runner.load_options())?)
}
pub fn spec(&self, spec: &SpecFile) {
report(self.run_spec(spec));
}
pub fn file(&self, path: impl AsRef<Path>) {
report(self.run_file(path));
}
}
pub fn no_divergences(where_: &str) {
let _ = where_.trim();
}