//! RULE (the transforms contract, 22 Oct 2026, architect): every word a person //! reads is a LINE, and Swift draws what the core resolves. An English string //! typed into a Swift view is one the owner cannot reword without a build and //! an assistant cannot translate, so the apps' words move to //! `kits/shell/lines` through the core. //! //! The scan reads every `.swift` file under `apps/cotton/Sources` and //! `apps/loom/Sources` as text — no //! compile, Deck/ included — and flags a string literal holding English (two //! letters in a row, outside its `\( … )` parts, or inside a string nested in //! one) where a person reads it: the first argument of `Text`, `Label`, //! `Button`, `Toggle`, `TextField`, `.navigationTitle`, `.alert`, //! `.confirmationDialog`, `.accessibilityLabel` and the other calls in //! [`DRAWN`], and any argument labelled `title:`, `message:`, `placeholder:`, //! `prompt:` and the others in [`LABELS`], whoever the callee. It skips what //! no person reads, so those never reach the allow-list: SF Symbol names and //! identifiers (never in those places, and a single word with `.`, `-`, `_`, //! `/` or `@` is an identifier), `accessibilityIdentifier`, log and print text //! (anything inside [`DEVELOPER_ONLY`]), `#Preview` and `PreviewProvider` //! bodies, the face fixtures (`CottonUI/Gallery/`, invented specimen data), //! and comments. Tests live outside `Sources` and are not read. //! //! And a literal shaped like a sentence ANYWHERE in Sources — two or more //! words with letters, or ending in `.`, `?` or `…` — is a hit too //! (architect, 22 Oct 2026 03:55Z: an honest count over a smaller number): a //! sentence a function returns reaches a view all the same, and a scan that //! saw only the draw site undercounted. It skips what is matched against //! rather than said ([`MATCHING`], a `case` pattern, `==`), what names a key or //! an image ([`KEY_LABELS`]), and a date pattern. //! //! Every hit standing today is in `swift_literals_allowed.txt` next to this //! file, one per line with its reason. A new one fails here: say it as a line //! (`ShellLines.line("set", "key")`, or a line the core resolves into the //! read), never a new entry. //! //! The list may only shrink (architect's ruling, 22 Oct 2026). An entry //! nothing matches any more FAILS, so a word worked off into a line cannot //! come back allowed. And [`ALLOWED_CEILING`] is a ratchet from day one: more //! entries than it fails. A push that moves entries into lines lowers the //! ceiling to the new count in the same commit; the ceiling rises only with a //! reason in the commit message that names the architect's ruling allowing it. mod rust_text; use rust_text::workspace; use std::path::{Path, PathBuf}; /// How many entries `swift_literals_allowed.txt` may hold — lowered by every /// push that works entries off, raised only by an architect's ruling named in /// the commit message (the module comment says why). const ALLOWED_CEILING: usize = 166; /// Calls whose FIRST argument a person reads (a `verbatim:` label included). const DRAWN: [&str; 26] = [ "Text", "Label", "Button", "Toggle", "Picker", "Menu", "TextField", "SecureField", "Section", "Link", "ContentUnavailableView", "LabeledContent", "DatePicker", "Stepper", "ProgressView", "ShareLink", "navigationTitle", "navigationSubtitle", "alert", "confirmationDialog", "accessibilityLabel", "accessibilityHint", "accessibilityValue", "help", "searchable", "badge", ]; /// Argument labels whose string a person reads, whatever the callee. const LABELS: [&str; 12] = [ "title", "subtitle", "message", "placeholder", "prompt", "label", "detail", "caption", "hint", "header", "footer", "accessibilityLabel", ]; /// Calls whose strings only a developer reads: logs (`Log.write`, /// `Log.warn`), prints, traps, and identifiers a test or the system reads. const DEVELOPER_ONLY: [&str; 28] = [ "print", "warn", // Home's board: a Log.warn said once per launch. "warnOnce", "write", "debugPrint", "NSLog", "os_log", "fatalError", "precondition", "preconditionFailure", "assert", "assertionFailure", "debug", "info", "notice", "warning", "error", "fault", "critical", "trace", "log", "Logger", "OSLog", "DispatchQueue", "accessibilityIdentifier", "Image", "UIImage", "NSImage", ]; #[derive(Clone, Copy, PartialEq, Debug)] enum Tok<'a> { Ident(&'a str), Punct(u8), /// A string literal: its source text between the quotes, and whether it /// holds English (outside its interpolations, or in a string nested in one). Str(&'a str, bool), } struct Token<'a> { tok: Tok<'a>, line: usize, } /// Swift source as identifiers, punctuation and string literals, comments cut. fn tokens(source: &str) -> Vec> { let bytes = source.as_bytes(); let mut out = Vec::new(); let mut i = 0; let mut line = 1; while i < bytes.len() { let c = bytes[i]; match c { b'\n' => { line += 1; i += 1; } b'/' if bytes.get(i + 1) == Some(&b'/') => { while i < bytes.len() && bytes[i] != b'\n' { i += 1; } } b'/' if bytes.get(i + 1) == Some(&b'*') => { let mut depth = 0; while i < bytes.len() { if bytes[i] == b'/' && bytes.get(i + 1) == Some(&b'*') { depth += 1; i += 2; } else if bytes[i] == b'*' && bytes.get(i + 1) == Some(&b'/') { depth -= 1; i += 2; if depth == 0 { break; } } else { if bytes[i] == b'\n' { line += 1; } i += 1; } } } b'"' | b'#' if string_start(bytes, i).is_some() => { let start_line = line; let (hashes, open) = string_start(bytes, i).unwrap(); let body = i + hashes + open; let (end, english) = string_end(bytes, body, hashes, open == 3); line += bytes[i..end].iter().filter(|b| **b == b'\n').count(); let close = end - hashes - if open == 3 { 3 } else { 1 }; out.push(Token { tok: Tok::Str(&source[body..close.max(body)], english), line: start_line }); i = end; } _ if c.is_ascii_alphabetic() || c == b'_' => { let start = i; while i < bytes.len() && (bytes[i].is_ascii_alphanumeric() || bytes[i] == b'_') { i += 1; } out.push(Token { tok: Tok::Ident(&source[start..i]), line }); } _ if c.is_ascii_whitespace() => i += 1, _ if c.is_ascii() => { out.push(Token { tok: Tok::Punct(c), line }); i += 1; } _ => i += 1, } } out } /// At `i`, a string literal's opening: (`#` count, quote count 1 or 3). fn string_start(bytes: &[u8], i: usize) -> Option<(usize, usize)> { let hashes = bytes[i..].iter().take_while(|b| **b == b'#').count(); let at = i + hashes; if bytes.get(at) != Some(&b'"') { return None; } let open = if bytes.get(at + 1) == Some(&b'"') && bytes.get(at + 2) == Some(&b'"') { 3 } else { 1 }; // `""` is an empty string, not the start of a multi-line one. if open == 1 && bytes.get(at + 1) == Some(&b'"') { return Some((hashes, 1)); } Some((hashes, open)) } /// From a literal's body at `i`: the index just past its closing delimiter, /// and whether it holds English (two letters in a row outside its /// interpolations, or anywhere in a string nested inside one). fn string_end(bytes: &[u8], mut i: usize, hashes: usize, multi: bool) -> (usize, bool) { let mut english = false; let mut run = 0; let closes = |at: usize| { let quotes = if multi { 3 } else { 1 }; bytes.len() >= at + quotes + hashes && bytes[at..at + quotes].iter().all(|b| *b == b'"') && bytes[at + quotes..at + quotes + hashes].iter().all(|b| *b == b'#') }; while i < bytes.len() { if closes(i) { return (i + hashes + if multi { 3 } else { 1 }, english); } let c = bytes[i]; let escape = c == b'\\' && bytes[i + 1..].iter().take(hashes).filter(|b| **b == b'#').count() == hashes; if escape { let at = i + 1 + hashes; if bytes.get(at) == Some(&b'(') { let (end, nested) = interpolation_end(bytes, at + 1); english |= nested; i = end; } else { // `\n`, `\t`, `\u{…}`: an escape, never a letter of a word. i = at + 1; if bytes.get(at) == Some(&b'u') && bytes.get(at + 1) == Some(&b'{') { while i < bytes.len() && bytes[i] != b'}' { i += 1; } i += 1; } } run = 0; continue; } if c.is_ascii_alphabetic() { run += 1; english |= run >= 2; } else { run = 0; } if c == b'\n' && !multi { return (i, english); } i += 1; } (i, english) } /// From just inside `\(`: the index past its `)`, and whether a string /// nested in it holds English. fn interpolation_end(bytes: &[u8], mut i: usize) -> (usize, bool) { let mut depth = 1; let mut english = false; while i < bytes.len() { match bytes[i] { b'(' => depth += 1, b')' => { depth -= 1; if depth == 0 { return (i + 1, english); } } b'"' | b'#' if string_start(bytes, i).is_some() => { let (hashes, open) = string_start(bytes, i).unwrap(); let (end, nested) = string_end(bytes, i + hashes + open, hashes, open == 3); english |= nested; i = end; continue; } _ => {} } i += 1; } (i, english) } /// One open bracket: the call it belongs to, whether a top-level comma has /// been seen (the first argument is over), and the current argument's label. struct Group<'a> { caller: Option<&'a str>, first: bool, label: Option<&'a str>, skipped: bool, } /// Each person-read English literal of one file: (line, literal text). fn person_read<'a>(tokens: &[Token<'a>], matching_here: &[&str]) -> Vec<(usize, &'a str)> { let mut hits = Vec::new(); let mut stack: Vec = Vec::new(); // A `{` that opens a `#Preview` or `PreviewProvider` body is skipped whole. let mut skip_next_brace = false; // A `case` pattern list runs to its `:` at the same depth; each literal // in it is matched against, never said. let mut case_depth: Option = None; for (i, token) in tokens.iter().enumerate() { let before = |k: usize| i.checked_sub(k).map(|k| tokens[k].tok); let skipped_above = stack.last().is_some_and(|group| group.skipped); match token.tok { Tok::Ident("Preview") if before(1) == Some(Tok::Punct(b'#')) => skip_next_brace = true, Tok::Ident("PreviewProvider") => skip_next_brace = true, Tok::Ident("case") => case_depth = Some(stack.len()), Tok::Punct(open @ (b'(' | b'[' | b'{')) => { let caller = match before(1) { Some(Tok::Ident(name)) if open != b'{' => Some(name), _ => None, }; let preview = open == b'{' && std::mem::take(&mut skip_next_brace); let developer = caller.is_some_and(|name| DEVELOPER_ONLY.contains(&name)); stack.push(Group { caller, first: true, label: None, skipped: skipped_above || preview || developer }); } Tok::Punct(b')' | b']' | b'}') => { stack.pop(); if case_depth.is_some_and(|depth| depth > stack.len()) { case_depth = None; } } Tok::Punct(b',') => { if let Some(group) = stack.last_mut() { group.first = false; group.label = None; } } Tok::Punct(b':') => { if case_depth == Some(stack.len()) { case_depth = None; } if let (Some(group), Some(Tok::Ident(name))) = (stack.last_mut(), before(1)) { // `a ? b : c` is no label: a label follows `(` or `,`. if matches!(before(2), Some(Tok::Punct(b'(' | b','))) { group.label = Some(name); } } } Tok::Str(text, english) => { let group = stack.last(); if group.is_some_and(|group| group.skipped) || identifier(text) { continue; } let caller = group.and_then(|group| group.caller); let label = group.and_then(|group| group.label); let drawn = english && caller.is_some_and(|name| DRAWN.contains(&name)) && group.is_some_and(|group| group.first) && matches!(label, None | Some("verbatim")); let labelled = english && label.is_some_and(|label| LABELS.contains(&label)); // Anywhere else, a sentence-shaped literal is words a person // will read once some function hands it on — unless it is // matched against rather than said, or names a key. let matched = caller.is_some_and(|name| MATCHING.contains(&name) || matching_here.contains(&name)) || label.is_some_and(|label| KEY_LABELS.contains(&label)) || (case_depth == Some(stack.len()) && matches!(before(1), Some(Tok::Ident("case") | Tok::Punct(b',')))) || (before(1) == Some(Tok::Punct(b'=')) && matches!(before(2), Some(Tok::Punct(b'=' | b'!')))); if drawn || labelled || (!matched && sentence_shaped(text)) { hits.push((token.line, text)); } } _ => {} } } hits } /// Calls that match a literal against text rather than say it. const MATCHING: [&str; 17] = [ "hasPrefix", "hasSuffix", "contains", "starts", "replacingOccurrences", "components", "range", "firstRange", "split", "NSRegularExpression", "Regex", "firstMatch", "evaluateJavaScript", // Executed program text, never displayed. "matches", "trimmingPrefix", "caseInsensitiveCompare", "localizedCaseInsensitiveContains", ]; /// Calls that match a literal against text in ONE file, by its path from the /// repo root: a name too common to pass everywhere (any `match(` would hide /// words handed to a function of that name). const MATCHING_IN_FILE: [(&str, &str); 1] = [ // FaceMarkdown's own regex helper: its literals are patterns. ("apps/loom/Sources/CottonFaces/Shared/FaceMarkdown.swift", "match"), ]; /// The calls `MATCHING_IN_FILE` passes in the file at `at`. fn matching_in(at: &str) -> Vec<&'static str> { MATCHING_IN_FILE.iter().filter(|(file, _)| *file == at).map(|(_, call)| *call).collect() } /// Argument labels whose string is a key, a pattern, a name the system /// reads, a debug description or an image — never words. const KEY_LABELS: [&str; 16] = [ "key", "pattern", "debugDescription", "forKey", "id", "identifier", "named", "systemImage", "systemName", "image", "icon", "subsystem", "category", "domain", "forResource", "withExtension", ]; /// A literal shaped like a sentence wherever it stands (architect, 22 Oct /// 2026 03:55Z): two or more words with letters outside its `\( … )` parts, /// or one ending in `.`, `?` or `…`. A date pattern (`EEE d MMM`) is a /// format, not words. fn sentence_shaped(text: &str) -> bool { let outside = outside(text); let trimmed = outside.trim(); if !trimmed.chars().any(char::is_alphabetic) || date_pattern(trimmed) { return false; } let words = trimmed.split_whitespace().filter(|word| word.chars().filter(|c| c.is_alphabetic()).count() >= 2).count(); words >= 2 || trimmed.ends_with(['.', '?', '\u{2026}']) } /// The literal's own text: each `\( … )` and escape cut to a space, `\u{2026}` /// kept as the ellipsis it is. fn outside(text: &str) -> String { let mut out = String::with_capacity(text.len()); let mut chars = text.chars().peekable(); while let Some(c) = chars.next() { if c != '\\' { out.push(c); continue; } match chars.next() { Some('(') => { let mut depth = 1; let mut quoted = false; for c in chars.by_ref() { match c { '"' => quoted = !quoted, '(' if !quoted => depth += 1, ')' if !quoted => { depth -= 1; if depth == 0 { break; } } _ => {} } } out.push(' '); } Some('u') if chars.peek() == Some(&'{') => { let code: String = chars.by_ref().skip(1).take_while(|c| *c != '}').collect(); out.push(u32::from_str_radix(&code, 16).ok().and_then(char::from_u32).unwrap_or(' ')); } _ => out.push(' '), } } out } /// `EEE d MMM`, `yyyy-MM-dd HH:mm`: every run of letters one repeated /// pattern letter. fn date_pattern(text: &str) -> bool { let mut runs = Vec::new(); let mut run = String::new(); for c in text.chars().chain(std::iter::once(' ')) { if c.is_ascii_alphabetic() { run.push(c); } else if !run.is_empty() { runs.push(std::mem::take(&mut run)); } } runs.iter().all(|run| { let first = run.chars().next().unwrap(); "yMdEHhmsaSZzLGQwWecKkjvVxXOu".contains(first) && run.chars().all(|c| c == first) }) } /// One word with `.`, `-`, `_`, `/`, `@` or `:` and no space: a symbol name, /// a key, a path, an address — never a sentence. fn identifier(text: &str) -> bool { !text.contains(' ') && text.contains(['.', '-', '_', '/', '@', ':']) } /// The lines of each face's catalogue entry (`enum FaceCatalogue { … }` /// in a Loom face file): its specimens are invented data ("Meera Iyer"), /// skipped as a rule as the Gallery's fixtures are; the face's own code beside /// it is read like any other. In a file of Loom's faces (`CottonFaces/`) any /// `enum Catalogue` is that entry: a face not named `…Face` (the in-call /// telephone, the recipe stand) keeps its specimens under its own name /// (`CallTelephoneCatalogue`), invented data all the same. fn catalogue_lines(source: &str, in_faces: bool) -> Vec> { let marker = if in_faces { "Catalogue {" } else { "FaceCatalogue {" }; let mut found = Vec::new(); let mut from = 0; while let Some(offset) = source[from..].find(marker) { let open = from + offset + marker.len() - 1; let line_start = source[..open].rfind('\n').map_or(0, |at| at + 1); let head = source[line_start..open].trim_start(); from = open + 1; if !(head.starts_with("enum ") || head.starts_with("public enum ")) { continue; } let mut depth = 0usize; let mut close = source.len(); for (index, byte) in source.bytes().enumerate().skip(open) { match byte { b'{' => depth += 1, b'}' => { depth -= 1; if depth == 0 { close = index; break; } } _ => {} } } let line = |at: usize| source[..at].matches('\n').count() + 1; found.push(line(open)..=line(close)); from = close.max(from); } found } fn swift_files(dir: &Path, files: &mut Vec) { let Ok(entries) = std::fs::read_dir(dir) else { return }; for entry in entries.flatten() { let path = entry.path(); if path.is_dir() { swift_files(&path, files); } else if path.extension().is_some_and(|ext| ext == "swift") { files.push(path); } } } /// The allow-list's form of a literal: its first non-blank line, trimmed, at /// most 60 characters. An entry must equal it — a prefix would let a new /// literal that starts with an allowed one through. fn listed_form(text: &str) -> &str { let first = text.lines().map(str::trim).find(|line| !line.is_empty()).unwrap_or_default(); match first.char_indices().nth(60) { Some((at, _)) => &first[..at], None => first, } } /// `swift_literals_allowed.txt`: `path "listed form" — reason`. fn allowed() -> Vec<(String, String, String)> { let text = std::fs::read_to_string(cotton_store::manifest_dir().join("tests/swift_literals_allowed.txt")) .expect("tests/swift_literals_allowed.txt"); text.lines() .map(str::trim) .filter(|line| !line.is_empty() && !line.starts_with('#')) .map(|line| { let (path, rest) = line.split_once(" \"").unwrap_or_else(|| panic!("`{line}` is not `path \"literal\" — reason`")); let (literal, reason) = rest.rsplit_once("\" — ").unwrap_or_else(|| panic!("`{line}` names no reason after `\" — `")); assert!(!reason.trim().is_empty(), "`{line}` names no reason"); (path.to_string(), literal.to_string(), reason.to_string()) }) .collect() } #[test] fn no_english_a_person_reads_is_a_literal_in_the_swift_apps() { let started = std::time::Instant::now(); let root = workspace(); let mut files = Vec::new(); // The app and Loom, the package its faces, look and values live in. swift_files(&root.join("apps/cotton/Sources"), &mut files); swift_files(&root.join("apps/loom/Sources"), &mut files); // The face fixtures under `Gallery/` are invented specimen data // ("Aarav", "Receipt"), skipped as a rule like previews (architect, 22 // Oct 2026, on c65444529). files.retain(|path| !path.components().any(|part| part.as_os_str() == "Gallery")); files.sort(); assert!(files.len() > 300, "apps/cotton/Sources and apps/loom/Sources hold {} Swift files — the scan has lost the apps", files.len()); let allowed = allowed(); let mut used = vec![false; allowed.len()]; let mut hits = Vec::new(); let mut seen = 0; for path in &files { let source = std::fs::read_to_string(path).unwrap(); let at = path.strip_prefix(&root).unwrap_or(path).display().to_string(); let specimens = catalogue_lines(&source, at.starts_with("apps/loom/Sources/CottonFaces/")); for (line, text) in person_read(&tokens(&source), &matching_in(&at)) { if specimens.iter().any(|lines| lines.contains(&line)) { continue; } seen += 1; let listed = listed_form(text); let mut matched = false; for (index, (file, literal, _)) in allowed.iter().enumerate() { if *file == at && listed == literal { used[index] = true; matched = true; } } if !matched { hits.push(format!("{at} \"{listed}\" — (line {line})")); } } } let took = started.elapsed(); assert!( hits.is_empty(), "{} English literals a person reads in the Swift apps ({} files, {took:?}) — say each as a line:\n{}", hits.len(), files.len(), hits.join("\n") ); let stale: Vec = allowed .iter() .zip(&used) .filter(|(_, used)| !**used) .map(|((path, literal, _), _)| format!("{path} \"{literal}\"")) .collect(); assert!( stale.is_empty(), "swift_literals_allowed.txt entries nothing matches any more — delete them and lower ALLOWED_CEILING:\n{}", stale.join("\n") ); assert!( allowed.len() <= ALLOWED_CEILING, "swift_literals_allowed.txt holds {} entries and the ceiling is {ALLOWED_CEILING} — say the new words as a line; \ the ceiling rises only by an architect's ruling named in the commit", allowed.len() ); assert!(seen > 0 || allowed.is_empty(), "the scan saw no literal — it has stopped reading the views"); eprintln!("swift literals: {} files, {seen} person-read literals, {} allowed, {took:?}", files.len(), allowed.len()); } /// The scanner's own edges, on inline Swift. #[test] fn the_scan_reads_what_a_person_reads_and_skips_the_rest() { let source = r##" // Text("a comment") Text("Hello there") Text(verbatim: "Raw words") Label("Delete", systemImage: "trash") Image(systemName: "star.fill") Text("\(count)") Text("\(count) \(count == 1 ? "item" : "items")") Text(shown ? "Open" : "Closed") Text(name ?? "Untitled") Text(lookup["key"] ?? "") QuietState(title: "Nothing here", message: "Add one.") DispatchQueue(label: "com.example.queue") print("Debug words here") logger.error("Failed to read \(x)") .accessibilityIdentifier("save button") Button("Save") { } .alert("Remove it?", isPresented: $shown) { } Field(placeholder: "you@example.com") let x = a ? b : "Not a label" #Preview { Text("Preview words") } struct P: PreviewProvider { static var previews: some View { Text("Old preview") } } Text(""" Multi line """) Text(#"Raw "quoted" words"#) Text("·") func said() -> String { "Nothing was found." } static let heading = "Two words" if line.hasPrefix("Some words here") { } switch state { case "two words", "three more words": break } formatter.dateFormat = "EEE d MMM" if x == "two words" { } Image("Brand mark") let one = "word" view.evaluateJavaScript("const words = 'not displayed';") "##; let hits: Vec<&str> = person_read(&tokens(source), &[]).into_iter().map(|(_, text)| text).collect(); // `match` is passed only in the one file whose helper it is: anywhere // else, words handed to a `match(` are words. let helper = r##"Self.match("Two words here", in: source)"##; assert_eq!(person_read(&tokens(helper), &[]).into_iter().map(|(_, text)| text).collect::>(), ["Two words here"]); assert!(person_read(&tokens(helper), &matching_in("apps/loom/Sources/CottonFaces/Shared/FaceMarkdown.swift")).is_empty()); assert_eq!( hits, vec![ "Hello there", "Raw words", "Delete", "\\(count) \\(count == 1 ? \"item\" : \"items\")", "Open", "Closed", "Untitled", "Nothing here", "Add one.", "Save", "Remove it?", "Not a label", "\n Multi line\n ", "Raw \"quoted\" words", "Nothing was found.", "Two words", ] ); }