Cotton code
153 lines · 6.1 KB · RustRaw
//! The retired vocabulary, emitted as JSON for the readers that are not Rust//! (step 5, R18).//!//! # Why a test writes a file//!//! The dictionary is declared ONCE. Rust reads the declaration directly;//! `scripts/__tests__/plainLanguage.test.ts` runs on Node and cannot, and it//! used to `import { RETIRED_TERMS } from "@cottondb/core"` — a package that//! goes away. A second hand-kept copy in `scripts/` would be a second//! declaration, which is the one thing this list must not have, and a//! Rust→TypeScript generator script would be a whole new lane for one file.//!//! So the emit lives where the guarantee lives: this test RENDERS//! `src/language/retired-terms.json` from the Rust declaration and compares it//! with the committed copy. Add a term and the test is red until the JSON is//! regenerated, exactly like `gen:check`. Regenerate with://!//! ```text//! COTTON_UPDATE_RETIRED_TERMS=1 cargo test -p cotton-core --lib language::emit//! ```//!//! # What the JSON has to carry//!//! `pattern` is the JavaScript SOURCE — the text between the slashes in the//! declaration — and `flags` is what a reader must apply to it. Both matter://! the flags are `i` and NOT `u`, because a JavaScript regex without `u` folds//! case and matches `\b`/`\w` on the ASCII word class only, and that is the//! behaviour every declared pattern was written against and every vector in//! `retired_terms_tests.rs` pins. A reader that spells `new RegExp(pattern)`//! with different flags is asking a different question than the sweeps it//! shares a declaration with.//!//! `retired_terms.rs` IS the declaration — step 5i deleted the TypeScript it//! used to be generated from, and the file that was generated was folded into//! the one that wrapped it (R18). So this JSON is not a copy arriving by way of//! Rust any more; it is the declaration, rendered for the one sweep that cannot//! read Rust.//!//! `cotton-gen`'s `RetiredTerms.swift` renderer reads the Rust declaration//! directly rather than this JSON — it is Rust, so it can.use std::path::PathBuf;use serde_json::{json, Value};use super::retired_terms::{RetiredTerm, RETIRED_TERMS, RETIRED_TERMS_STRICT};/// The env var that turns the comparison into a write.const UPDATE: &str = "COTTON_UPDATE_RETIRED_TERMS";/// Where the emitted file lives, resolved at RUN time — `manifest_dir` says/// why the compile-time constant is not usable in this workspace.fn json_path() -> PathBuf {    cotton_store::manifest_dir().join("src/language/retired-terms.json")}fn term_value(term: &RetiredTerm) -> Value {    json!({        "slug": term.slug,        "pattern": term.pattern,        "instead": term.instead,    })}/// The file's whole content, as this declaration says it should be.fn rendered() -> String {    let document = json!({        "$comment": concat!(            "GENERATED by `cargo test -p cotton-core --lib language::emit` from ",            "crates/cotton-core/src/language/, which is where a term is retired — ",            "a term is NEVER retired here. Regenerate with ",            "COTTON_UPDATE_RETIRED_TERMS=1; the same test fails on drift. ",            "`pattern` is the JavaScript regex SOURCE and `flags` is what to apply ",            "to it: `i` and deliberately not `u`, because the declared patterns match ",            "the ASCII word class and fold case within ASCII only.",        ),        "flags": "i",        "terms": RETIRED_TERMS.iter().map(term_value).collect::<Vec<_>>(),        "strict": RETIRED_TERMS_STRICT.iter().map(term_value).collect::<Vec<_>>(),    });    let mut text = serde_json::to_string_pretty(&document).expect("the dictionary serialises");    text.push('\n');    text}/// RULE: The retired-words list has one declaration; the copy other checks read is generated from it and fails the build when it drifts.#[test]fn the_committed_json_is_what_this_declaration_renders() {    let path = json_path();    let expected = rendered();    if std::env::var(UPDATE).is_ok_and(|value| !value.is_empty()) {        std::fs::write(&path, &expected)            .unwrap_or_else(|error| panic!("could not write {} — {error}", path.display()));        return;    }    let found = std::fs::read_to_string(&path);    assert!(        found.is_ok(),        "{} is missing — the retired vocabulary is emitted there for the readers that are not \         Rust (scripts/__tests__/plainLanguage.test.ts). Regenerate it with {UPDATE}=1 cargo test \         -p cotton-core --lib language::emit",        path.display()    );    assert_eq!(        found.expect("read checked above"),        expected,        "{} has drifted from the Rust declaration. Regenerate it with {UPDATE}=1 cargo test -p \         cotton-core --lib language::emit, and commit it in the SAME change as the term.",        path.display()    );}/// The emitted file is the whole dictionary, not a prefix of it — a reader/// that sweeps 4 of 14 terms passes while the rule goes unenforced.#[test]fn the_json_carries_every_term_and_the_stricter_list_extends_it() {    let document: Value = serde_json::from_str(&rendered()).expect("valid JSON");    let terms = document["terms"].as_array().expect("terms is an array");    let strict = document["strict"].as_array().expect("strict is an array");    assert_eq!(terms.len(), RETIRED_TERMS.len());    assert_eq!(strict.len(), RETIRED_TERMS_STRICT.len());    assert_eq!(        &strict[..terms.len()],        &terms[..],        "the stricter list starts with the declared one, by index"    );    let slugs: Vec<&str> = terms        .iter()        .map(|term| term["slug"].as_str().expect("a slug"))        .collect();    assert_eq!(        slugs,        RETIRED_TERMS            .iter()            .map(|term| term.slug)            .collect::<Vec<_>>()    );    assert!(        terms            .iter()            .all(|term| !term["pattern"].as_str().expect("a pattern").is_empty()),        "every term carries its pattern source"    );    assert_eq!(        document["flags"], "i",        "the flags a JavaScript reader must apply — `i`, and not `u`"    );}