tabnas_support/expect.rs
1// Copyright (c) 2026 tabnas, MIT License
2
3// Reading the `expected` column, and comparing a parse result against it.
4//
5// A fixture's expected cell is one of two things: a JSON value the parse
6// must produce, or an error the parse must raise, written `ERROR:<code>`.
7// The code is part of the contract: "it threw" is not enough, since two
8// runtimes that reject the same input for different reasons have not
9// actually agreed on anything.
10//
11// `ts/src/expect.ts` and `go/expect.go` mirror all of this.
12
13use crate::value::Value;
14use crate::{Error, Result};
15
16/// The prefix marking an expected-failure cell.
17pub const ERROR_PREFIX: &str = "ERROR";
18
19/// Is this expected cell an error expectation?
20///
21/// Exactly `ERROR`, or `ERROR:` followed by a code. Note the colon: a bare
22/// prefix test would read a legitimate `ERRORS` or `ERROR_LIST` expected
23/// value as a failure expectation and then never check the parse result
24/// at all, a fixture row that silently tests nothing.
25pub fn is_error_expect(expected: &str) -> bool {
26 expected == ERROR_PREFIX || expected.starts_with(&format!("{ERROR_PREFIX}:"))
27}
28
29/// The code from an error expectation: `ERROR:unexpected` gives
30/// `unexpected`, and a bare `ERROR` gives `""` (meaning "any code"). A
31/// trailing `@<row>:<col>` is a position expectation and is NOT part of
32/// the code; see [`error_expect`]. An error when handed a cell that is
33/// not an error expectation at all.
34pub fn error_code(expected: &str) -> Result<String> {
35 error_expect(expected).map(|expectation| expectation.code)
36}
37
38/// An error expectation, split into the parts a runner checks separately.
39#[derive(Debug, Clone, PartialEq, Eq)]
40pub struct ErrorExpect {
41 /// The code, or `""` for "any code" (a bare `ERROR`, or a cell that
42 /// pins only a position).
43 pub code: String,
44 /// 1-based source position the error must report, when the cell pins
45 /// one. Both `None` otherwise.
46 pub row: Option<usize>,
47 pub col: Option<usize>,
48}
49
50/// Read an error expectation.
51///
52/// ```text
53/// ERROR any error
54/// ERROR:unexpected that code, position unchecked
55/// ERROR:unexpected@1:8 that code, reported at row 1 col 8
56/// ERROR:@1:8 any code, reported at row 1 col 8
57/// ```
58///
59/// The position channel exists because a code alone does not pin a
60/// diagnostic. Two runtimes can agree on `unexpected` and disagree on
61/// where they say it happened, which is exactly what the fleet audit
62/// found, in several repos at once, with every code row green. A fixture
63/// that pins the position makes that disagreement a failing row instead
64/// of a difference nobody is looking at.
65///
66/// `@` rather than another colon because a code is not always a bare
67/// identifier: the fleet's fixtures already carry `ERROR:a:b` and whole
68/// diagnostic sentences with embedded colons, so `ERROR:x:1:8` could not
69/// be split without guessing. Anchoring at the end and requiring digits
70/// keeps a message that merely CONTAINS an `@` intact.
71///
72/// An error when handed a cell that is not an error expectation at all.
73pub fn error_expect(expected: &str) -> Result<ErrorExpect> {
74 if !is_error_expect(expected) {
75 return Err(Error(format!("not an error expectation: {expected:?}")));
76 }
77
78 let code = if expected == ERROR_PREFIX {
79 ""
80 } else {
81 &expected[ERROR_PREFIX.len() + 1..]
82 };
83
84 let Some((code, row_text, col_text)) = position_suffix(code) else {
85 return Ok(ErrorExpect {
86 code: code.to_string(),
87 row: None,
88 col: None,
89 });
90 };
91
92 // The digits are already constrained; only an absurdly long run can
93 // fail here, and that is a malformed fixture, not a mismatch.
94 let row = row_text.parse::<usize>().map_err(|error| {
95 Error(format!(
96 "invalid row in error expectation {expected:?}: {error}"
97 ))
98 })?;
99 let col = col_text.parse::<usize>().map_err(|error| {
100 Error(format!(
101 "invalid column in error expectation {expected:?}: {error}"
102 ))
103 })?;
104
105 // Positions are 1-based, so zero is not a position. It matters more
106 // than it looks: an error type that leaves row and col at their zero
107 // value when it has no position would MATCH `@0:0`, and the row would
108 // pass while pinning no source location at all, the exact silent gap
109 // this channel exists to close, reintroduced through its own syntax.
110 if row < 1 || col < 1 {
111 return Err(Error(format!(
112 "position in an error expectation is 1-based, so 0 is not a position: {expected:?}"
113 )));
114 }
115
116 Ok(ErrorExpect {
117 code: code.to_string(),
118 row: Some(row),
119 col: Some(col),
120 })
121}
122
123/// Split a trailing `@<digits>:<digits>` off a code. Zero is matched here
124/// and REJECTED by the caller rather than excluded by the pattern, so
125/// `@0:0` fails as a malformed fixture instead of quietly falling through
126/// and being read as part of the code.
127fn position_suffix(code: &str) -> Option<(&str, &str, &str)> {
128 let digits_end = code.len();
129 let col_start = code
130 .rfind(|c: char| !c.is_ascii_digit())
131 .map_or(0, |i| i + 1);
132 if col_start == digits_end || !code[..col_start].ends_with(':') {
133 return None;
134 }
135 let colon = col_start - 1;
136 let row_start = code[..colon]
137 .rfind(|c: char| !c.is_ascii_digit())
138 .map_or(0, |i| i + 1);
139 if row_start == colon || !code[..row_start].ends_with('@') {
140 return None;
141 }
142 let at = row_start - 1;
143 Some((&code[..at], &code[row_start..colon], &code[col_start..]))
144}
145
146/// Parse an expected cell as JSON. An empty cell is [`Value::Undefined`],
147/// the fixture convention for "no value", as in a utility whose result is
148/// nothing at all.
149///
150/// The cell is NOT escape-decoded first: it is JSON, and JSON has its own
151/// escape rules. Decoding it here would turn the two characters `\n`
152/// inside a JSON string into a real newline, which is not valid JSON.
153///
154/// A number too large for an `f64` (`1e400`) reads as an infinity, which
155/// is what the canonical `JSON.parse` answers, so a row that loads in
156/// TypeScript loads here too.
157pub fn parse_expect(expected: &str) -> Result<Value> {
158 if expected.is_empty() {
159 return Ok(Value::Undefined);
160 }
161 Value::parse_json(expected)
162 .map_err(|reason| Error(format!("invalid expected JSON: {expected:?}: {reason}")))
163}
164
165/// The position of the first UNPAIRED `\uXXXX` surrogate escape in an
166/// expected cell, counted in CODE POINTS, or `None`.
167///
168/// Code points because this number crosses the runtimes. The natural
169/// index is a UTF-16 offset in TypeScript, a byte offset in Go and here,
170/// and those disagree the moment anything non-ASCII precedes the escape:
171/// for `"é\ud800"` they are 2 and 3. A helper whose whole purpose is to
172/// keep the ports saying the same thing cannot report a number that
173/// depends on which port asked.
174///
175/// Why this is not a curiosity: `JSON.parse` preserves a lone surrogate
176/// (a JavaScript string is UTF-16 and may hold one) while Go's
177/// `encoding/json` and this crate's reader replace it with U+FFFD (a
178/// UTF-8 string cannot). A SHARED expected cell holding one asks the
179/// runtimes different questions and reports agreement either way, so the
180/// runner refuses it. A per-runtime register column is a different
181/// matter: there each runtime reads its own cell.
182///
183/// Only the ESCAPE form is detected, because it is the only one that can
184/// occur: a fixture file is UTF-8, and a lone surrogate has no UTF-8
185/// encoding.
186pub fn lone_surrogate_at(cell: &str) -> Option<usize> {
187 let bytes = cell.as_bytes();
188 let hex4 = |at: usize| -> Option<u32> {
189 let text = bytes.get(at..at + 4)?;
190 let text = std::str::from_utf8(text).ok()?;
191 if !text.chars().all(|c| c.is_ascii_hexdigit()) {
192 return None;
193 }
194 u32::from_str_radix(text, 16).ok()
195 };
196 let code_points_before = |at: usize| cell[..at].chars().count();
197
198 let mut i = 0;
199 while i < bytes.len() {
200 if bytes[i] != b'\\' {
201 i += 1;
202 continue;
203 }
204
205 // A run of backslashes escapes itself in pairs; only an ODD run
206 // leaves a live escape, whose introducer is the byte after the
207 // whole run. `\\ud800` is a literal backslash then `ud800`.
208 let mut j = i;
209 while j < bytes.len() && bytes[j] == b'\\' {
210 j += 1;
211 }
212 if (j - i) % 2 == 0 {
213 i = j;
214 continue;
215 }
216
217 let start = j - 1;
218 if j >= bytes.len() || bytes[j] != b'u' {
219 i = j + 1;
220 continue;
221 }
222
223 let Some(unit) = hex4(j + 1) else {
224 i = j + 1;
225 continue;
226 };
227
228 if (0xD800..=0xDBFF).contains(&unit) {
229 // A high surrogate is fine if a low follows IMMEDIATELY.
230 let k = j + 5;
231 if bytes.get(k) == Some(&b'\\') && bytes.get(k + 1) == Some(&b'u') {
232 if let Some(low) = hex4(k + 2) {
233 if (0xDC00..=0xDFFF).contains(&low) {
234 i = k + 6;
235 continue;
236 }
237 }
238 }
239 return Some(code_points_before(start));
240 }
241 if (0xDC00..=0xDFFF).contains(&unit) {
242 // A paired low was consumed above, so reaching one here means
243 // it has no high before it. The prefix always ends on a
244 // backslash, so counting over it never splits a character.
245 return Some(code_points_before(start));
246 }
247
248 i = j + 5;
249 }
250
251 None
252}
253
254/// The message the runner uses when a shared cell holds an unpaired
255/// surrogate escape. Exported so every runtime says the same thing, and
256/// so a caller building its own runner can reuse it.
257pub fn lone_surrogate_message(cell: &str, at: usize) -> String {
258 format!(
259 "expected cell holds an unpaired surrogate escape at code point {at}: {cell:?}\n \
260 A shared expected column CANNOT express this: JSON.parse preserves a lone surrogate\n \
261 (a JavaScript string is UTF-16) and Go's encoding/json replaces it with U+FFFD\n \
262 (a Go string is UTF-8). The two runtimes would be asked different questions and both\n \
263 would pass. This is a recorded, permanent divergence - see DIVERGENCE.md.\n \
264 Put the case in a per-runtime register column, where each decoding is written out,\n \
265 or in each port's own suite with opposite assertions. A surrogate PAIR is fine here."
266 )
267}
268
269/// Compare a parse result against an expected value with JSON semantics:
270/// structural, key-order independent, `NaN` equal to itself, and `-0`
271/// NOT equal to `0`. Those last two are the two halves of ADR-15, and
272/// they go opposite ways on purpose. See [`Value`]'s equality.
273pub fn equal_value(got: &Value, expected: &Value) -> bool {
274 got == expected
275}
276
277/// [`equal_value`] with a normalize hook, applied to every node on both
278/// sides, outermost first. This is where a runtime-specific container,
279/// an insertion-ordered map or a reference wrapper unwrapped into a
280/// plain value, is folded into the plain value the fixture's JSON
281/// describes.
282pub fn equal_value_with(got: &Value, expected: &Value, normalize: &dyn Fn(Value) -> Value) -> bool {
283 let got = normalize(got.clone());
284 let expected = normalize(expected.clone());
285 match (&got, &expected) {
286 (Value::Array(a), Value::Array(b)) => {
287 a.len() == b.len()
288 && a.iter()
289 .zip(b)
290 .all(|(x, y)| equal_value_with(x, y, normalize))
291 }
292 (Value::Object(a), Value::Object(b)) => {
293 a.len() == b.len()
294 && a.iter().all(|(key, value)| {
295 b.iter()
296 .find(|(other_key, _)| other_key == key)
297 .is_some_and(|(_, other)| equal_value_with(value, other, normalize))
298 })
299 }
300 _ => got == expected,
301 }
302}
303
304/// Render a value for a failure message: JSON where possible, so the text
305/// lines up with how the fixture wrote it, with `-0` spelt `-0` and the
306/// values JSON cannot spell written as JavaScript names them.
307pub fn format_value(value: &Value) -> String {
308 value.to_string()
309}