tabnas_support/register.rs
1// Copyright (c) 2026 tabnas, MIT License
2
3// A divergence register: the places two ports of one grammar DISAGREE,
4// recorded in a fixture every port executes.
5//
6// The audit this exists for found 29 recorded divergence claims
7// contradicted by execution, and one file that had been wrong in BOTH
8// directions at once. Prose does not hold. What did hold was the one
9// mechanism that ran: a register whose rows are executed, so a row that
10// stops being true fails the build.
11//
12// The property that makes it work is not that a regression fails. It is
13// that a FIX fails too. When a port is repaired to agree with the other,
14// the register still claims they differ, so the suite goes red and names
15// the row to delete. A register cannot quietly outlive the divergence it
16// records, which is precisely how the 29 prose claims survived.
17//
18// `ts/src/register.ts` and `go/register.go` mirror all of this.
19
20use std::path::Path;
21
22use crate::expect::{equal_value, equal_value_with, error_code, is_error_expect, parse_expect};
23use crate::runner::{report, Runner};
24use crate::spec::{load_spec, Column, Row, SpecFile};
25use crate::{Error, Result};
26
27/// A fixture of recorded divergences, run by every port.
28///
29/// Each row gives an input and one cell per runtime, written in the same
30/// vocabulary as an ordinary fixture's expected column: a JSON value, or
31/// `ERROR:<code>`. Every row is checked three ways:
32///
33/// 1. The row must actually record a divergence. If every runtime cell
34/// says the same thing, the row asserts nothing and would pass
35/// forever; that is the shape of the claims this mechanism replaces.
36/// 2. This runtime must still produce what the register says it does.
37/// 3. When it does not, and it now produces what ANOTHER runtime's cell
38/// says, the failure says the divergence is CLOSED and names the row
39/// to delete, rather than reporting it as a regression, which is the
40/// opposite conclusion.
41#[derive(Clone)]
42pub struct Register {
43 /// Supplies the parse hook and every comparison rule. The register
44 /// adds which column to read and what a mismatch means; it does not
45 /// get its own idea of what "equal" is.
46 runner: Runner,
47 /// The column holding THIS runtime's answer: `rust` in a Rust suite.
48 /// The suites of the ports run the same file and read different
49 /// columns of it.
50 runtime: String,
51 /// Every runtime column in the file, this one included. Named rather
52 /// than inferred from the header, because inferring would silently
53 /// treat a `note` or `issue` column as a runtime and then report that
54 /// the ports "agree" with a sentence.
55 runtimes: Vec<String>,
56}
57
58impl Register {
59 /// A register reading the `runtime` column of a file whose runtime
60 /// columns are `runtimes`.
61 pub fn new(runner: Runner, runtime: &str, runtimes: &[&str]) -> Self {
62 Register {
63 runner,
64 runtime: runtime.to_string(),
65 runtimes: runtimes.iter().map(|name| name.to_string()).collect(),
66 }
67 }
68
69 /// Why this register cannot run at all, or `Ok`.
70 fn check(&self) -> Result<()> {
71 if self.runtime.is_empty() {
72 return Err(Error("Register: runtime is required".to_string()));
73 }
74 if self.runtimes.len() < 2 {
75 return Err(Error(format!(
76 "Register: a divergence needs at least two runtimes, got {:?}",
77 self.runtimes
78 )));
79 }
80 if !self.runtimes.contains(&self.runtime) {
81 return Err(Error(format!(
82 "Register: runtimes must include {:?}, got {:?}",
83 self.runtime, self.runtimes
84 )));
85 }
86 Ok(())
87 }
88
89 /// A runtime column the file does not have. A typo in `runtimes`
90 /// would otherwise surface as a missing-column error on some later
91 /// row, or not at all.
92 fn check_columns(&self, row: &Row) -> Result<()> {
93 for name in &self.runtimes {
94 if row.index_of(name).is_none() {
95 return Err(Error(format!(
96 "no column named {name:?} (Register runtimes)"
97 )));
98 }
99 }
100 Ok(())
101 }
102
103 /// Do two expectation CELLS mean the same thing?
104 ///
105 /// Compared by meaning, not by bytes. `1` and `1.0`, or two objects
106 /// written with their keys in a different order, are the same
107 /// expectation to the runner, so a row whose cells differ only that
108 /// way records no divergence, and comparing the raw strings would let
109 /// it sit there passing in every port forever while describing a
110 /// disagreement that does not exist.
111 fn same_expectation(&self, a: &str, b: &str, row: &Row) -> bool {
112 if a == b {
113 return true;
114 }
115
116 if is_error_expect(a) || is_error_expect(b) {
117 if !is_error_expect(a) || !is_error_expect(b) {
118 return false;
119 }
120 return match (error_code(a), error_code(b)) {
121 (Ok(code_a), Ok(code_b)) => code_a == code_b,
122 _ => false,
123 };
124 }
125
126 let read = |cell: &str| -> Result<_> {
127 match self.runner.parse_expected_hook() {
128 Some(hook) => hook(cell, row),
129 None => parse_expect(cell),
130 }
131 };
132
133 // A cell the fixture's own reader cannot parse is a defect the
134 // runner will report with a better message when it runs the row.
135 // Saying "these differ" here defers to that.
136 let (Ok(value_a), Ok(value_b)) = (read(a), read(b)) else {
137 return false;
138 };
139
140 match self.runner.normalize_hook() {
141 Some(normalize) => equal_value_with(&value_a, &value_b, normalize),
142 None => equal_value(&value_a, &value_b),
143 }
144 }
145
146 /// Run one row and return the failure rather than reporting it.
147 pub fn check_row(&self, row: &Row, input: &str) -> Result<()> {
148 self.check()?;
149 // Checked here too, not only in `run_spec`: this is public, and a
150 // caller driving it directly would otherwise read a missing
151 // column as an empty expectation.
152 self.check_columns(row)
153 .map_err(|error| Error(format!("{}: {error}", row.location())))?;
154
155 let mine = row.named(&self.runtime).to_string();
156 let others: Vec<(String, String)> = self
157 .runtimes
158 .iter()
159 .filter(|name| **name != self.runtime)
160 .map(|name| (name.clone(), row.named(name).to_string()))
161 .collect();
162
163 // 1. Does this row record a divergence at all?
164 if others
165 .iter()
166 .all(|(_, cell)| self.same_expectation(cell, &mine, row))
167 {
168 return Err(Error(format!(
169 "{}: every runtime column means {mine:?}, so this row records no divergence \
170 and can never fail meaningfully. Delete it, or correct the cells to what \
171 the runtimes actually do.",
172 row.location()
173 )));
174 }
175
176 // ONE parse per row, whatever it ends up being compared against.
177 let runner = self
178 .runner
179 .reading(Column::Name(self.runtime.clone()))
180 .parsing_once();
181
182 // 2. Does this runtime still do what the register says?
183 let Err(mismatch) = runner.check_row(row, input, &mine) else {
184 return Ok(());
185 };
186
187 // 3. It does not. Which of the OTHERS does it now agree with?
188 let converged: Vec<&(String, String)> = others
189 .iter()
190 .filter(|(_, cell)| runner.check_row(row, input, cell).is_ok())
191 .collect();
192
193 // 4. None. An ordinary regression; the runner's own message says
194 // what was produced and what was expected.
195 if converged.is_empty() {
196 return Err(mismatch);
197 }
198
199 let names: Vec<&str> = converged.iter().map(|(name, _)| name.as_str()).collect();
200
201 // Converged with EVERY other runtime: the divergence is gone.
202 if converged.len() == others.len() {
203 return Err(Error(format!(
204 "{}: this divergence is CLOSED. {} now produces what the {} column(s) record \
205 ({:?}), not its own ({mine:?}).\n \
206 This is the register working: a fixed divergence fails as loudly as a \
207 regressed one, so the row cannot outlive it.\n \
208 DELETE this row. Do not edit it to match: that would record a divergence \
209 that no longer exists, which is what this mechanism exists to prevent.",
210 row.location(),
211 self.runtime,
212 names.join(", "),
213 converged[0].1
214 )));
215 }
216
217 // Converged with SOME. The row still records a live disagreement
218 // between the runtimes that have not converged, so deleting it
219 // would drop that coverage. Only this runtime's own column is
220 // stale.
221 let live: Vec<&str> = others
222 .iter()
223 .filter(|other| !converged.iter().any(|c| c.0 == other.0))
224 .map(|(name, _)| name.as_str())
225 .collect();
226
227 Err(Error(format!(
228 "{}: this divergence is PARTIALLY closed. {} now agrees with {}, but not with {}.\n \
229 Do NOT delete this row: it still records a live disagreement between the \
230 runtimes that have not converged.\n \
231 UPDATE the {} column to what it now produces, instead of {mine:?}.",
232 row.location(),
233 self.runtime,
234 names.join(", "),
235 live.join(", "),
236 self.runtime
237 )))
238 }
239
240 /// Run every row of an already-loaded register. `Err` when it cannot
241 /// run at all; otherwise the failures, one per failing row.
242 pub fn run_spec(&self, spec: &SpecFile) -> Result<Vec<String>> {
243 self.check()?;
244 // Checked through a runner whose expectation column IS this
245 // runtime's, because that is the column a register reads.
246 let reading = self.runner.reading(Column::Name(self.runtime.clone()));
247 reading.check_spec(spec)?;
248 self.check_columns(&spec.rows[0])
249 .map_err(|error| Error(format!("{}: {error}", spec.file)))?;
250
251 let input_col = spec.rows[0].resolve(self.runner.input_column())?;
252 Ok(spec
253 .rows
254 .iter()
255 .filter_map(|row| {
256 let input = row.unesc(input_col);
257 self.check_row(row, &input).err().map(|error| error.0)
258 })
259 .collect())
260 }
261
262 /// Load one register file by path and run it; see [`Register::run_spec`].
263 pub fn run_file(&self, path: impl AsRef<Path>) -> Result<Vec<String>> {
264 self.check()?;
265 self.run_spec(&load_spec(path, self.runner.load_options())?)
266 }
267
268 /// Run an already-loaded register, panicking with every failing row.
269 pub fn spec(&self, spec: &SpecFile) {
270 report(self.run_spec(spec));
271 }
272
273 /// Load one register file by path and run it, panicking on failure.
274 pub fn file(&self, path: impl AsRef<Path>) {
275 report(self.run_file(path));
276 }
277}
278
279/// Declare that a repo records no divergences at all.
280///
281/// An empty register is legitimate; an empty FILE is not, because the
282/// runner cannot tell "no rows" from "the loader read nothing". Call this
283/// from a test so the claim is stated in the suite rather than assumed
284/// from a file nobody notices is missing. It asserts nothing; its value is
285/// that the suite names the claim out loud.
286pub fn no_divergences(where_: &str) {
287 let _ = where_.trim();
288}