Cotton code
141 lines · 5.8 KB · RustRaw
//! `RetiredTerms.swift` — the retired vocabulary, rendered ONCE for the whole//! Swift package.//!//! The declaration is `cotton_core::language`, which was generated from//! `packages/core/src/language/retiredTerms.ts` until the flip (step 5, R2/R18).//! In that interval the TypeScript declared, `gen:check --lang` held the Rust//! equal to it, and THIS renderer read the Rust; 5i deleted the TypeScript side//! and the generator, so the Rust IS the declaration and this renderer's input//! did not change.//!//! The brief offered two shapes for the Swift language sweep — read the//! declaration by path at test time, or hand-copy the patterns and guard the//! copy. This is the third and strictly better one: GENERATE the copy, and let//! `--check` be the guard. A path read cannot work from a built test bundle on//! a simulator (the sources are not in it), and a hand copy needs a second test//! to stay honest.//!//! There is one copy and one sweep (R19, then H2's fold): the Mac half had no//! vocabulary file at all until step 5, then carried a second rendering of this//! one until the two apps became one package. A rule enforced on one surface//! only is not a rule, and two copies of the same table are a rule with a seam//! to drift through.use cotton_core::language::retired_terms::{RETIRED_TERMS, RETIRED_TERMS_STRICT};use cotton_core::language::retired_terms::RetiredTerm;use crate::swift::{generated_header, swift_raw, swift_str};fn entry(term: &RetiredTerm) -> Result<String, String> {    Ok([        "    RetiredTerm(".to_string(),        format!("        slug: {},", swift_str(term.slug)),        format!("        pattern: {},", swift_raw(term.pattern)?),        format!("        instead: {}", swift_str(term.instead)),        "    ),".to_string(),    ]    .join("\n"))}pub fn render_retired_terms() -> Result<String, String> {    let terms = RETIRED_TERMS        .iter()        .map(entry)        .collect::<Result<Vec<_>, _>>()?        .join("\n");    let extra = RETIRED_TERMS_STRICT.len() - RETIRED_TERMS.len();    // `RETIRED_TERMS_STRICT` is `RETIRED_TERMS[0..12]` plus one more. Emit the    // shared prefix by INDEX, so a declaration edit that broke the relationship    // fails HERE rather than producing two Swift tables free to disagree in one    // entry. (Same rule, same reason, as the Rust half.)    let mut strict_lines: Vec<String> = Vec::new();    for (at, term) in RETIRED_TERMS_STRICT.iter().enumerate() {        let shared = RETIRED_TERMS.get(at);        match shared {            Some(shared) if shared.slug == term.slug => {                strict_lines.push(format!("    plain[{at}],"))            }            Some(shared) => {                return Err(format!(                    "cotton-gen: RETIRED_TERMS_STRICT[{at}] is \"{}\" where RETIRED_TERMS has \                     \"{}\" — the strict list is meant to EXTEND the plain one, so either the \                     prefix was dropped or the order changed; fix the declaration, not this",                    term.slug, shared.slug                ))            }            None => strict_lines.push(entry(term)?),        }    }    let strict = strict_lines.join("\n");    let count = RETIRED_TERMS.len();    let strict_count = RETIRED_TERMS_STRICT.len();    let header = generated_header("cotton-core — language/retired_terms.rs");    Ok(format!(        r#"{header}//// The retired vocabulary — {count} terms, and {extra} more for sources that never// talk about disk space or about marking a message read.//// Read from `crates/cotton-core/src/language/retired_terms.rs`, which is where a// term is retired; a term is NEVER retired here. `LanguageSweepTests` runs these// patterns over every source in the package — the phone's screens and the Mac// half's alike — and over the phone's string catalogue, which together are the// Swift half of `plainLanguage.test.ts`. The Mac half has no catalogue of its// own and is not getting one: English is the only supported language, so a// catalogue with one locale would carry nothing, and its sentences are swept as// SOURCES instead.//// The patterns are the JavaScript SOURCE with no flags. Every declared one is// `/…/i`, so the Swift options are set ONCE where the regex is built// (`caseInsensitive`) rather than repeated {strict_count} times — a flag repeated is a// flag that goes missing once. `\b` means the same thing in NSRegularExpression// as in a non-unicode JavaScript regex for the ASCII words these patterns name.import Foundation/// One retired term: the pattern that finds it, and the plain words instead.public struct RetiredTerm: Sendable, Equatable {{    /// Stable id, so a test can assert coverage without matching prose.    public let slug: String    /// The pattern SOURCE, exactly as the TypeScript declares it.    public let pattern: String    /// What to say instead — this is the message a failing guard prints.    public let instead: String    public init(slug: String, pattern: String, instead: String) {{        self.slug = slug        self.pattern = pattern        self.instead = instead    }}    /// The compiled form. Case-insensitive, matching the `/i` every declared    /// pattern carries.    public func regex() throws -> NSRegularExpression {{        try NSRegularExpression(pattern: pattern, options: [.caseInsensitive])    }}}}public enum RetiredVocabulary {{    /// The {count}, in the TypeScript's declared order.    public static let plain: [RetiredTerm] = [{terms}    ]    /// Stricter, for sources that never talk about disk space or about marking    /// a message read: a bare `room` here is always the retired metaphor.    ///    /// The first {count} entries are `plain` by index, not by copy.    public static let strict: [RetiredTerm] = [{strict}    ]}}"#    ))}#[cfg(test)]#[path = "retired_tests.rs"]mod tests;