tabnas_support/spec.rs
1// Copyright (c) 2026 tabnas, MIT License
2
3// The TSV spec-fixture loader.
4//
5// Every tabnas package keeps its cross-runtime conformance fixtures in
6// `test/spec/*.tsv` at the repo root, above every runtime, so `ts/`,
7// `go/` and `rs/` run the same files. Before this package each repo
8// carried its own loader, and they had quietly drifted: one decoded `\t`
9// and another did not, one skipped `#` comment lines and another crashed
10// on them, one decoded escapes in every column and another only in the
11// first. A row that means two different things in two runtimes cannot pin
12// agreement on anything else, so there is one loader now, and this file
13// mirrors `ts/src/spec.ts` and `go/spec.go`.
14//
15// The rules, in full:
16//
17// - Line 1 is a header naming the columns. Names are how a row is read by
18// `row.named("input")` rather than by position.
19// - A blank line is skipped.
20// - A line that starts with `#` and holds no tab is a comment and is
21// skipped. A `#`-leading line WITH a tab is data, so a fixture whose
22// input is a C preprocessor directive still works.
23// - Columns are returned RAW. Escape decoding is per-column and explicit
24// (`row.unesc(i)`), because the `expected` column is normally JSON,
25// which carries its own escapes and must not be decoded twice.
26// - Line numbers are the physical 1-based line in the file, so a failure
27// message points an editor at the offending row.
28
29use std::fs;
30use std::path::{Path, PathBuf};
31use std::sync::Arc;
32
33use crate::escape::unescape;
34use crate::{Error, Result};
35
36/// How to interpret a fixture file. The defaults are the tabnas
37/// convention; override them only for a fixture that genuinely differs.
38#[derive(Debug, Clone, PartialEq, Eq)]
39pub struct SpecOptions {
40 /// First line names the columns. Default true.
41 pub header: bool,
42 /// Skip `#`-leading lines that hold no tab. Default true.
43 pub comment: bool,
44 /// Reject a data row with fewer columns. Default 1.
45 pub min_cols: usize,
46}
47
48impl Default for SpecOptions {
49 fn default() -> Self {
50 SpecOptions {
51 header: true,
52 comment: true,
53 min_cols: 1,
54 }
55 }
56}
57
58/// A column selector: a position, or a header name.
59#[derive(Debug, Clone, PartialEq, Eq)]
60pub enum Column {
61 Position(usize),
62 Name(String),
63}
64
65impl From<usize> for Column {
66 fn from(position: usize) -> Self {
67 Column::Position(position)
68 }
69}
70
71impl From<&str> for Column {
72 fn from(name: &str) -> Self {
73 Column::Name(name.to_string())
74 }
75}
76
77impl From<String> for Column {
78 fn from(name: String) -> Self {
79 Column::Name(name)
80 }
81}
82
83/// One data row of a fixture file.
84#[derive(Debug, Clone)]
85pub struct Row {
86 /// Base name of the file this row came from (`happy.tsv`).
87 pub file: String,
88 /// Physical 1-based line number within that file.
89 pub line: usize,
90 /// 0-based position among the file's DATA rows (header and skipped
91 /// lines do not advance it).
92 pub index: usize,
93 /// The row's columns, exactly as they appear in the file.
94 pub cols: Vec<String>,
95 /// The file's header names, shared with every row of the file.
96 pub header: Arc<Vec<String>>,
97}
98
99impl Row {
100 /// Raw column by position. Out of range is `""`: a fixture with a
101 /// trailing optional column should not need a length check at every
102 /// use.
103 pub fn col(&self, i: usize) -> &str {
104 self.cols.get(i).map(String::as_str).unwrap_or("")
105 }
106
107 /// Escape-decoded column by position. This is what a parser input
108 /// column goes through.
109 pub fn unesc(&self, i: usize) -> String {
110 unescape(self.col(i))
111 }
112
113 /// Position of a header name, or `None` when the file has no such
114 /// column.
115 pub fn index_of(&self, name: &str) -> Option<usize> {
116 self.header.iter().position(|column| column == name)
117 }
118
119 /// Raw column by header name; `""` when there is no such column.
120 pub fn named(&self, name: &str) -> &str {
121 self.index_of(name).map_or("", |i| self.col(i))
122 }
123
124 /// Escape-decoded column by header name.
125 pub fn unesc_named(&self, name: &str) -> String {
126 unescape(self.named(name))
127 }
128
129 /// Resolve a column selector to a position. An unknown name is a
130 /// defect in the caller, not a missing value, so it is an error rather
131 /// than a silent read of an absent column.
132 pub fn resolve(&self, selector: &Column) -> Result<usize> {
133 match selector {
134 Column::Position(i) => Ok(*i),
135 Column::Name(name) => self.index_of(name).ok_or_else(|| {
136 Error(format!(
137 "{}: no column named '{}' (header: {})",
138 self.file,
139 name,
140 self.header.join(", ")
141 ))
142 }),
143 }
144 }
145
146 /// `<file>:<line>`, the prefix every failure message should carry.
147 pub fn location(&self) -> String {
148 format!("{}:{}", self.file, self.line)
149 }
150}
151
152/// A loaded fixture file.
153#[derive(Debug, Clone)]
154pub struct SpecFile {
155 /// Base name (`happy.tsv`).
156 pub file: String,
157 /// Path it was read from (empty when parsed from text).
158 pub path: PathBuf,
159 /// Column names, empty when `header` is off.
160 pub header: Arc<Vec<String>>,
161 /// Data rows, in file order.
162 pub rows: Vec<Row>,
163}
164
165/// Parse fixture text that is already in memory. [`load_spec`] is this
166/// plus a file read; tests of the loader itself use this form.
167pub fn parse_spec(file: &str, text: &str, options: &SpecOptions) -> Result<SpecFile> {
168 // A BOM ahead of the header would become part of the first column
169 // name, and the lookup by that name would then fail in a way nothing
170 // about the fixture explains.
171 let text = text.strip_prefix('\u{FEFF}').unwrap_or(text);
172
173 let name = base_name(file);
174 let mut header: Arc<Vec<String>> = Arc::new(Vec::new());
175 let mut rows = Vec::new();
176
177 for (i, raw) in text.split('\n').enumerate() {
178 // Drop the CR of a CRLF line, so a CRLF fixture feeds every
179 // runtime the same bytes.
180 let line = raw.strip_suffix('\r').unwrap_or(raw);
181 let line_no = i + 1;
182
183 if options.header && i == 0 {
184 header = Arc::new(line.split('\t').map(str::to_string).collect());
185 continue;
186 }
187
188 if line.is_empty() {
189 continue;
190 }
191
192 // A comment needs no tab; a data row always has at least one, so
193 // a `#`-leading source stays usable as input.
194 if options.comment && line.starts_with('#') && !line.contains('\t') {
195 continue;
196 }
197
198 let cols: Vec<String> = line.split('\t').map(str::to_string).collect();
199 if cols.len() < options.min_cols {
200 return Err(Error(format!(
201 "{name}:{line_no}: expected at least {} tab-separated column(s), found {}",
202 options.min_cols,
203 cols.len()
204 )));
205 }
206
207 rows.push(Row {
208 file: name.clone(),
209 line: line_no,
210 index: rows.len(),
211 cols,
212 header: Arc::clone(&header),
213 });
214 }
215
216 Ok(SpecFile {
217 file: name,
218 path: PathBuf::new(),
219 header,
220 rows,
221 })
222}
223
224/// Load one fixture file by path.
225pub fn load_spec(path: impl AsRef<Path>, options: &SpecOptions) -> Result<SpecFile> {
226 let path = path.as_ref();
227 let text = fs::read_to_string(path)
228 .map_err(|error| Error(format!("spec file not found: {}: {error}", path.display())))?;
229 let mut spec = parse_spec(&path.to_string_lossy(), &text, options)?;
230 spec.path = path.to_path_buf();
231 Ok(spec)
232}
233
234/// Load every `*.tsv` in a directory, sorted by name so every runtime and
235/// every run visits them in the same order. Discovery by listing is
236/// deliberate: adding a fixture then runs it without editing a runner.
237pub fn load_spec_dir(dir: impl AsRef<Path>, options: &SpecOptions) -> Result<Vec<SpecFile>> {
238 let dir = dir.as_ref();
239 if !dir.is_dir() {
240 return Err(Error(format!(
241 "spec directory not found: {}",
242 dir.display()
243 )));
244 }
245
246 let entries = fs::read_dir(dir).map_err(|error| {
247 Error(format!(
248 "spec directory not found: {}: {error}",
249 dir.display()
250 ))
251 })?;
252
253 let mut names = Vec::new();
254 for entry in entries {
255 let entry = entry.map_err(|error| Error(format!("{}: {error}", dir.display())))?;
256 let name = entry.file_name().to_string_lossy().into_owned();
257 if !name.ends_with(".tsv") {
258 continue;
259 }
260 // Files only, judged by what the name RESOLVES to: a DIRECTORY
261 // named `foo.tsv` would otherwise be handed to the reader and
262 // abort the run, and a symlinked fixture must be loaded rather
263 // than dropped, since a row that runs in one runtime and not
264 // another is the exact failure this crate exists to prevent. A
265 // dangling link names a fixture that is not there, and skipping
266 // it silently is the same silent pass this loader refuses
267 // everywhere else, so it is an error.
268 let metadata = fs::metadata(dir.join(&name)).map_err(|error| {
269 Error(format!(
270 "spec fixture cannot be read: {}: {error}",
271 dir.join(&name).display()
272 ))
273 })?;
274 if metadata.is_file() {
275 names.push(name);
276 }
277 }
278 names.sort();
279
280 // A directory with no fixtures in it is the silent-pass failure mode
281 // one level up: every runner over it reports green having run nothing.
282 if names.is_empty() {
283 return Err(Error(format!(
284 "no .tsv fixtures in spec directory: {}",
285 dir.display()
286 )));
287 }
288
289 names
290 .iter()
291 .map(|name| load_spec(dir.join(name), options))
292 .collect()
293}
294
295/// Walk up from `from` (the working directory when `None`) looking for a
296/// `test/spec` directory, and return it.
297///
298/// This replaces the `../../test/spec` hop every suite would otherwise
299/// hard-code, which has to be recounted whenever a test moves a
300/// directory. A crate's suite passes `Some(env!("CARGO_MANIFEST_DIR"))`.
301pub fn find_spec_dir(from: Option<&Path>) -> Result<PathBuf> {
302 let start = match from {
303 Some(path) => path.to_path_buf(),
304 None => std::env::current_dir()
305 .map_err(|error| Error(format!("cannot read the working directory: {error}")))?,
306 };
307 let start = start.canonicalize().unwrap_or(start);
308
309 let mut dir = start.clone();
310 loop {
311 let candidate = dir.join("test").join("spec");
312 if candidate.is_dir() {
313 return Ok(candidate);
314 }
315 match dir.parent() {
316 Some(parent) => dir = parent.to_path_buf(),
317 None => break, // Filesystem root: there is nowhere left to look.
318 }
319 }
320
321 Err(Error(format!(
322 "no test/spec directory found at or above: {}",
323 start.display()
324 )))
325}
326
327fn base_name(file: &str) -> String {
328 Path::new(file)
329 .file_name()
330 .map(|name| name.to_string_lossy().into_owned())
331 .unwrap_or_else(|| file.to_string())
332}