Skip to main content

tabnas_support/
census.rs

1// Copyright (c) 2026 tabnas, MIT License
2
3// Coverage and parity tripwires over error codes.
4//
5// Every tabnas package declares a set of error codes, renders each through
6// a `{code: template}` message catalogue, and pins its rejections in
7// fixtures as `ERROR:<code>` rows. Three lists, three ways to drift: a
8// declared code no fixture ever exercises, two catalogues whose keys or
9// templates have come apart, a fixture pinning a code nobody declares.
10// These helpers compute those gaps from real loaded data.
11//
12// Every input arrives as an argument. Nothing here fetches a catalogue or
13// imports the engine, which is exactly why these tripwires can live in the
14// one crate every repo already shares.
15//
16// `ts/src/census.ts` and `go/census.go` mirror all of this.
17
18use std::collections::{BTreeSet, HashMap};
19use std::path::Path;
20
21use crate::expect::{error_code, is_error_expect};
22use crate::spec::{load_spec_dir, Row, SpecFile, SpecOptions};
23use crate::{Error, Result};
24
25/// Which column holds the expectation. The default is each row's last
26/// column (the ordinary two-column `input`/`expected` fixture needs no
27/// selection at all), but a wider fixture can keep the expectation
28/// anywhere, which is why the selection exists.
29#[derive(Debug, Clone, Default, PartialEq, Eq)]
30pub struct CensusOptions {
31    /// Expectation column by position.
32    pub col: Option<usize>,
33    /// Expectation column by header name; wins when set.
34    pub name: Option<String>,
35}
36
37/// What a code-style expectation names: a bare lowercase token, which is
38/// how every tabnas error code is spelt. `ERROR:bad token` and
39/// `ERROR:1:8` are message- and position-style expectations, real
40/// rejections but not codes, and a census that returned them would count
41/// coverage that is not there.
42fn is_code_token(code: &str) -> bool {
43    let mut chars = code.chars();
44    matches!(chars.next(), Some('a'..='z'))
45        && chars.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_')
46}
47
48/// Collect every code named by a code-style expectation cell under a
49/// fixture directory: sorted, unique. Message-style expectations and bare
50/// `ERROR` cells assert a rejection without naming a code, so they are
51/// not collected; a value row is not an expectation at all.
52///
53/// The directory is read with the shared loader, so an empty directory
54/// fails here the way it fails everywhere else: a census over nothing
55/// must not report "no codes" as if it had looked.
56pub fn codes_in_spec_dir(dir: impl AsRef<Path>, options: &CensusOptions) -> Result<Vec<String>> {
57    let mut codes = BTreeSet::new();
58
59    for spec in load_spec_dir(dir, &SpecOptions::default())? {
60        for row in &spec.rows {
61            let cell = row.col(expectation_col(&spec, row, options)?);
62            if !is_error_expect(cell) {
63                continue;
64            }
65            let code = error_code(cell)?;
66            if is_code_token(&code) {
67                codes.insert(code);
68            }
69        }
70    }
71
72    // A `BTreeSet<String>` orders by bytes, which for valid UTF-8 is code
73    // point order: the same order Go's sort.Strings and the TypeScript
74    // half's code-point comparison produce.
75    Ok(codes.into_iter().collect())
76}
77
78/// The expectation column for one row: the named column when `name` is
79/// set, else the given position, else the row's own last column. An
80/// unknown name is an error: that is a defect in the caller, and a census
81/// silently reading the wrong column would report coverage nobody has.
82fn expectation_col(spec: &SpecFile, row: &Row, options: &CensusOptions) -> Result<usize> {
83    if let Some(name) = &options.name {
84        return row.index_of(name).ok_or_else(|| {
85            Error(format!(
86                "{}: no column named {name:?} (header: {:?})",
87                spec.file, spec.header
88            ))
89        });
90    }
91    if let Some(col) = options.col {
92        return Ok(col);
93    }
94    Ok(row.cols.len().saturating_sub(1))
95}
96
97/// What [`compare_catalogues`] found. All three lists are sorted.
98#[derive(Debug, Clone, Default, PartialEq, Eq)]
99pub struct CatalogueDiff {
100    /// Keys of `a` absent in `b`.
101    pub missing: Vec<String>,
102    /// Keys of `b` absent in `a`.
103    pub extra: Vec<String>,
104    /// Shared keys whose templates differ.
105    pub template_mismatch: Vec<String>,
106}
107
108/// Diff two `{code: template}` catalogues: message catalogues, hint
109/// catalogues, or one runtime's against the other's. Templates compare
110/// byte for byte: two templates that merely "mean the same" have still
111/// drifted, and the byte diff is what a maintainer has to reconcile.
112pub fn compare_catalogues(
113    a: &HashMap<String, String>,
114    b: &HashMap<String, String>,
115) -> CatalogueDiff {
116    let mut diff = CatalogueDiff::default();
117
118    for (code, template) in a {
119        match b.get(code) {
120            None => diff.missing.push(code.clone()),
121            Some(other) if other != template => diff.template_mismatch.push(code.clone()),
122            Some(_) => {}
123        }
124    }
125    for code in b.keys() {
126        if !a.contains_key(code) {
127            diff.extra.push(code.clone());
128        }
129    }
130
131    diff.missing.sort();
132    diff.extra.sort();
133    diff.template_mismatch.sort();
134    diff
135}
136
137/// What [`coverage`] found. Both lists are sorted.
138#[derive(Debug, Clone, Default, PartialEq, Eq)]
139pub struct CoverageReport {
140    /// Declared, but exercised by no fixture.
141    pub uncovered: Vec<String>,
142    /// Exercised, but declared by nobody.
143    pub orphan: Vec<String>,
144}
145
146/// Compare the codes a package declares against the codes its fixtures
147/// exercise (typically [`codes_in_spec_dir`]'s answer). Whether inherited
148/// base codes count as declared is the caller's choice: pass them in or
149/// leave them out.
150///
151/// An uncovered code is a rejection nobody has pinned; an orphan is a
152/// fixture pinning a code the package does not declare, a misspelt code
153/// or one that has since been removed. Both lists empty is what "the
154/// fixtures and the declarations agree" means.
155pub fn coverage(declared: &[String], exercised: &[String]) -> CoverageReport {
156    let declared_set: BTreeSet<&String> = declared.iter().collect();
157    let exercised_set: BTreeSet<&String> = exercised.iter().collect();
158
159    CoverageReport {
160        uncovered: declared_set
161            .difference(&exercised_set)
162            .map(|code| (*code).clone())
163            .collect(),
164        orphan: exercised_set
165            .difference(&declared_set)
166            .map(|code| (*code).clone())
167            .collect(),
168    }
169}