use std::collections::{BTreeMap, BTreeSet};
use std::fs;
use std::path::{Path, PathBuf};
fn repo_root() -> PathBuf {
Path::new(env!("CARGO_MANIFEST_DIR"))
.parent()
.expect("rs/ has a parent")
.to_path_buf()
}
fn descriptor_codes() -> Vec<String> {
let text = fs::read_to_string(repo_root().join("tabnas.plugin.json"))
.expect("tabnas.plugin.json is readable");
let descriptor: serde_json::Value =
serde_json::from_str(&text).expect("tabnas.plugin.json is JSON");
descriptor["errorCodes"]
.as_array()
.expect("the descriptor declares errorCodes")
.iter()
.map(|code| {
code.as_str()
.expect("every errorCodes entry is a string")
.to_string()
})
.collect()
}
fn canonical_table_keys(opener: &str) -> Vec<String> {
let source = fs::read_to_string(repo_root().join("ts").join("src").join("xml.ts"))
.expect("ts/src/xml.ts is readable");
let mut lines = source.lines();
let open = lines
.find(|line| line.trim() == opener)
.unwrap_or_else(|| panic!("ts/src/xml.ts opens a `{opener}` block"));
let indent = open.len() - open.trim_start().len();
let mut keys = Vec::new();
for line in lines {
let body = line.trim_start();
let depth = line.len() - body.len();
if depth <= indent && (body.starts_with('}') || body.starts_with("},")) {
return keys;
}
if let Some(name) = body.split(':').next() {
let identifier = !name.is_empty()
&& name
.chars()
.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_');
if identifier && body.len() > name.len() && body.as_bytes()[name.len()] == b':' {
keys.push(name.to_string());
}
}
}
panic!("the `{opener}` block in ts/src/xml.ts is not closed");
}
fn canonical_error_table() -> BTreeMap<String, String> {
let source = fs::read_to_string(repo_root().join("ts").join("src").join("xml.ts"))
.expect("ts/src/xml.ts is readable");
let mut lines = source.lines();
let open = lines
.find(|line| line.trim() == "error: {")
.expect("ts/src/xml.ts opens an `error` block");
let indent = open.len() - open.trim_start().len();
let mut table = BTreeMap::new();
let mut entry: Option<(String, String)> = None;
let flush = |entry: Option<(String, String)>, table: &mut BTreeMap<String, String>| {
if let Some((code, raw)) = entry {
let value = raw.trim().strip_suffix(',').unwrap_or(raw.trim()).trim();
let text = value
.strip_prefix('\'')
.and_then(|rest| rest.strip_suffix('\''))
.unwrap_or_else(|| {
panic!(
"the {code} entry in ts/src/xml.ts is not a single-quoted string: {value}"
)
});
table.insert(code, text.to_string());
}
};
for line in lines {
let body = line.trim_start();
let depth = line.len() - body.len();
if depth <= indent && body.starts_with('}') {
flush(entry, &mut table);
return table;
}
match body.split_once(':') {
Some((name, rest))
if !name.is_empty()
&& name
.chars()
.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_') =>
{
flush(entry.take(), &mut table);
entry = Some((name.to_string(), rest.trim().to_string()));
}
_ => {
if let Some((_, value)) = entry.as_mut() {
if !value.is_empty() {
value.push(' ');
}
value.push_str(body);
}
}
}
}
panic!("the `error` block in ts/src/xml.ts is not closed");
}
fn canonical_hint_table() -> BTreeMap<String, String> {
let source = fs::read_to_string(repo_root().join("ts").join("src").join("xml.ts"))
.expect("ts/src/xml.ts is readable");
let mut lines = source.lines();
let open = lines
.find(|line| line.trim() == "hint: {")
.expect("ts/src/xml.ts opens a `hint` block");
let indent = open.len() - open.trim_start().len();
let mut table = BTreeMap::new();
let mut open_entry: Option<(String, Vec<String>)> = None;
for line in lines {
let body = line.trim_start();
let depth = line.len() - body.len();
if open_entry.is_none() && depth <= indent && body.starts_with('}') {
return table;
}
if let Some((code, parts)) = open_entry.as_mut() {
match line.split_once('`') {
Some((before, _)) => {
parts.push(before.to_string());
table.insert(code.clone(), parts.join("\n"));
open_entry = None;
}
None => parts.push(line.to_string()),
}
continue;
}
let Some((name, rest)) = body.split_once(':') else {
continue;
};
let is_code = !name.is_empty()
&& name
.chars()
.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_');
if !is_code {
continue;
}
let Some(after) = rest.trim_start().strip_prefix('`') else {
panic!("the {name} hint in ts/src/xml.ts is not a template literal: {rest}");
};
match after.split_once('`') {
Some((text, _)) => {
table.insert(name.to_string(), text.to_string());
}
None => open_entry = Some((name.to_string(), vec![after.to_string()])),
}
}
panic!("the `hint` block in ts/src/xml.ts is not closed");
}
fn resolve_substitutions(table: BTreeMap<String, String>) -> BTreeMap<String, String> {
let source = fs::read_to_string(repo_root().join("ts").join("src").join("xml.ts"))
.expect("ts/src/xml.ts is readable");
let constant = |name: &str| -> Option<String> {
let needle = format!("const {name} = '");
let at = source.find(&needle)? + needle.len();
let end = source[at..].find('\'')?;
Some(source[at..at + end].to_string())
};
table
.into_iter()
.map(|(code, mut hint)| {
while let Some(at) = hint.find("${") {
let end = at + hint[at..]
.find('}')
.unwrap_or_else(|| panic!("the {code} hint has an unclosed substitution"));
let name = &hint[at + 2..end];
let value = constant(name).unwrap_or_else(|| {
panic!("the {code} hint names ${{{name}}}, and ts/src/xml.ts declares no such const")
});
hint.replace_range(at..=end, &value);
}
(code, hint)
})
.collect()
}
struct Catalogues {
error: std::collections::HashMap<String, String>,
hint: std::collections::HashMap<String, String>,
base_error: std::collections::HashMap<String, String>,
base_hint: std::collections::HashMap<String, String>,
}
fn installed_catalogue() -> Catalogues {
let base = tabnas_jsonic::make().config();
let installed = tabnas_xml::make().config();
Catalogues {
error: installed.error,
hint: installed.hint,
base_error: base.error,
base_hint: base.hint,
}
}
#[test]
fn the_descriptor_lists_the_canonical_codes() {
let descriptor: BTreeSet<String> = descriptor_codes().into_iter().collect();
let canonical: BTreeSet<String> = canonical_table_keys("error: {").into_iter().collect();
assert_eq!(
canonical, descriptor,
"tabnas.plugin.json and the `error` table in ts/src/xml.ts declare different codes"
);
}
#[test]
fn the_guide_states_the_catalogue_it_documents() {
let guide = fs::read_to_string(repo_root().join("AGENTS.md")).expect("AGENTS.md is readable");
let canonical = canonical_error_table();
let at = guide
.find("Every one of the ")
.expect("AGENTS.md states how many codes are declared");
let stated: usize = guide[at + "Every one of the ".len()..]
.split_whitespace()
.next()
.expect("a number follows")
.parse()
.expect("the stated count is a number");
assert_eq!(
stated,
canonical.len(),
"AGENTS.md says {stated} declared codes; ts/src/xml.ts declares {}",
canonical.len()
);
let rows = guide_error_rows(&guide);
assert_eq!(
rows.len(),
stated,
"AGENTS.md says {stated} declared codes and its own table carries {} rows",
rows.len()
);
let mut seen = BTreeSet::new();
for (code, _, _) in &rows {
assert!(
seen.insert(code.clone()),
"the error-code table in AGENTS.md lists `{code}` more than once"
);
}
let pinned = codes_pinned_by_fixtures();
for (code, _, fixture) in &rows {
let want = if pinned.contains(code) { "yes" } else { "no" };
assert_eq!(
fixture,
want,
"AGENTS.md says the Fixture column for `{code}` is {fixture:?}; \
test/spec pins it {}",
if "yes" == want {
"as claimed"
} else {
"nowhere"
}
);
}
let documented: BTreeMap<String, String> = rows
.into_iter()
.map(|(code, message, _)| (code, message))
.collect();
assert_eq!(
documented.keys().collect::<Vec<_>>(),
canonical.keys().collect::<Vec<_>>(),
"the error-code table in AGENTS.md and the `error` table in ts/src/xml.ts list different codes"
);
for (code, message) in &canonical {
assert_eq!(
documented.get(code).map(String::as_str),
Some(message.as_str()),
"AGENTS.md documents a different message for `{code}` than ts/src/xml.ts raises"
);
}
}
fn guide_error_rows(guide: &str) -> Vec<(String, String, String)> {
const HEADER: &str = "| Code | Message | Fixture |";
let mut lines = guide.lines();
lines
.find(|line| line.trim() == HEADER)
.unwrap_or_else(|| panic!("AGENTS.md carries the error-code table under `{HEADER}`"));
let separator = lines
.next()
.expect("a separator row follows the error-code table's header");
assert!(
separator.starts_with("|---"),
"the error-code table's header is not followed by a separator row: {separator}"
);
let mut rows = Vec::new();
for line in lines {
if !line.starts_with('|') {
return rows;
}
let cells: Vec<&str> = line.split('|').map(str::trim).collect();
assert_eq!(
cells.len(),
5,
"the error-code table in AGENTS.md carries a row that is not three cells: {line}"
);
rows.push((
code_span(cells[1], line),
code_span(cells[2], line),
cells[3].to_string(),
));
}
panic!("the error-code table in AGENTS.md runs to the end of the page");
}
fn code_span(cell: &str, line: &str) -> String {
cell.strip_prefix('`')
.and_then(|rest| rest.strip_suffix('`'))
.unwrap_or_else(|| panic!("a cell of the error-code table is not a code span: {line}"))
.to_string()
}
#[test]
fn the_canonical_tables_are_paired() {
let errors: BTreeSet<String> = canonical_table_keys("error: {").into_iter().collect();
let hints: BTreeSet<String> = canonical_table_keys("hint: {").into_iter().collect();
assert_eq!(
errors, hints,
"the `error` and `hint` tables in ts/src/xml.ts do not cover the same codes"
);
}
#[test]
fn the_port_installs_exactly_the_canonical_codes() {
let catalogues = installed_catalogue();
let canonical: BTreeSet<String> = canonical_table_keys("error: {").into_iter().collect();
let missing: BTreeSet<&String> = canonical
.iter()
.filter(|code| !catalogues.error.contains_key(*code))
.collect();
assert!(
missing.is_empty(),
"the port does not install these canonical codes: {missing:?}"
);
let noncanonical = |map: &std::collections::HashMap<String, String>| -> BTreeSet<String> {
map.keys()
.filter(|code| !canonical.contains(*code))
.cloned()
.collect()
};
let extra: BTreeSet<String> = noncanonical(&catalogues.error)
.union(&noncanonical(&catalogues.base_error))
.filter(|code| catalogues.base_error.get(*code) != catalogues.error.get(*code))
.cloned()
.collect();
assert!(
extra.is_empty(),
"outside the canonical table, the installed `error` catalogue differs from the \
inherited one (added, overridden or REMOVED): {extra:?}"
);
let unhinted: BTreeSet<&String> = canonical
.iter()
.filter(|code| !catalogues.hint.contains_key(*code))
.collect();
assert!(
unhinted.is_empty(),
"these canonical codes are installed with no hint: {unhinted:?}"
);
let extra_hints: BTreeSet<String> = noncanonical(&catalogues.hint)
.union(&noncanonical(&catalogues.base_hint))
.filter(|code| catalogues.base_hint.get(*code) != catalogues.hint.get(*code))
.cloned()
.collect();
assert!(
extra_hints.is_empty(),
"outside the canonical table, the installed `hint` catalogue differs from the \
inherited one (added, overridden or REMOVED): {extra_hints:?}"
);
}
#[test]
fn the_port_installs_the_canonical_message_templates() {
let catalogues = installed_catalogue();
let canonical = canonical_error_table();
assert_eq!(
canonical.len(),
descriptor_codes().len(),
"the messages read out of ts/src/xml.ts do not cover every declared code"
);
for (code, message) in canonical {
assert_eq!(
catalogues.error.get(&code),
Some(&message),
"the {code} message differs from the canonical one in ts/src/xml.ts"
);
}
}
#[test]
fn the_port_installs_the_canonical_hint_templates() {
let catalogues = installed_catalogue();
let canonical = resolve_substitutions(canonical_hint_table());
assert_eq!(
canonical.len(),
descriptor_codes().len(),
"the hints read out of ts/src/xml.ts do not cover every declared code"
);
assert!(
canonical
.get("xml_mismatched_tag")
.is_some_and(|hint| hint.contains('\n')),
"the multi-line hint came back as one line; the extraction is wrong"
);
assert!(
canonical
.get("reserved_namespace")
.is_some_and(|hint| hint.contains("http://www.w3.org/XML/1998/namespace")
&& !hint.contains("${")),
"the ${{XML_NS_URI}} substitution was not resolved"
);
for (code, hint) in canonical {
assert_eq!(
catalogues.hint.get(&code),
Some(&hint),
"the {code} hint differs from the canonical one in ts/src/xml.ts"
);
}
}
#[test]
fn every_declared_code_is_pinned_by_a_fixture() {
let expected = codes_pinned_by_fixtures();
let unpinned: Vec<String> = descriptor_codes()
.into_iter()
.filter(|code| !expected.contains(code))
.collect();
assert!(
unpinned.is_empty(),
"these declared codes are pinned by no fixture row: {unpinned:?}. \
Add a row to test/spec, which every runtime discovers, rather than \
recording the gap in prose"
);
}
fn codes_pinned_by_fixtures() -> BTreeSet<String> {
let spec = repo_root().join("test").join("spec");
let mut expected: BTreeSet<String> = BTreeSet::new();
for entry in fs::read_dir(&spec).expect("the spec directory lists") {
let path = entry.expect("a directory entry").path();
if path.extension().is_none_or(|ext| ext != "tsv") {
continue;
}
let text = fs::read_to_string(&path).expect("a fixture is readable");
let at = expected_column(&text)
.unwrap_or_else(|| panic!("{path:?} has no `expected` column in its header"));
for line in text
.lines()
.filter(|line| !line.starts_with('#') && !line.trim().is_empty())
{
let fields: Vec<&str> = line.split('\t').collect();
let Some(cell) = fields.get(at) else { continue };
if let Some(code) = cell.trim().strip_prefix("ERROR:") {
expected.insert(code.to_string());
}
}
}
assert!(
!expected.is_empty(),
"no ERROR: expectations were read from {spec:?}"
);
expected
}
fn expected_column(text: &str) -> Option<usize> {
let header = text.lines().find(|line| line.starts_with('#'))?;
header
.trim_start_matches('#')
.split('\t')
.position(|name| "expected" == name.trim())
}
#[test]
fn the_expected_column_is_found_by_name() {
assert_eq!(
expected_column("# name\tinput\texpected\topts\nrow\tsrc\tERROR:x\t\n"),
Some(2)
);
assert_eq!(expected_column("# name\texpected\tinput\topts\n"), Some(1));
assert_eq!(expected_column("row\tsrc\tERROR:x\n"), None);
assert_eq!(expected_column("# name\tinput\topts\n"), None);
}