From 27bb1ebf065a58fc415ac9eb05c04a834d3cbb38 Mon Sep 17 00:00:00 2001 From: totoz64 <47389794+totoz64@users.noreply.github.com> Date: Tue, 3 Nov 2026 11:19:25 +0100 Subject: [PATCH 01/56] CP: Adapt French proofing to shared Language packs Keep French locales in Pack(PackLocale), reusing the shared dictionary cache, affix reader and suggestion engine. Add French elisions, bounded accent and split tuning, conservative typography and Quebec punctuation rules. Validate displayed suggestion casing before OCONV and retain the original eligible form when an explicit target is excluded. Preserve historical text fixtures with three documented pre-existing upstream chain differences. Ported from WordCraft #3185; no dictionary or hyphenation data is bundled. --- crates/proof/README.md | 41 ++ crates/proof/src/affix.rs | 66 ++ crates/proof/src/affix_suggest.rs | 30 + crates/proof/src/fr/grammar.rs | 665 ++++++++++++++++++ crates/proof/src/fr/mod.rs | 181 +++++ crates/proof/src/fr/suggest.rs | 81 +++ crates/proof/src/fr/test_dict.rs | 234 ++++++ crates/proof/src/hunspell.rs | 17 +- crates/proof/src/lib.rs | 5 + crates/proof/src/pack_lang.rs | 8 +- crates/proof/tests/affix_compatibility.rs | 92 +++ .../fixtures/affix_compatibility.compact | 7 + .../fixtures/affix_compatibility.expected | 497 +++++++++++++ .../fixtures/affix_compatibility_cases.rs | 61 ++ crates/proof/tests/french_dictionary.rs | 107 +++ crates/proof/tests/french_packs.rs | 124 ++++ 16 files changed, 2210 insertions(+), 6 deletions(-) create mode 100644 crates/proof/src/fr/grammar.rs create mode 100644 crates/proof/src/fr/mod.rs create mode 100644 crates/proof/src/fr/suggest.rs create mode 100644 crates/proof/src/fr/test_dict.rs create mode 100644 crates/proof/tests/affix_compatibility.rs create mode 100644 crates/proof/tests/fixtures/affix_compatibility.compact create mode 100644 crates/proof/tests/fixtures/affix_compatibility.expected create mode 100644 crates/proof/tests/fixtures/affix_compatibility_cases.rs create mode 100644 crates/proof/tests/french_dictionary.rs create mode 100644 crates/proof/tests/french_packs.rs diff --git a/crates/proof/README.md b/crates/proof/README.md index 970670143..b4b4b5ba8 100644 --- a/crates/proof/README.md +++ b/crates/proof/README.md @@ -16,6 +16,7 @@ craft-proof = { git = "https://github.com/storytold/craft-libs", rev = " | English (en-US, en-CA, en-AU, en-GB and the British-spelling Englishes such as en-NZ) | SCOWL 2026 Hunspell dictionary per English + `en-extra.txt`, dialect policy (`en-variants.txt`); a dictionaries-folder English first; without SCOWL the installed Hunspell English, else the built-in Moby list ([below](#english-is-always-checked)) | yes | Moby list, our patterns, heuristic | | Polish, Portuguese, Italian | the installed Hunspell dictionary | yes | TeX patterns (embedded, or a Language pack) | | Croatian, Turkish, Russian, Czech, Indonesian, Spanish (es, es-MX, es-419, es-UY) | the installed Hunspell dictionary (Russian also `ru-extra.txt`) | yes | Turkish and Russian rules; English fallback otherwise | +| French (fr-FR, fr-CA and other French pack locales) | the installed Language pack or Hunspell dictionary; dictionary-driven elisions and accent-oriented suggestions | conservative typography and basic checks, with Quebec punctuation spacing in fr-CA | the Language pack (generic fr fallback) | | German | — | — | TeX patterns (embedded, or a Language pack) | | Bulgarian | — | — | syllable rules | @@ -41,6 +42,12 @@ application data (`%LOCALAPPDATA%\WordCraft\dictionaries` and `%APPDATA%\WordCra `~/Library/Application Support/WordCraft/dictionaries`, `$XDG_DATA_HOME/wordcraft/dictionaries`), then the usual Hunspell and LibreOffice locations. None on the web. +French remains a `ProofLang::Pack` locale: use its full `tag()` for settings and issue identity. +The shared pack loader keeps regional dictionary overrides, fallback to `fr`, reloads and its +memory budget; no separate French dictionary slot or embedded French patterns are added. +Only French packs receive the French spelling tuning and typography; other pack languages +keep their existing behavior. French agreement and conjugation are outside these checks. + State is process-wide: `add_word`, `ignore_word`, `set_dictionaries_folder`, `load_user_dictionary`/`save_user_dictionary`. The crate reads no document model; callers pass plain text and language spans. @@ -221,6 +228,40 @@ CI: `.github/workflows/proof.yml`. storytold/craft-libs#30/#31 by brzuchal (Michał Marcin Brzuchalski) started the shared crate. +### French adaptation validation + +The French rules and original synthetic fixtures are adapted from +[totoz64’s WordCraft contribution #3185](https://github.com/storytold/wordcraft/pull/3185). +They use the shared affix reader and Language pack cache; WCAFF1 remains deliberately rejected. +The historical text fixtures retain their original expected data. Three observations for +Indonesian `bermainkanlah` are explicitly updated in the compatibility test because the +shared reader already supports that prefix plus two suffixes. This is a finite regression +check, not a universal compatibility claim. + +The ordinary tests cover French packs, regional overrides and reloads, options, user words, +NFC/NFD lookup with original ranges, suggestions and pack hyphenation. The opt-in real French +dictionary gate fails when its input is missing; it never silently skips its assertions: + +```sh +WORDCRAFT_DICTIONARIES=/absolute/isolated/french-dictionary cargo test -p craft-proof --test french_dictionary -- --ignored +``` + +For a reproducible real-dictionary run, use Dicollecte 7.7 from LibreOffice/dictionaries +revision `67032ee957631908098a72edf48dc81cac27e369`: +[fr.aff](https://raw.githubusercontent.com/LibreOffice/dictionaries/67032ee957631908098a72edf48dc81cac27e369/fr_FR/dictionaries/fr.aff) and +[fr.dic](https://raw.githubusercontent.com/LibreOffice/dictionaries/67032ee957631908098a72edf48dc81cac27e369/fr_FR/dictionaries/fr.dic). +Verify SHA-256 before invoking the gate (the test checks location and behavior, not hashes): + +| File | SHA-256 | +|---|---| +| fr.aff | `c176610cd5dc4846806a65ddd029f422d87978bf58f224aa44222662a16a2de5` | +| fr.dic | `b78a868e31dd6e373b6c3217969afb898a9acde828a5e7ef97308da42218c88c` | + +Use a dedicated directory containing only the intended `fr.aff`/`fr.dic` pair (or explicit +regional pairs for both regions). The gate requires more than 50,000 dictionary entries and +checks the actual source folder, spelling, accent/elision suggestions, regional dispatch, +combining-mark ranges and hyphenated compounds. No real dictionary is committed here. + ## Owners WordCraft maintainers: echelon, dylanmtaylor, aiongg. diff --git a/crates/proof/src/affix.rs b/crates/proof/src/affix.rs index 0df68665b..32de07659 100644 --- a/crates/proof/src/affix.rs +++ b/crates/proof/src/affix.rs @@ -2212,6 +2212,37 @@ impl AffixDict { self.check_except(w, self.excluded(true)) } + /// Validate a collected suggestion in its displayed case, before OCONV. Only identity, + /// first-letter and uppercase variants are allowed (including uppercase that keeps sharp s). + /// An exact target excluded from suggestions cannot be rescued by a lowercase fallback. + /// This preserves the checker's homonym, compound and CHECKSHARPS rules without scanning + /// stems or changing which words the spelling checker accepts. + pub(crate) fn can_suggest_cased(&self, original: &str, changed: &str) -> bool { + if original.len() > MAX_INPUT_BYTES || changed.len() > MAX_INPUT_BYTES { + return false; + } + if changed != original + && changed != capitalize(original) + && changed != original.to_uppercase() + && changed != original.split('ß').map(str::to_uppercase).collect::>().join("ß") + { + return false; + } + let target = self.normalize(changed); + if self.is_forbidden(&target) { + return false; + } + // The exact simple-word path includes affixes; asking with no exclusions detects a + // target whose only derivations carry NOSUGGEST, SUBSTANDARD or FORBIDDENWORD. Spend + // the same shared suggestion budget as the normal checker, and abstain if it runs out. + match self.simple_word_budgeted(&target, Excluded::default(), true) { + None => return false, + Some(true) if !self.simple_word(&target, self.excluded(true)) => return false, + _ => {} + } + self.can_suggest(changed) + } + /// Whether `w` is a word only through a `KEEPCASE` stem, so it is correct in this letter case /// alone (`km` from `km/K`, which `Km` and `KM` are not). pub(crate) fn case_locked(&self, w: &str) -> bool { @@ -3298,6 +3329,41 @@ pub(crate) mod tests { assert!(d.check("ASSASSASSASSASS") && !d.check(&"SS".repeat(60))); } + #[test] + fn displayed_casing_rejects_exact_exclusions_before_case_fallback() { + for flag in ["N", "F", "S"] { + let aff = "SET UTF-8\nNOSUGGEST N\nFORBIDDENWORD F\nSUBSTANDARD S\nSFX A Y 1\nSFX A 0 s .\nSFX B Y 1\nSFX B 0 S .\n"; + let dic = format!("5\nnormal/A\nNORMAL/{flag}B\nmixCase\npour\nkm/K\n"); + let d = AffixDict::from_hunspell(&format!("{aff}KEEPCASE K\n"), &dic, &[]).unwrap(); + for (original, changed) in [("normal", "NORMAL"), ("normals", "NORMALS")] { + assert!(!d.can_suggest_cased(changed, changed), "{flag}: {changed}"); + assert!(!d.can_suggest_cased(original, changed), "{flag}: {original} → {changed}"); + } + assert!(d.can_suggest_cased("normal", "Normal")); + assert!(d.can_suggest_cased("mixCase", "MIXCASE")); + assert!(d.can_suggest_cased("km", "km") && !d.can_suggest_cased("km", "KM")); + assert!(!d.can_suggest_cased("normal", "pour"), "no arbitrary replacement"); + let back = AffixDict::from_bytes(&d.to_bytes().unwrap()).unwrap(); + assert!(!back.can_suggest_cased("normal", "NORMAL")); + } + } + + #[test] + fn displayed_casing_uses_normalization_and_native_homonym_policy() { + let aff = "SET UTF-8\nNOSUGGEST N\nSUBSTANDARD S\nIGNORE ()\nICONV 1\nICONV Q NORMAL\n"; + for flag in ["N", "S"] { + let d = AffixDict::from_hunspell(aff, &format!("3\nnormal\nNORMAL/{flag}\nNORMAL\n"), &[]).unwrap(); + // Native homonyms carry exclusions: a second entry does not erase NOSUGGEST. + assert!(!d.contains_suggestible("NORMAL")); + assert!(!d.can_suggest_cased("(normal)", "(NORMAL)")); + assert!(!d.can_suggest_cased("Q", "Q")); + } + let plain = AffixDict::from_hunspell(aff, "3\nnormal\nNORMAL\nNORMAL\n", &[]).unwrap(); + assert!(plain.can_suggest_cased("normal", "NORMAL")); + assert!(plain.can_suggest_cased("Q", "Q")); + assert!(!plain.can_suggest_cased(&"x".repeat(MAX_INPUT_BYTES + 1), "NORMAL")); + } + #[test] fn oconv_converts_suggestions_only() { // Answers as Hunspell 1.7 gives them on the same files: `kbt` → `k’t`. diff --git a/crates/proof/src/affix_suggest.rs b/crates/proof/src/affix_suggest.rs index 3b498542c..68336de16 100644 --- a/crates/proof/src/affix_suggest.rs +++ b/crates/proof/src/affix_suggest.rs @@ -426,6 +426,18 @@ pub(crate) fn suggest_in(d: &AffixDict, word: &str, max: usize, t: &Tuning) -> V _ => vec![text.clone()], }; for t in recased { + let eligible = |candidate: &str| { + let original: Vec<_> = text.split(' ').collect(); + let changed: Vec<_> = candidate.split(' ').collect(); + original.len() == changed.len() && original.iter().zip(changed).all(|(a, b)| d.can_suggest_cased(a, b)) + }; + let t = if eligible(&t) { + t + } else if eligible(&text) { + text.clone() + } else { + continue; + }; // Shown as the dictionary's OCONV table writes it (`'` → `’` in French). let t = d.output(&t).into_owned(); if t != word && !out.contains(&t) { @@ -763,6 +775,24 @@ mod tests { assert_eq!(suggest_in(&d, "Piesx", 4, &Tuning::DEFAULT).first().map(String::as_str), Some("Pies")); } + #[test] + fn recasing_keeps_valid_original_when_exact_target_is_excluded() { + for flag in ["N", "F", "S"] { + let aff = "SET UTF-8\nNOSUGGEST N\nFORBIDDENWORD F\nSUBSTANDARD S\nTRY normal\n"; + let d = AffixDict::from_hunspell(aff, &format!("2\nnormal\nNORMAL/{flag}\n"), &[]).unwrap(); + let got = suggest_in(&d, "NORMALL", 4, &Tuning::DEFAULT); + assert!(got.iter().any(|w| w == "normal"), "{flag}: {got:?}"); + assert!(!got.iter().any(|w| w == "NORMAL"), "{flag}: {got:?}"); + let split = AffixDict::from_hunspell(aff, &format!("3\nnormal\nNORMAL/{flag}\npour\n"), &[]).unwrap(); + let got = suggest_in(&split, "NORMALPOUR", 4, &Tuning::DEFAULT); + assert!(got.iter().any(|w| w == "normal pour"), "{flag}: {got:?}"); + assert!(!got.iter().any(|w| w == "NORMAL POUR"), "{flag}: {got:?}"); + } + let d = AffixDict::from_hunspell("NOSUGGEST N\n", "3\nnormal\nNORMAL/N\npour\n", &[]).unwrap(); + assert!(!d.can_suggest_cased("normal", "NORMAL")); + assert!(!d.can_suggest_cased("normal", "pour")); + } + /// A language's tables come after its dictionary's, a TRY alphabet stands in for a missing TRY /// line, and a split rule decides which missing spaces are offered. #[test] diff --git a/crates/proof/src/fr/grammar.rs b/crates/proof/src/fr/grammar.rs new file mode 100644 index 000000000..1d5449b1f --- /dev/null +++ b/crates/proof/src/fr/grammar.rs @@ -0,0 +1,665 @@ +//! French grammar and typography checks: cheap, rule-based and tuned to stay quiet when unsure +//! (a missed mistake costs less than a wrong mark on correct text). Messages are in French. +//! +//! - **Space before `;` `!` `?` `:`**: French typography puts a non-breaking space there — a +//! narrow one (U+202F) before `;` `!` `?`, a full one (U+00A0) before `:`. Only a missing +//! space is flagged (`Bonjour!`): an ordinary one stays quiet until typing turns it into a +//! non-breaking one (no French AutoFormat yet). Quebec French (`fr-CA`) has no space before +//! `;` `!` `?`, only before `:`. Addresses (`https://…`) and times (`10:30`) are left alone. +//! - **Space inside `« »`**: a missing one after `«` or before `»` (`«oui»`) → U+00A0. +//! - **Straight double quotes** around a phrase (`"bonjour"`) → `« bonjour »`; inch marks +//! (`27"`) and unbalanced quotes are left alone. +//! - **Repeated word** (`le le`, `que que`), except repetitions French makes on purpose +//! (`nous nous lavons`, `vous vous trompez`, `si si`, interjections) and a proper noun after +//! the same lower-case word (`de De…`). +//! - **Capital letter at the start of a sentence** after `.` `!` `?`, knowing French +//! abbreviations (`etc.`, `M.`, `p.`, `cf.`), initials, numbers, ellipses, addresses, +//! dialogue (`« Tu viens ? » demanda-t-elle`), inversions (`Quoi ? dit-il`) and exclamations +//! after an interjection (`Ah ! que c'est beau`). +//! - **Elision** (`de avoir` → `d’avoir`, `je ai` → `j’ai`, `le homme` → `l’homme`) for `le`, +//! `la`, `de`, `je`, `me`, `te`, `se`, `ne`, `que` before a vowel. Before an `h` only for words +//! known to have a mute `h`, so aspirated ones (`le hibou`, `la hache`, `le héros`) stay quiet; +//! never before a proper noun, `onze`, `oui`, `y…` words (`le yaourt`) or `la une`. +//! +//! No agreement or conjugation rule, and no English rule (such as `a`/`an`), applies to French +//! text. + +use crate::{Issue, IssueKind, ProofLang, words}; + +/// Non-breaking space, before `:` and inside `« »`. +const NBSP: char = '\u{A0}'; +/// Narrow non-breaking space, before `;` `!` `?`. +const NNBSP: char = '\u{202F}'; + +/// Words French repeats on purpose: pronominal verbs (`nous nous lavons`), emphasis, +/// interjections, onomatopoeia. +const ALLOWED_REPEATS: &[&str] = &[ + "nous", "vous", "si", "oui", "non", "très", "bon", "vite", "là", "ah", "oh", "eh", "ha", "hé", "ho", "hi", "bla", "chut", "toc", "pan", "bravo", + "merci", "allez", "encore", "beaucoup", "fort", "tchin", "bye", "couci", "tam", "miam", "glou", +]; + +/// Abbreviations written with a final period after which a sentence goes on in lower case +/// (lower case, without the period). +const ABBREVIATIONS: &[&str] = &[ + "etc", "cf", "ex", "env", "av", "apr", "mm", "mme", "mmes", "mlle", "mlles", "mgr", "dr", "pr", "me", "st", "ste", "sts", "pp", "vol", "chap", + "fig", "éd", "coll", "trad", "réf", "tél", "art", "al", "op", "cit", "ibid", "id", "resp", "min", "max", "sq", "sqq", "suiv", "hab", "janv", + "févr", "avr", "juil", "sept", "oct", "nov", "déc", "bd", "boul", "cie", "éts", "vve", "nb", "ps", "no", "nos", "vs", "qqch", "qqn", "ca", + "approx", "prof", "dir", "sté", "dépt", "adj", "adv", "fém", "masc", "sing", "plur", "à-d", "ms", "mss", "éds", "trim", "hôp", +]; + +/// Words after which `!` or `?` doesn't end the sentence (`Ah ! que c'est beau`, `Eh bien ? +/// et alors`). +const INTERJECTIONS: &[&str] = &[ + "ah", "oh", "eh", "hé", "hein", "hélas", "bah", "ô", "aïe", "ouf", "oups", "quoi", "comment", "ha", "ho", "bon", "tiens", "allons", "zut", + "chut", "bravo", "hourra", "dame", "bien", "là", "oui", "non", "pardon", "voyons", +]; + +/// Pronouns ending an inversion (`dit-il`, `demanda-t-elle`): after one, a `!` or `?` doesn't +/// end the sentence (`Quoi ? dit-il`). +const INVERTED: &[&str] = &["-il", "-elle", "-on", "-ils", "-elles", "-je", "-tu", "-nous", "-vous"]; + +/// Speech verbs of a dialogue tag: after one, a `!` or `?` doesn't end the sentence (`— Tu +/// viens ? demanda le voisin`). +const SPEECH_VERBS: &[&str] = &[ + "dit", + "demanda", + "répondit", + "cria", + "murmura", + "ajouta", + "reprit", + "fit", + "lança", + "souffla", + "répliqua", + "interrogea", + "hurla", + "poursuivit", + "continua", + "déclara", + "expliqua", + "protesta", + "soupira", + "chuchota", + "insista", + "s'écria", + "s’écria", + "s'exclama", + "s’exclama", + "objecta", + "conclut", + "dis", + "dit-on", +]; + +/// The words that elide before a vowel, and their elided form. +const ELIDING: &[(&str, &str)] = + &[("le", "l"), ("la", "l"), ("de", "d"), ("je", "j"), ("me", "m"), ("te", "t"), ("se", "s"), ("ne", "n"), ("que", "qu")]; + +/// Words starting with a vowel that don't take an elision (`le onze`, `le oui`, `de ouate`). +const NO_ELISION: &[&str] = &["onze", "onzième", "onzièmes", "oui", "ouistiti", "ouistitis", "ouate", "ouates", "uhlan", "uhlans"]; + +/// Words with a mute `h`, which take an elision (`l’homme`, `d’habitude`, `j’habite`). Only these +/// are flagged: an `h` word outside the list may be aspirated (`le hibou`, `la hache`, `le +/// héros`), and staying quiet is the safe side. +const MUTE_H: &[&str] = &[ + "homme", + "hommes", + "heure", + "heures", + "histoire", + "histoires", + "hiver", + "hivers", + "hôtel", + "hôtels", + "herbe", + "herbes", + "habitude", + "habitudes", + "habitant", + "habitants", + "habit", + "habits", + "hôpital", + "hôpitaux", + "humain", + "humains", + "humanité", + "honneur", + "honneurs", + "horizon", + "horizons", + "huile", + "huiles", + "hypothèse", + "hypothèses", + "harmonie", + "héritage", + "héroïne", + "héroïnes", + "hésitation", + "hommage", + "hommages", + "horaire", + "horaires", + "horreur", + "horreurs", + "humeur", + "humour", + "hygiène", + "hymne", + "habiter", + "hériter", + "hésiter", + "habiller", + "honorer", + "habite", + "habites", + "habitent", + "habitais", + "habitait", + "hésite", + "hésites", + "hésitent", + "hésitais", + "hésitait", + "habille", + "habillent", + "honore", + "hier", + "hôte", + "hôtes", + "hôtesse", + "humidité", + "haleine", + "hebdomadaire", + "hectare", + "hectares", + "hélicoptère", + "hémisphère", + "heureux", + "heureuse", + "hippopotame", + "hirondelle", + "honnête", + "honnêteté", + "huître", + "huîtres", + "humble", + "humilité", + "hydrogène", + "hypocrite", + "horloge", + "hôtellerie", + "hérédité", + "historien", + "historique", + "humanitaire", + "hormone", + "hormones", + "hospitalité", +]; + +fn issue(start: usize, end: usize, message: String, suggestions: Vec) -> Issue { + Issue { start, end, kind: IssueKind::Grammar, message, suggestions, lang: ProofLang::from_tag(Some("fr-FR")) } +} + +/// Is `c` a space that doesn't break (or a thin space some writers use instead)? +fn is_fixed_space(c: char) -> bool { + matches!(c, '\u{A0}' | '\u{202F}' | '\u{2007}' | '\u{2009}' | '\u{2060}') +} + +/// The byte range of the whitespace-delimited token around byte `i` of `text`. +fn token_bounds(text: &str, i: usize) -> (usize, usize) { + let start = text.get(..i).and_then(|t| t.char_indices().rev().find(|(_, c)| c.is_whitespace())).map_or(0, |(k, c)| k + c.len_utf8()); + let end = text.get(i..).and_then(|t| t.find(char::is_whitespace)).map_or(text.len(), |k| i + k); + (start, end) +} + +/// The whitespace-delimited token around byte `i` of `text`. +fn token_at(text: &str, i: usize) -> &str { + let (start, end) = token_bounds(text, i); + text.get(start..end).unwrap_or("") +} + +/// Is `token` a web or e-mail address, a path or an HTML entity, where punctuation isn't prose? +fn is_address(token: &str) -> bool { + token.contains("://") || token.contains('@') || token.starts_with("www.") || token.contains('&') || token.contains('\\') +} + +/// `«` + text + `»` in a message, with French spacing. +fn quoted(s: &str) -> String { + format!("«{NBSP}{s}{NBSP}»") +} + +/// `;` `!` `?` `:` without the non-breaking space French puts before them. +/// Quebec typography (`quebec`) puts no space before `;` `!` `?`, only before `:`. +fn high_punctuation(text: &str, quebec: bool, v: &mut Vec) { + let mut token: Option<(usize, usize, bool)> = None; + for (i, p) in text.char_indices() { + if !matches!(p, ';' | ':' | '!' | '?') || (quebec && p != ':') { + continue; + } + let before = text.get(..i).and_then(|t| t.chars().next_back()); + let after = text.get(i + p.len_utf8()..).and_then(|t| t.chars().next()); + // One look per token, so a long run of marks stays linear. + let address = match token { + Some((start, end, address)) if start <= i && i < end => address, + _ => { + let (start, end) = token_bounds(text, i); + let address = is_address(text.get(start..end).unwrap_or("")); + token = Some((start, end, address)); + address + } + }; + if address { + continue; + } + let (space, kind) = if p == ':' { (NBSP, "insécable") } else { (NNBSP, "fine insécable") }; + let message = format!("Espace {kind} attendue avant {}", quoted(&p.to_string())); + let fix = format!("{space}{p}"); + // Only a missing space is flagged: an ordinary one stays quiet until typing turns it into + // a non-breaking one by itself (French AutoFormat). + if before.is_some_and(char::is_alphabetic) { + // `10:30`, `a:b`, `C:` and `x;y` aren't prose: the mark must end the word. + let ends = match p { + ':' => after.is_none_or(char::is_whitespace), + _ => after.is_none_or(|a| a.is_whitespace() || matches!(a, '!' | '?' | '»' | '"' | '”' | ')')), + }; + if ends { + v.push(issue(i, i + p.len_utf8(), message, vec![fix])); + } + } + } +} + +/// `«` and `»` without a non-breaking space inside. +fn guillemets(text: &str, v: &mut Vec) { + for (i, c) in text.char_indices() { + let len = c.len_utf8(); + match c { + '«' => { + let mut next = text.get(i + len..).unwrap_or("").chars(); + let message = format!("Espace insécable attendue après {}", quoted("«")); + if next.next().is_some_and(char::is_alphanumeric) { + v.push(issue(i, i + len, message, vec![format!("«{NBSP}")])); + } + } + '»' => { + let prev = text.get(..i).unwrap_or("").chars().next_back(); + let message = format!("Espace insécable attendue avant {}", quoted("»")); + if prev.is_some_and(|n| n.is_alphanumeric() || matches!(n, '.' | '!' | '?' | '…')) { + v.push(issue(i, i + len, message, vec![format!("{NBSP}»")])); + } + } + _ => {} + } + } +} + +/// `"…"` around a phrase, where French uses `« … »`. +fn straight_quotes(text: &str, v: &mut Vec) { + let quotes: Vec = text.match_indices('"').map(|(i, _)| i).collect(); + // An odd count leaves no telling which quote opens and which closes. + if !quotes.len().is_multiple_of(2) { + return; + } + for pair in quotes.chunks(2) { + let [a, b] = pair else { continue }; + let (Some(inner), Some(before), Some(after)) = (text.get(a + 1..*b), text.get(..*a), text.get(b + 1..)) else { continue }; + let opens = before.chars().next_back().is_none_or(|c| c.is_whitespace() || matches!(c, '(' | '[' | '—' | '–')); + let closes = after.chars().next().is_none_or(|c| c.is_whitespace() || matches!(c, '.' | ',' | ';' | ':' | '!' | '?' | ')' | ']' | '…')); + let phrase = inner.trim(); + if !opens || !closes || !phrase.chars().any(char::is_alphabetic) || phrase.chars().count() > 120 || phrase.contains('\n') { + continue; + } + v.push(issue(*a, b + 1, format!("Guillemets français attendus{NBSP}: {}", quoted(phrase)), vec![quoted(phrase)])); + } +} + +fn repeated_words(text: &str, ws: &[(usize, usize)], v: &mut Vec) { + for pair in ws.windows(2) { + let [(a0, b0), (a1, b1)] = pair else { continue }; + let (Some(w0), Some(w1), Some(gap)) = (text.get(*a0..*b0), text.get(*a1..*b1), text.get(*b0..*a1)) else { continue }; + let lower = w0.to_lowercase(); + let starts_upper = |w: &str| w.chars().next().is_some_and(char::is_uppercase); + if !gap.is_empty() + && gap.chars().all(char::is_whitespace) + && w0.chars().all(char::is_alphabetic) + && lower == w1.to_lowercase() + && !ALLOWED_REPEATS.contains(&lower.as_str()) + // `de De…`, `Bora Bora`: a capitalized second word is a name. + && !starts_upper(w1) + { + v.push(issue(*a0, *b1, format!("Mot répété{NBSP}: {}", quoted(w1)), vec![w0.to_string()])); + } + } +} + +/// Is `prev`, before a period, an abbreviation, an initial, a number or a Roman numeral (after +/// which a lower-case word doesn't start a sentence)? +fn abbreviation_or_number(prev: &str) -> bool { + prev.chars().count() <= 1 + || prev.chars().any(|c| c.is_ascii_digit()) + || prev.chars().all(|c| matches!(c, 'I' | 'V' | 'X' | 'L' | 'C' | 'D' | 'M')) + || ABBREVIATIONS.contains(&prev.to_lowercase().as_str()) +} + +/// Does `gap`, between the words `prev` and `next`, end a sentence: a `.`, `!` or `?` (French +/// puts a space before the last two), then a space, with only quotes and brackets around? Not +/// an ellipsis, not after an abbreviation; for `!` and `?`, not after an interjection, not before +/// a closing quote (dialogue goes on: `« Tu viens ? » demanda-t-elle`), not before an inversion +/// or a speech verb (`Quoi ? dit-il`, `— Viens ! cria-t-on`), and never in a `dialogue` line (one +/// opening with a dash). +fn ends_sentence(gap: &str, prev: &str, next: &str, dialogue: bool) -> bool { + let closing = ['"', '”', '’', '\'', ')', '»', ']']; + let t = gap.trim_start_matches(|c: char| c.is_whitespace() || is_fixed_space(c) || closing.contains(&c)); + let Some(end) = t.chars().next() else { return false }; + if !matches!(end, '.' | '!' | '?') || t.starts_with("..") { + return false; + } + if end == '.' && abbreviation_or_number(prev) { + return false; + } + let exclamation = end != '.'; + let lower_next = next.to_lowercase(); + if exclamation + && (dialogue + || INTERJECTIONS.contains(&prev.to_lowercase().as_str()) + || INVERTED.iter().any(|p| lower_next.ends_with(p)) + || SPEECH_VERBS.contains(&lower_next.as_str())) + { + return false; + } + let rest = t.trim_start_matches(['.', '!', '?']); + let after_marks = rest.trim_start_matches(is_fixed_space); + if after_marks.starts_with(closing) { + if exclamation { + return false; + } + return ends_sentence_after(after_marks.trim_start_matches(|c: char| closing.contains(&c) || is_fixed_space(c))); + } + ends_sentence_after(rest) +} + +/// Is `rest` (after the final mark) a space, then nothing but opening quotes and brackets? +fn ends_sentence_after(rest: &str) -> bool { + rest.starts_with(char::is_whitespace) + && rest.trim_start().chars().all(|c| c.is_whitespace() || is_fixed_space(c) || matches!(c, '"' | '“' | '«' | '(' | '[' | '—' | '–')) +} + +fn sentence_capitals(text: &str, ws: &[(usize, usize)], v: &mut Vec) { + let dialogue = text.trim_start().starts_with(['—', '–']); + for pair in ws.windows(2) { + let [(a0, b0), (a1, b1)] = pair else { continue }; + let (Some(prev), Some(gap), Some(w)) = (text.get(*a0..*b0), text.get(*b0..*a1), text.get(*a1..*b1)) else { continue }; + let word_like = w.chars().all(|c| c.is_alphabetic() || matches!(c, '\'' | '’' | '-')); + if word_like && w.chars().next().is_some_and(char::is_lowercase) && ends_sentence(gap, prev, w, dialogue) && !is_address(token_at(text, *a1)) + { + let fixed: String = w.chars().next().map(|f| f.to_uppercase().chain(w.chars().skip(1)).collect()).unwrap_or_default(); + v.push(issue(*a1, *b1, "Majuscule attendue en début de phrase".into(), vec![fixed])); + } + } +} + +/// Does `w` (lower case) start with a sound that makes `le`, `de`, `que`… elide? +fn takes_elision(w: &str) -> bool { + let Some(first) = w.chars().next() else { return false }; + if NO_ELISION.contains(&w) { + return false; + } + match first { + 'a' | 'à' | 'â' | 'ä' | 'e' | 'é' | 'è' | 'ê' | 'ë' | 'i' | 'î' | 'ï' | 'o' | 'ô' | 'ö' | 'u' | 'ù' | 'û' | 'ü' | 'œ' | 'æ' => { + true + } + 'h' => MUTE_H.contains(&w), + // Only `y` itself (`j’y vais`): `le yaourt`, `de yoga`. + 'y' => w == "y", + _ => false, + } +} + +fn elisions(text: &str, ws: &[(usize, usize)], v: &mut Vec) { + for pair in ws.windows(2) { + let [(a0, b0), (a1, b1)] = pair else { continue }; + let (Some(w0), Some(w1), Some(gap)) = (text.get(*a0..*b0), text.get(*a1..*b1), text.get(*b0..*a1)) else { continue }; + if gap.is_empty() || !gap.chars().all(|c| c == ' ') { + continue; + } + let lower0 = w0.to_lowercase(); + let Some((_, elided)) = ELIDING.iter().find(|(full, _)| *full == lower0) else { continue }; + // `le`/`Le` only, not `LE`; never before a proper noun (`de Orléans`) or a capital. + let capital = w0.chars().next().is_some_and(char::is_uppercase); + if w0.chars().skip(1).any(char::is_uppercase) || !w1.chars().next().is_some_and(char::is_lowercase) { + continue; + } + if !w1.chars().all(|c| c.is_alphabetic() || c == '-') { + continue; + } + let lower1 = w1.to_lowercase(); + // `le un`, `la une` (the number, the front page); a single letter only where it is a word + // the elision is certain for (`n’a`, `qu’a`, `j’y`). + if matches!(lower0.as_str(), "le" | "la") && matches!(lower1.as_str(), "un" | "une") { + continue; + } + let certain = (lower1 == "y" && matches!(lower0.as_str(), "je" | "me" | "te" | "se" | "ne")) + || (lower1 == "a" && matches!(lower0.as_str(), "ne" | "que")); + if lower1.chars().count() == 1 && !certain { + continue; + } + if !takes_elision(&lower1) { + continue; + } + let head = if capital { crate::affix::capitalize(elided) } else { (*elided).to_string() }; + let fixed = format!("{head}’{w1}"); + v.push(issue(*a0, *b1, format!("Élision{NBSP}: {}", quoted(&fixed)), vec![fixed])); + } +} + +/// Grammar issues in a paragraph of French text (France's typography), in order. +pub fn check(text: &str) -> Vec { + check_in(text, ProofLang::from_tag(Some("fr-FR"))) +} + +/// Grammar issues in a French Language pack locale, with Quebec typography in `fr-CA`. +/// Other locales have no French issues; the original locale is retained on every issue. +pub fn check_in(text: &str, lang: ProofLang) -> Vec { + let Some(locale) = lang.pack_locale().filter(|l| l.primary() == "fr") else { return Vec::new() }; + let ws: Vec<(usize, usize)> = words(text); + let mut v = Vec::new(); + high_punctuation(text, crate::lang::region(locale.as_str()).is_some_and(|r| r.eq_ignore_ascii_case("CA")), &mut v); + guillemets(text, &mut v); + straight_quotes(text, &mut v); + repeated_words(text, &ws, &mut v); + sentence_capitals(text, &ws, &mut v); + elisions(text, &ws, &mut v); + for i in &mut v { + i.lang = lang; + } + v.sort_by_key(|i| (i.start, i.end)); + v +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The issues of `text` as (flagged text, first suggestion). + fn found(text: &str) -> Vec<(String, String)> { + check(text) + .iter() + .map(|i| (text.get(i.start..i.end).unwrap_or("?").to_string(), i.suggestions.first().cloned().unwrap_or_default())) + .collect() + } + + fn quiet(text: &str) { + let v = check(text); + assert!(v.is_empty(), "{text:?} → {v:?}"); + } + + fn one(text: &str, flagged: &str, fix: &str) { + assert_eq!(found(text), [(flagged.to_string(), fix.to_string())], "{text:?}"); + } + + #[test] + fn missing_space_before_high_punctuation() { + one("Bonjour!", "!", "\u{202F}!"); + one("Tu viens?", "?", "\u{202F}?"); + one("Il pleut; il vente.", ";", "\u{202F};"); + one("Note: rien.", ":", "\u{A0}:"); + // `?!`: only the first mark needs the space. + one("Quoi?!", "?", "\u{202F}?"); + assert!(check("Bonjour!").iter().all(|i| i.lang == ProofLang::from_tag(Some("fr-FR")) && i.message.contains("fine insécable"))); + assert!(check("Note: rien.").iter().all(|i| i.message.contains("insécable") && !i.message.contains("fine"))); + } + + #[test] + fn an_ordinary_space_stays_quiet_until_french_autoformat() { + // Typing can't produce a non-breaking space yet, so an ordinary one is accepted. + quiet("Vraiment ? Bonjour ! Il pleut ; note : rien."); + quiet("Il dit « oui » hier."); + } + + #[test] + fn quebec_has_no_space_before_semicolon_exclamation_and_question() { + let fr_ca = |t: &str| check_in(t, ProofLang::from_tag(Some("fr-CA"))); + assert!(fr_ca("Bonjour! Tu viens? Il pleut; il vente.").is_empty(), "{:?}", fr_ca("Bonjour! Tu viens?")); + // The colon and the guillemets still want their space in Quebec. + let v = fr_ca("Note: «oui»."); + assert_eq!(v.len(), 3, "{v:?}"); + assert!(v.iter().all(|i| i.lang == ProofLang::from_tag(Some("fr-CA"))), "{v:?}"); + assert_eq!(check_in("Bonjour!", ProofLang::from_tag(Some("fr-FR"))).len(), 1, "France still wants the space"); + } + + #[test] + fn high_punctuation_stays_quiet() { + quiet("Bonjour\u{202F}! Tu viens\u{202F}? Il pleut\u{202F}; note\u{A0}: rien."); + quiet("Bonjour\u{A0}! Quoi\u{202F}?! Ah\u{2009}!"); + quiet("Il est 10:30."); + quiet("Voir https://exemple.org:8080/a?b=c pour la suite."); + quiet("Écrire à contact@exemple.org!"); + quiet("Super :) et ;-) aussi :D"); + quiet("a:b et x;y"); + quiet("Le fichier C:\\dossier est là."); + } + + #[test] + fn missing_space_inside_guillemets() { + assert_eq!(found("Il dit «oui» hier."), [("«".to_string(), "«\u{A0}".to_string()), ("»".to_string(), "\u{A0}»".to_string())]); + quiet("Il dit «\u{A0}oui\u{A0}» hier."); + quiet("Il dit «\u{202F}oui\u{202F}» hier."); + } + + #[test] + fn straight_quotes_become_guillemets() { + one("Il a dit \"bonjour\" hier.", "\"bonjour\"", "«\u{A0}bonjour\u{A0}»"); + one("\"Bonne idée\", dit-elle.", "\"Bonne idée\"", "«\u{A0}Bonne idée\u{A0}»"); + // Inch marks and unbalanced quotes are left alone. + quiet("Un écran de 27\" et un de 32\" ici."); + quiet("Il a dit \"bonjour hier."); + } + + #[test] + fn repeated_words_are_flagged() { + one("Le le chat dort.", "Le le", "Le"); + one("Je pense que que tu viens.", "que que", "que"); + one("Il mange la la pomme.", "la la", "la"); + } + + #[test] + fn deliberate_repetitions_stay_quiet() { + quiet("Nous nous lavons et vous vous trompez."); + quiet("Si si, très très bien."); + quiet("Ah ah, bla bla."); + quiet("Je crois que qu’il viendra."); + quiet("Le livre de De Gaulle."); + quiet("Nous partons à Bora Bora."); + quiet("Ils ont dit bye bye. Tchin tchin\u{202F}!"); + } + + #[test] + fn sentence_capitals_are_flagged() { + one("Il pleut. il fait froid.", "il", "Il"); + one("Il pleut\u{202F}! il fait froid.", "il", "Il"); + one("Tu viens\u{202F}? on part.", "on", "On"); + one("Il pleut. l’orage arrive.", "l’orage", "L’orage"); + one("Il pleut. «\u{A0}tout va bien\u{A0}», dit-il.", "tout", "Tout"); + } + + #[test] + fn sentence_capitals_stay_quiet() { + quiet("Voir p. 12 et cf. la note, etc. puis la suite."); + quiet("M. le maire est là."); + quiet("Il attend… puis part. Il attend... puis part."); + quiet("«\u{A0}Tu viens\u{202F}?\u{A0}» demanda-t-elle."); + quiet("Ah\u{202F}! que c’est beau."); + quiet("Quoi\u{202F}? dit-il."); + quiet("Tu viens\u{202F}? demanda le voisin."); + quiet("— Tu viens\u{202F}? reprends-tu, inquiet."); + quiet("– Viens\u{202F}! on part."); + quiet("Voir www.exemple.fr pour la suite."); + quiet("En 2026. ensuite rien."); + quiet("il commence en minuscule."); + } + + #[test] + fn missing_elisions_are_flagged() { + one("Il refuse de avoir peur.", "de avoir", "d’avoir"); + one("Je ai faim.", "Je ai", "J’ai"); + one("Voici le homme.", "le homme", "l’homme"); + one("Je sais que il viendra.", "que il", "qu’il"); + one("Le arbre est grand.", "Le arbre", "L’arbre"); + one("Il ne a pas faim.", "ne a", "n’a"); + one("Bon, je y vais.", "je y", "j’y"); + one("Il se est levé.", "se est", "s’est"); + one("Voici la école.", "la école", "l’école"); + one("Il me aime.", "me aime", "m’aime"); + } + + #[test] + fn aspirated_h_and_other_exceptions_stay_quiet() { + for w in [ + "hibou", + "héros", + "haricot", + "hasard", + "haut", + "hall", + "hamac", + "hangar", + "hockey", + "homard", + "huit", + "hérisson", + "hors-jeu", + "onze", + "oui", + "yaourt", + ] { + quiet(&format!("Voici le {w}.")); + } + // hiérarchie has an aspirated h, despite the mute h in hiéroglyphe: + // https://www.academie-francaise.fr/le-hieroglyphe-pour-lhieroglyphe + for w in ["honte", "hache", "harpe", "hausse", "hiérarchie"] { + quiet(&format!("Voici la {w}.")); + } + quiet("Une question de hiérarchie."); + quiet("Le onze de France. À la une du journal."); + quiet("Il vient de Orléans."); + quiet("De a à z, le a et le b."); + quiet("Le y et le x sont des variables. La dérivée de y."); + quiet("Je mange de la viande."); + } + + #[test] + fn hostile_input_never_panics() { + for t in ["", " ", "!", " !", "«", "»", " »", "« ", "\"", "\"\"", ". a", "de", "de ", "\u{202F}?", "é!é", "« » « »", ":", " :", "a :)"] + { + let _ = check(t); + } + // A long run of marks in one token: linear, not one token scan per mark. + let run = format!("mot{}", "?".repeat(200_000)); + assert_eq!(check(&run).len(), 1); + } +} diff --git a/crates/proof/src/fr/mod.rs b/crates/proof/src/fr/mod.rs new file mode 100644 index 000000000..541fcac0d --- /dev/null +++ b/crates/proof/src/fr/mod.rs @@ -0,0 +1,181 @@ +//! French proofing through the shared Language pack cache. +//! +//! A French locale remains [`ProofLang::Pack`]: dictionary selection, installation, reloads, +//! memory limits and hyphenation use the same paths as other packs. This module adds French +//! elisions, accent-oriented suggestions and conservative typography, including Quebec spacing. +//! No dictionary or hyphenation data is bundled here. + +pub mod grammar; +mod suggest; +#[cfg(test)] +#[allow(clippy::unwrap_used)] +pub(crate) mod test_dict; + +use crate::affix::AffixDict; +use crate::{Options, ProofLang}; + +pub use suggest::suggest_in; + +/// Words after whose elision a user-dictionary entry is accepted. Ordinary words and their +/// elisions are always decided by the dictionary (`l'arbre`, but not `l'arbres`). +const ELISIONS: &[&str] = &["l", "d", "j", "m", "t", "s", "n", "c", "qu", "jusqu", "lorsqu", "puisqu", "quoiqu", "presqu", "quelqu"]; + +/// Check French spelling in the installed France/generic pack, with the default options. +/// Regional callers should use [`crate::is_correct_in`] with their full locale. +pub fn is_correct(word: &str) -> bool { + crate::is_correct_in(word, ProofLang::from_tag(Some("fr-FR"))) +} + +/// French suggestions from the installed France/generic pack, best first, at most `max`. +/// Regional callers should use [`crate::suggest_in`] with their full locale. +pub fn suggest(word: &str, max: usize) -> Vec { + crate::suggest_in(word, max, ProofLang::from_tag(Some("fr-FR"))) +} + +/// Check against a supplied dictionary, without changing any installed pack or cache. +pub fn is_correct_with(d: &AffixDict, word: &str) -> bool { + check(d, &crate::composed(word), &Options::default()) +} + +pub(crate) fn check(d: &AffixDict, word: &str, opts: &Options) -> bool { + let Some(w) = crate::spelling::word_to_check(d, word, opts) else { return true }; + // A regional dictionary may store the curly apostrophe without ICONV. Honor that entry + // before the French ASCII-apostrophe fallback. + if known(d, w) { + return true; + } + let w = w.replace('’', "'"); + if known(d, &w) { + return true; + } + if let Some((head, tail)) = w.split_once('\'') + && ELISIONS.contains(&head.to_lowercase().as_str()) + && !tail.is_empty() + && !tail.contains('\'') + && crate::in_user_dictionary(&tail.to_lowercase()) + { + return true; + } + w.contains('-') && w.split('-').all(|p| !p.is_empty() && (p.chars().count() <= 1 || known(d, p))) +} + +fn known(d: &AffixDict, word: &str) -> bool { + d.check(word) || crate::in_user_dictionary(&word.to_lowercase()) +} + +#[cfg(test)] +#[allow(clippy::unwrap_used)] +mod tests { + use super::*; + + #[test] + fn original_french_words_and_elisions() { + let d = test_dict::dictionary(); + for word in [ + "maison", + "maisons", + "école", + "écoles", + "grand", + "grande", + "grands", + "grandes", + "aimer", + "aime", + "aimons", + "aiment", + "suis", + "est", + "sommes", + "sont", + "a", + "avons", + "ont", + "Paris", + "Montréal", + "œuvre", + "sœur", + "aujourd'hui", + "aujourd’hui", + "peut-être", + "arc-en-ciel", + "km", + "Maison", + "MAISON", + "SNCF", + "2026", + "très", + "rivière", + "l'arbre", + "l’arbre", + "L'arbre", + "d'enfants", + "l'homme", + "qu'elle", + "qu’il", + "j'aime", + "j’ai", + "d'avoir", + "l'école", + "jusqu'à", + "maison-école", + "est-il", + "a-t-il", + ] { + assert!(is_correct_with(&d, word), "{word}"); + } + for word in [ + "maisonn", + "ecole", + "arbrre", + "beaucoups", + "aimmer", + "soeur", + "Km", + "grandd", + "aim", + "l'hasard", + "l'chat", + "l'arbres", + "l'arbrre", + "qu'maison", + "maison-ecole", + "maison--école", + ] { + assert!(!is_correct_with(&d, word), "{word}"); + } + assert!(is_correct_with(&d, "e\u{301}cole")); + assert!(!is_correct_with(&d, "maison\u{338}"), "a trailing mark is part of the word"); + } + + #[test] + fn explicit_curly_apostrophe_without_iconv() { + let d = AffixDict::from_hunspell("SET UTF-8\n", "1\naujourd’hui\n", &[]).unwrap(); + assert!(is_correct_with(&d, "aujourd’hui")); + assert!(!is_correct_with(&d, "aujourd’huui")); + } + + #[test] + fn user_word_after_an_elision() { + let d = test_dict::dictionary(); + let word = "zxqmotadaptfr"; + assert!(!is_correct_with(&d, word) && !is_correct_with(&d, &format!("l'{word}"))); + crate::add_word(word); + assert!(is_correct_with(&d, word) && is_correct_with(&d, &format!("l'{word}")) && is_correct_with(&d, &format!("d’{word}"))); + assert!(!is_correct_with(&d, &format!("chat'{word}"))); + crate::remove_word(word); + } + + #[test] + fn options_and_missing_dictionary() { + let d = test_dict::dictionary(); + let defaults = Options::default(); + let strict = Options { ignore_uppercase: false, ignore_numbers: false, ..defaults }; + assert!(check(&d, "SNCF", &defaults) && check(&d, "mp3x", &defaults)); + assert!(!check(&d, "SNCF", &strict) && !check(&d, "mp3x", &strict)); + assert!(check(&d, "MAISON", &strict) && check(&d, "2026", &strict)); + for word in ["école", "l'arbre", "xqzv", "SNCF", ""] { + assert!(check(&AffixDict::default(), word, &strict)); + } + } +} diff --git a/crates/proof/src/fr/suggest.rs b/crates/proof/src/fr/suggest.rs new file mode 100644 index 000000000..86477d33f --- /dev/null +++ b/crates/proof/src/fr/suggest.rs @@ -0,0 +1,81 @@ +//! French tuning of the shared, bounded affix suggestion engine. + +use crate::affix::AffixDict; +use crate::affix_suggest::{Split, Tuning}; + +/// Short words often run into the next one (`et la`, `de Paris`, `pour moi`). +const LEADING_WORDS: &[&str] = &[ + "à", "a", "au", "aux", "de", "du", "des", "le", "la", "les", "un", "une", "et", "ou", "où", "en", "y", "ce", "se", "ne", "je", "tu", "il", "on", + "nous", "vous", "ils", "elle", "par", "pour", "sur", "sous", "dans", "avec", "sans", "chez", "vers", "entre", "très", "plus", "moins", "bien", + "pas", "que", "qui", "mais", "donc", "car", "si", "son", "sa", "ses", "mon", "ma", "mes", "ton", "ta", "tes", "est", "tout", "tous", "toute", + "comme", "quand", "puis", "encore", "déjà", "jamais", "toujours", +]; +/// Short words often run into the one before (`dis-moi` without the hyphen, `là-bas`, or a +/// dropped space: `pourmoi` → `pour moi`). +const TRAILING_WORDS: &[&str] = + &["moi", "toi", "lui", "elle", "nous", "vous", "eux", "le", "la", "les", "en", "y", "là", "ci", "il", "on", "ils", "elles", "est", "et"]; + +const TUNING: Tuning = Tuning { + split: Split::Near { leading: LEADING_WORDS, trailing: TRAILING_WORDS }, + alphabet: "esaitnrulodcpmévqfbghjàxèêyçôîâûùœ", + ..Tuning::DEFAULT +}; + +/// French suggestions from a supplied dictionary; keeps the writer's apostrophe and case. +/// Dictionary OCONV remains active for every other output conversion. +pub fn suggest_in(d: &AffixDict, word: &str, max: usize) -> Vec { + let word = crate::composed(word); + let curly = word.contains('’'); + let apostrophe = if curly { '’' } else { '\'' }; + let mut out = Vec::new(); + for text in crate::affix_suggest::suggest_in(d, &word, max, &TUNING) { + let styled: String = text.chars().map(|c| if c == '\'' || c == '’' { apostrophe } else { c }).collect(); + // A pack may spell only one apostrophe and have no ICONV. Keep its valid output + // rather than turn it back into the spelling mistake the caller is correcting. + let text = if styled.split(' ').all(|p| d.can_suggest_cased(p, p)) { styled } else { text }; + if text != word && !out.contains(&text) { + out.push(text); + } + } + out +} + +#[cfg(test)] +#[allow(clippy::unwrap_used)] +mod tests { + use super::*; + + #[test] + fn french_accents_confusions_splits_and_elisions() { + let d = super::super::test_dict::dictionary(); + for (typo, expected) in [ + ("ecole", "école"), + ("riviere", "rivière"), + ("soeur", "sœur"), + ("maisonn", "maison"), + ("pourmoi", "pour moi"), + ("l'arbrre", "l'arbre"), + ("l’arbrre", "l’arbre"), + ] { + let got = suggest_in(&d, typo, 8); + assert!(got.iter().any(|s| s == expected), "{typo}: {got:?}"); + } + assert!(suggest_in(&d, "e\u{301}cole", 4).iter().all(|s| s != "école")); + assert!(suggest_in(&d, "ecole", 0).is_empty()); + assert!(suggest_in(&d, &"a".repeat(41), 4).is_empty()); + } + + #[test] + fn curly_dictionary_without_iconv_remains_suggestible() { + let d = AffixDict::from_hunspell("SET UTF-8\n", "1\naujourd’hui\n", &[]).unwrap(); + assert!(suggest_in(&d, "aujourd’huui", 4).iter().any(|s| s == "aujourd’hui")); + assert!(suggest_in(&d, "aujourd'hui", 4).iter().any(|s| s == "aujourd’hui")); + } + + #[test] + fn output_conversion_preserves_typed_apostrophe() { + let d = AffixDict::from_hunspell("SET UTF-8\nICONV 1\nICONV ’ '\nOCONV 1\nOCONV ' ’\n", "1\nl'arbre\n", &[]).unwrap(); + assert!(suggest_in(&d, "l'arbrre", 4).iter().any(|s| s == "l'arbre")); + assert!(suggest_in(&d, "l’arbrre", 4).iter().any(|s| s == "l’arbre")); + } +} diff --git a/crates/proof/src/fr/test_dict.rs b/crates/proof/src/fr/test_dict.rs new file mode 100644 index 000000000..23637254c --- /dev/null +++ b/crates/proof/src/fr/test_dict.rs @@ -0,0 +1,234 @@ +//! A tiny synthetic French Hunspell dictionary for tests (written for these tests; not taken +//! from any real dictionary). Real dictionaries are installed on the system, never bundled. +//! +//! It exercises what the Dicollecte French dictionary uses: two-character flags (`FLAG long`), +//! stems that need an affix (`NEEDAFFIX`, with an empty suffix for the singular), elisions as +//! prefixes licensed by a suffix's continuation (`l'arbre` but not `l'arbres`), irregular verbs +//! through `FULLSTRIP` (`être` → `suis`), `KEEPCASE` (`km`), `NOSUGGEST` (`bah`), `ICONV` (`’` +//! read as `'`) and the +//! suggestion tables (`TRY`, `MAP` for accents, `REP` for common confusions). + +pub const AFF: &str = "SET UTF-8 +FLAG long +NEEDAFFIX () +KEEPCASE || +NOSUGGEST -- +FULLSTRIP +ICONV 1 +ICONV ’ ' +TRY esaitnrulodcpmévqfbghjàxèêyçôîâûùœ +MAP 6 +MAP aàâä +MAP eéèêë +MAP iîï +MAP oôö +MAP uùûü +MAP cç +REP 3 +REP oe œ +REP ph f +REP f ph +PFX L' Y 1 +PFX L' 0 l' [aàâeéèêiîoôuœh] +PFX D' Y 1 +PFX D' 0 d' [aàâeéèêiîoôuœh] +PFX Q' Y 1 +PFX Q' 0 qu' [aàâeéèêiîoôuœh] +PFX J' Y 1 +PFX J' 0 j' [aàâeéèêiîoôuœhy] +SFX S. Y 2 +SFX S. 0 0/L'D'Q' [^sxz] +SFX S. 0 s/D'Q' [^sxz] +SFX S= Y 2 +SFX S= 0 0 [^sxz] +SFX S= 0 s [^sxz] +SFX F. Y 4 +SFX F. 0 0/L'D'Q' . +SFX F. 0 e/L'D'Q' . +SFX F. 0 s/D'Q' . +SFX F. 0 es/D'Q' . +SFX Er Y 6 +SFX Er er er/D' er +SFX Er er e/J' er +SFX Er er es er +SFX Er er ons er +SFX Er er ez er +SFX Er er ent er +SFX Et N 7 +SFX Et être être être +SFX Et être suis être +SFX Et être es être +SFX Et être est être +SFX Et être sommes être +SFX Et être êtes être +SFX Et être sont être +SFX Av N 7 +SFX Av avoir avoir/D' avoir +SFX Av avoir ai/J' avoir +SFX Av avoir as avoir +SFX Av avoir a avoir +SFX Av avoir avons avoir +SFX Av avoir avez avoir +SFX Av avoir ont/Q' avoir +"; + +/// Stems (the count line first, as in Hunspell files). +pub const DIC: &str = "150 +maison/S.() +arbre/S.() +enfant/S.() +ami/S.() +amie/S.() +homme/S.() +école/S.() +café/S.() +chat/S.() +rivière/S.() +ville/S.() +heure/S.() +histoire/S.() +sœur/S.() +œuvre/S.() +photo/S.() +téléphone/S.() +année/S.() +vie/S.() +livre/S.() +table/S.() +porte/S.() +femme/S.() +garçon/S.() +fille/S.() +père/S.() +mère/S.() +langue/S.() +mot/S.() +texte/S.() +phrase/S.() +exemple/S.() +jour/S.() +nuit/S.() +monde/S.() +hasard/S=() +haricot/S=() +grand/F.() +petit/F.() +noir/F.() +aimer/Er() +parler/Er() +chanter/Er() +arriver/Er() +être/Et() +avoir/Av() +il/Q' +ils/Q' +elle/Q' +elles/Q' +on/Q'L' +un/D'Q'L' +une/D'Q'L' +en/Q'J' +y/J' +à/Q' +jusqu'à +aujourd'hui/D' +peut-être +arc-en-ciel +km/|| +bah/-- +Paris +France +Montréal +le +la +les +de +des +du +et +à +je +tu +nous +vous +que +qui +ne +pas +se +me +te +ce +ça +avec +pour +dans +sur +sous +très +près +beaucoup +si +oui +non +mais +ou +où +dit +demanda +quand +comme +plus +bien +tout +toujours +jamais +ici +là +alors +donc +aussi +encore +déjà +mon +ma +mes +son +sa +ses +notre +votre +leur +cette +ces +au +aux +par +entre +vers +chez +sans +moi +toi +lui +rien +chose +temps +fois +eau +voici +voilà +bonjour +merci +beau +belle +la +etc +M +p +"; + +/// The original synthetic fixture, parsed independently of the installed pack cache. +pub fn dictionary() -> crate::affix::AffixDict { + crate::affix::AffixDict::from_hunspell(AFF, DIC, &[]).unwrap() +} diff --git a/crates/proof/src/hunspell.rs b/crates/proof/src/hunspell.rs index 966ded72f..948d0e25b 100644 --- a/crates/proof/src/hunspell.rs +++ b/crates/proof/src/hunspell.rs @@ -754,9 +754,13 @@ mod tests { /// spec's default `~/.local/share` applies, and with no home there is no folder. #[test] fn xdg_data_home_follows_the_spec() { - let home = Path::new("/home/a"); - assert_eq!(xdg_data_home(Some("/data".into()), Some(home)), Some(PathBuf::from("/data"))); - assert_eq!(xdg_data_home(Some("/data".into()), None), Some(PathBuf::from("/data"))); + // On Windows a rooted path without a drive is not absolute. Keep the same + // absolute/relative contract on each platform instead of changing the loader. + let (home, data) = if cfg!(windows) { (r"C:\Users\a", r"C:\data") } else { ("/home/a", "/data") }; + let (home, data) = (Path::new(home), Path::new(data)); + assert!(data.is_absolute()); + assert_eq!(xdg_data_home(Some(data.as_os_str().into()), Some(home)), Some(data.to_path_buf())); + assert_eq!(xdg_data_home(Some(data.as_os_str().into()), None), Some(data.to_path_buf())); for xdg in [None, Some(""), Some("relative/data")] { assert_eq!(xdg_data_home(xdg.map(Into::into), Some(home)), Some(home.join(".local/share")), "{xdg:?}"); assert_eq!(xdg_data_home(xdg.map(Into::into), None), None, "{xdg:?}"); @@ -1010,7 +1014,12 @@ mod tests { assert!(load(&aff, &big).unwrap_err().contains("too large")); // A directory, and on Unix an endless device, are not dictionary files. (No clock: a // reader that read `/dev/zero` would never return, so the error itself is the proof.) - assert!(load(&aff, &dir).unwrap_err().contains("not a regular file")); + // Windows rejects directories in File::open, before the regular-file guard. The + // rejection is required everywhere; its diagnostic is platform-dependent. + let directory_error = load(&aff, &dir).unwrap_err(); + assert!(directory_error.contains(&dir.display().to_string()), "{directory_error}"); + #[cfg(unix)] + assert!(directory_error.contains("not a regular file"), "{directory_error}"); #[cfg(unix)] assert!(load(&aff, Path::new("/dev/zero")).unwrap_err().contains("not a regular file")); // Turkish reads through the same reader. diff --git a/crates/proof/src/lib.rs b/crates/proof/src/lib.rs index 3df6cd017..f0f33d007 100644 --- a/crates/proof/src/lib.rs +++ b/crates/proof/src/lib.rs @@ -42,6 +42,9 @@ //! existing English fallback. //! - **German** ([`ProofLang::De`]): hyphenation by `hyph-utf8`'s German patterns (reformed //! spelling, MIT); no spelling or grammar marks yet. +//! - **French** (a [`ProofLang::Pack`] locale; module [`fr`]): the pack dictionary with French +//! elisions and accent-oriented suggestions, plus conservative typography and basic checks. +//! France and Canada retain their regional tags; Quebec uses its own punctuation spacing. //! - **Any other language** ([`ProofLang::Pack`], module [`packs`]): spelling and suggestions //! from its Hunspell dictionary (an installed Language pack, the dictionaries folder or the //! system's) with default tuning, hyphenation from its pack, no grammar rules; without a @@ -73,6 +76,7 @@ pub mod dict; pub mod en_variants; mod english; pub mod es; +pub mod fr; pub mod hr; pub mod hunspell; pub mod hyphen; @@ -976,6 +980,7 @@ fn grammar_in(text: &str, lang: ProofLang, capital_first: bool) -> Vec { match lang { ProofLang::En => grammar_en(text, capital_first), ProofLang::EnGb | ProofLang::EnAu | ProofLang::EnCa => grammar_en(text, capital_first).into_iter().map(|i| Issue { lang, ..i }).collect(), + ProofLang::Pack(locale) if locale.primary() == "fr" => fr::grammar::check_in(text, lang), // `pt-pt` shares Portuguese's rules, its issues in its own language. _ => language(lang.built_in()) .map_or_else(Vec::new, |l| (l.grammar)(text, lang, capital_first).into_iter().map(|i| Issue { lang, ..i }).collect()), diff --git a/crates/proof/src/pack_lang.rs b/crates/proof/src/pack_lang.rs index 7b4d19315..8b6cea902 100644 --- a/crates/proof/src/pack_lang.rs +++ b/crates/proof/src/pack_lang.rs @@ -1,6 +1,7 @@ //! Proofing for any language by its locale ([`crate::ProofLang::Pack`]): its Hunspell dictionary (the //! dictionaries folder, then an installed Language pack, then the system's), read by the shared -//! affix engine, with default suggestion tuning and no grammar rules. +//! affix engine. Most use default suggestion tuning and no grammar rules; French locales add +//! the spelling tuning and conservative typography in [`crate::fr`] without a separate cache. //! //! The loaded dictionaries share a memory budget ([`MAX_LOADED_BYTES`], estimated from their //! files); the one used least recently goes first, but never one used during the current @@ -320,6 +321,9 @@ pub(crate) fn is_correct(word: &str, locale: PackLocale, opts: &crate::Options) if other_script(w, &scripts) { return true; } + if locale.primary() == "fr" { + return crate::fr::check(&d, w, opts); + } let known = |w: &str| d.check(w) || crate::in_user_dictionary(&w.to_lowercase()); if w.contains('-') && !known(w) { return w.split('-').all(|p| p.chars().count() <= 1 || known(p)); @@ -333,7 +337,7 @@ pub(crate) fn suggest(word: &str, max: usize, locale: PackLocale) -> Vec if d.is_empty() { return Vec::new(); } - crate::affix_suggest::suggest_in(&d, word, max, &Tuning::DEFAULT) + if locale.primary() == "fr" { crate::fr::suggest_in(&d, word, max) } else { crate::affix_suggest::suggest_in(&d, word, max, &Tuning::DEFAULT) } } /// The pack locales whose hyphenation patterns serve a [`crate::ProofLang::Pack`] language: the locale, diff --git a/crates/proof/tests/affix_compatibility.rs b/crates/proof/tests/affix_compatibility.rs new file mode 100644 index 000000000..6d09e5f90 --- /dev/null +++ b/crates/proof/tests/affix_compatibility.rs @@ -0,0 +1,92 @@ +//! Frozen public output from the pre-French shared affix engine at upstream +//! e6c5a701ddff5be16e266028168c70658aae39d9, using original synthetic fixtures. +//! Do not regenerate expectations from the new implementation: they establish the baseline. +//! Legacy WCAFF1 bytes remain frozen, but are explicitly refused by the WCAFF2 engine. + +use craft_proof::affix::{AffixDict, capitalize}; +use std::fmt::Write; + +#[path = "fixtures/affix_compatibility_cases.rs"] +mod fixtures; + +fn snapshot(case: &fixtures::Case, dict: &AffixDict) -> String { + let mut out = format!("{}\nlen={} rules={}\n", case.name, dict.len(), dict.rule_count()); + writeln!(out, "try={:?} key={:?} map={:?} rep={:?} comments={:?}", dict.try_chars(), dict.key(), dict.map(), dict.rep(), dict.comments()) + .unwrap(); + let mut stems: Vec<_> = dict.stems().collect(); + stems.sort_unstable(); + for stem in &stems { + let mut forms = dict.forms(stem); + forms.sort_unstable(); + forms.dedup(); + writeln!(out, "forms {stem:?}: {forms:?}").unwrap(); + } + let mut probes: Vec = case.probes.iter().map(|word| (*word).to_string()).collect(); + for stem in stems { + probes.extend(dict.forms(stem)); + } + let originals = probes.clone(); + for word in originals { + probes.extend([word.to_uppercase(), word.to_lowercase(), capitalize(&word)]); + } + probes.sort_unstable(); + probes.dedup(); + for word in probes { + writeln!( + out, + "{word:?}: contains={} check={} suggest={} raw_suggest={}", + dict.contains(&word), + dict.check(&word), + dict.can_suggest(&word), + dict.contains_suggestible(&word) + ) + .unwrap(); + } + out +} + +#[test] +fn non_french_affix_outputs_match_pre_french_baseline() { + let expected = include_str!("fixtures/affix_compatibility.expected"); + let mut actual = String::new(); + for case in fixtures::cases() { + let dict = AffixDict::from_hunspell(&case.aff, &case.dic, &["original compatibility fixture"]).unwrap(); + let result = snapshot(&case, &dict); + let restored = AffixDict::from_bytes(&dict.to_bytes().unwrap()).unwrap(); + assert_eq!(snapshot(&case, &restored), result, "current compact round trip: {}", case.name); + actual.push_str(&result); + } + // craft-libs 55332dd predates this adaptation and supports a prefix plus a two-suffix + // chain (native test affix::tests::a_prefix_with_a_suffix_chain). The old Indonesian + // fixture's bermain + kan + lah therefore became a word, in these three cases only. + // Keep the frozen historical file untouched and assert every explicit transition once. + let mut expected = expected.to_string(); + let mut transitions = 0; + for word in ["BERMAINKANLAH", "Bermainkanlah", "bermainkanlah"] { + let before = format!("{word:?}: contains=false check=false suggest=false raw_suggest=false\n"); + let after = if word == "bermainkanlah" { + format!("{word:?}: contains=true check=true suggest=true raw_suggest=true\n") + } else { + format!("{word:?}: contains=false check=true suggest=true raw_suggest=false\n") + }; + assert_eq!(expected.matches(&before).count(), 1, "one historical observable: {word}"); + expected = expected.replacen(&before, &after, 1); + transitions += 1; + } + assert_eq!(transitions, 3, "the documented upstream exception has exactly three observables"); + assert_eq!(actual, expected, "shared engine output changed beyond the explicit upstream chain exception"); +} + +#[test] +fn legacy_compact_data_is_refused_without_reinterpreting_homonyms() { + let encoded = include_str!("fixtures/affix_compatibility.compact"); + let cases = fixtures::cases(); + let lines: Vec<_> = encoded.lines().collect(); + assert_eq!(lines.len(), cases.len()); + for (case, hex) in cases.iter().zip(lines) { + assert_eq!(hex.len() % 2, 0); + let bytes: Vec<_> = + hex.as_bytes().as_chunks::<2>().0.iter().map(|pair| u8::from_str_radix(std::str::from_utf8(pair).unwrap(), 16).unwrap()).collect(); + assert!(AffixDict::from_bytes(&bytes).is_err(), "WCAFF1 must be regenerated as WCAFF2: {}", case.name); + } +} diff --git a/crates/proof/tests/fixtures/affix_compatibility.compact b/crates/proof/tests/fixtures/affix_compatibility.compact new file mode 100644 index 000000000..5c8c627de --- /dev/null +++ b/crates/proof/tests/fixtures/affix_compatibility.compact @@ -0,0 +1,7 @@ +4d8bc10a825014446b7bbf62a07dd62744e5ae120b2ca2e02aafb8bceac54b295d067e91db76ea7f2516d16666ce30138c47ae3ba41e8c95a35cf884c89caf1c4b282789531ce4112756d1cadf809591a47e6a4bb39107aef2d64d5924e44f3dd42fd8ac4d09ca823c778d101b0c7011853e2d1be696536cf7e9ee57280dcd8dfe2dd4f97b88306faa2a0753b0f0274bea046c6f19dfd989a8a34dec70485d6b3e7c157553da617a03 +1d8c410e82301045bb9e534ce2deea11a8d8c48d10304196058b990418534aa25ec7852770e9aa17b3b27c79ffbf6a9768bd8515b2a32b8da6c796879bf1d4504ffe811dddfdec2c9c8a1a8d259ec33bbcc2077456a8439aee8f5556a418be90eb33e658e3069dc535941193888c462ae485d5a2a768ffa71244c32379968902d19a290e4174e6699dcc41d0308f17962aa67f +1dc7410ac2301005d0ace7141fdc1b3d42aa64a9a15d5497d392ca40eac818416f6fe8eaf1c65388f1483ba8c9439e5c30ebfae22a9314a93f2cf2ad1fcb94e20d09771c60823d0dada15521d06d1d2e6064308dd7fe3c90eb75657233bfd97789dcc2967db3c864ea03fd01 +1d8a3d0a02311406b77ea7f8c0dee8114437651453ac220a51a33cc88fc408e62c9e451bf55e1bb6199861baf94cca298d10135f39188753f43793f9c88e73c1859ff9912cade4060a5b4c102cc6a4abea410b7687b21f425b0f83df0b86bae57aa1a9f1ce9cbf6fa1a8b9e714bd50b51551f1ffd860444b3d +1d8c310e82401444b1dd53fcc45ef408282cb11008ab414b346a3641310413ed0cad95072034f450488c46f10a7f6fe4aeddcc9bcc0b4606a503d28538e15bbe0f2358c5bb4398f2258f787a860d3fa5c7644d268607d8881ba1ae3f1c9ba6e504ae6f0296c471d9ccb62d3605cc8947e780052ca00ff8c1067a842952fd89b8caae6e8c6878c716df3a56a4f3c01abfe222ed998ea5222f6c552e64d64426e7a794d53ae612fc00 +2dc84b0e8230100050d6738a49dc8b1e0114589800a11864398522c3a768a951120f2f212edf2b4e5e181e618793e13b6b1ab09ac60759963cb05db0e18f7d1905795622c9aa56dc6bb804253edfcad8e54b73dd4016a45877d8419c886b140522c718d2f08629967840a90cee41acf636f7a45dff3ffe3603b5ab8b243b0b702455e47ae08cc4daf552700cb534f37a31fc00 +35c7b98e82600045e1a9790a92e967dc97d20df71515b51345455114c1ed6d2616c6c2cad8d8fe2f36e67269cec9a7e5328a1296be65db31e7e6666cc9137bbd1dbba66e5aa67b9667e6c9f51c435295813c961b72e8d31f4887746a024da82934a50cc8a066d08c9a43736a012d281332a925b4a456d08ab2208b5a436b6a036d281bb2a92db4a576d08e722087da437bca855cca833cea001da82374a44ed0893a4367ea025da80c94a1b25096ca41392a0fe5a90254a01448a18a50912a4125aa0c95a90a54a1aa5095aa4135aa0ed5a906d4a09a50936a412daa0db5a90ed4a15448a5ba5097ea413daa0ff5290dd2a80134a086d0901a41232a0485a83014a62250848a42512a06c5a83814a71250824a42492a05a5a83494a6c41ff8197df77d0ffcf0fd08fcf4fd0cfcf6fd0e7cf37d0b7cf57d0dfcf2fdfa586b76f2aaf4657bae63ff8a97f475301cddfe0d8523d1583c914ca533d95cbea0144be54ab5566f345bed8edaedf5b5c17034d6275363365f98cb95b5ded8db9db377bdc3f174be883f71153771170ff1142ff196fe01 diff --git a/crates/proof/tests/fixtures/affix_compatibility.expected b/crates/proof/tests/fixtures/affix_compatibility.expected new file mode 100644 index 000000000..8fe3a9929 --- /dev/null +++ b/crates/proof/tests/fixtures/affix_compatibility.expected @@ -0,0 +1,497 @@ +pl: conditional strip, prefix cross products, diacritics +len=4 rules=5 +try="aeoiułkr" key="" map=[['a', 'ą'], ['o', 'ó', 'u']] rep=[("ż", "rz"), ("u", "ó")] comments=["original compatibility fixture"] +forms "Warszawa": ["Warszawa", "Warszawą"] +forms "kot": ["kot", "kotem", "koty", "niekot", "niekotem", "niekoty"] +forms "krowa": ["krowa", "krową"] +forms "piesek": ["piesek", "piesekem", "pieseky", "pieska"] +"": contains=false check=false suggest=false raw_suggest=false +"KOT": contains=false check=true suggest=true raw_suggest=false +"KOTEM": contains=false check=true suggest=true raw_suggest=false +"KOTY": contains=false check=true suggest=true raw_suggest=false +"KOTĄ": contains=false check=false suggest=false raw_suggest=false +"KROWA": contains=false check=true suggest=true raw_suggest=false +"KROWY": contains=false check=false suggest=false raw_suggest=false +"KROWĄ": contains=false check=true suggest=true raw_suggest=false +"Kot": contains=false check=true suggest=true raw_suggest=false +"Kotem": contains=false check=true suggest=true raw_suggest=false +"Koty": contains=false check=true suggest=true raw_suggest=false +"Kotą": contains=false check=false suggest=false raw_suggest=false +"Krowa": contains=false check=true suggest=true raw_suggest=false +"Krowy": contains=false check=false suggest=false raw_suggest=false +"Krową": contains=false check=true suggest=true raw_suggest=false +"NIE": contains=false check=false suggest=false raw_suggest=false +"NIEKOT": contains=false check=true suggest=true raw_suggest=false +"NIEKOTEM": contains=false check=true suggest=true raw_suggest=false +"NIEKOTY": contains=false check=true suggest=true raw_suggest=false +"NIEPIESKA": contains=false check=false suggest=false raw_suggest=false +"Nie": contains=false check=false suggest=false raw_suggest=false +"Niekot": contains=false check=true suggest=true raw_suggest=false +"Niekotem": contains=false check=true suggest=true raw_suggest=false +"Niekoty": contains=false check=true suggest=true raw_suggest=false +"Niepieska": contains=false check=false suggest=false raw_suggest=false +"PIESEK": contains=false check=true suggest=true raw_suggest=false +"PIESEKA": contains=false check=false suggest=false raw_suggest=false +"PIESEKEM": contains=false check=true suggest=true raw_suggest=false +"PIESEKY": contains=false check=true suggest=true raw_suggest=false +"PIESKA": contains=false check=true suggest=true raw_suggest=false +"Piesek": contains=false check=true suggest=true raw_suggest=false +"Pieseka": contains=false check=false suggest=false raw_suggest=false +"Piesekem": contains=false check=true suggest=true raw_suggest=false +"Pieseky": contains=false check=true suggest=true raw_suggest=false +"Pieska": contains=false check=true suggest=true raw_suggest=false +"WARSZAWA": contains=false check=true suggest=true raw_suggest=false +"WARSZAWĄ": contains=false check=true suggest=true raw_suggest=false +"Warszawa": contains=true check=true suggest=true raw_suggest=true +"Warszawą": contains=true check=true suggest=true raw_suggest=true +"kot": contains=true check=true suggest=true raw_suggest=true +"kotem": contains=true check=true suggest=true raw_suggest=true +"koty": contains=true check=true suggest=true raw_suggest=true +"kotą": contains=false check=false suggest=false raw_suggest=false +"krowa": contains=true check=true suggest=true raw_suggest=true +"krowy": contains=false check=false suggest=false raw_suggest=false +"krową": contains=true check=true suggest=true raw_suggest=true +"nie": contains=false check=false suggest=false raw_suggest=false +"niekot": contains=true check=true suggest=true raw_suggest=true +"niekotem": contains=true check=true suggest=true raw_suggest=true +"niekoty": contains=true check=true suggest=true raw_suggest=true +"niepieska": contains=false check=false suggest=false raw_suggest=false +"piesek": contains=true check=true suggest=true raw_suggest=true +"pieseka": contains=false check=false suggest=false raw_suggest=false +"piesekem": contains=true check=true suggest=true raw_suggest=true +"pieseky": contains=true check=true suggest=true raw_suggest=true +"pieska": contains=true check=true suggest=true raw_suggest=true +"warszawa": contains=false check=false suggest=false raw_suggest=false +"warszawą": contains=false check=false suggest=false raw_suggest=false +pt: UTF-8 flags, forbidden words, two suffixes +len=4 rules=3 +try="aeiouçãõ" key="" map=[] rep=[] comments=["original compatibility fixture"] +forms "bonito": ["bonita", "bonitas", "bonito", "bonitos"] +forms "casa": ["casa", "casas"] +forms "fazer": ["fazer", "refazer"] +forms "imundo": [] +"BONITA": contains=false check=true suggest=true raw_suggest=false +"BONITAS": contains=false check=true suggest=true raw_suggest=false +"BONITASS": contains=false check=false suggest=false raw_suggest=false +"BONITO": contains=false check=true suggest=true raw_suggest=false +"BONITOS": contains=false check=true suggest=true raw_suggest=false +"Bonita": contains=false check=true suggest=true raw_suggest=false +"Bonitas": contains=false check=true suggest=true raw_suggest=false +"Bonitass": contains=false check=false suggest=false raw_suggest=false +"Bonito": contains=false check=true suggest=true raw_suggest=false +"Bonitos": contains=false check=true suggest=true raw_suggest=false +"CASA": contains=false check=true suggest=true raw_suggest=false +"CASAA": contains=false check=false suggest=false raw_suggest=false +"CASAS": contains=false check=true suggest=true raw_suggest=false +"Casa": contains=false check=true suggest=true raw_suggest=false +"Casaa": contains=false check=false suggest=false raw_suggest=false +"Casas": contains=false check=true suggest=true raw_suggest=false +"FAZER": contains=false check=true suggest=true raw_suggest=false +"Fazer": contains=false check=true suggest=true raw_suggest=false +"IMUNDO": contains=false check=false suggest=false raw_suggest=false +"IMUNDOS": contains=false check=false suggest=false raw_suggest=false +"Imundo": contains=false check=false suggest=false raw_suggest=false +"Imundos": contains=false check=false suggest=false raw_suggest=false +"RECASAS": contains=false check=false suggest=false raw_suggest=false +"REFAZER": contains=false check=true suggest=true raw_suggest=false +"Recasas": contains=false check=false suggest=false raw_suggest=false +"Refazer": contains=false check=true suggest=true raw_suggest=false +"bonita": contains=true check=true suggest=true raw_suggest=true +"bonitas": contains=true check=true suggest=true raw_suggest=true +"bonitass": contains=false check=false suggest=false raw_suggest=false +"bonito": contains=true check=true suggest=true raw_suggest=true +"bonitos": contains=true check=true suggest=true raw_suggest=true +"casa": contains=true check=true suggest=true raw_suggest=true +"casaa": contains=false check=false suggest=false raw_suggest=false +"casas": contains=true check=true suggest=true raw_suggest=true +"fazer": contains=true check=true suggest=true raw_suggest=true +"imundo": contains=false check=false suggest=false raw_suggest=false +"imundos": contains=false check=false suggest=false raw_suggest=false +"recasas": contains=false check=false suggest=false raw_suggest=false +"refazer": contains=true check=true suggest=true raw_suggest=true +it: stripping, non-crossing suffix, proper-name casing +len=4 rules=3 +try="" key="" map=[] rep=[] comments=["original compatibility fixture"] +forms "Roma": ["Roma"] +forms "casa": ["casa", "case", "ricasa"] +forms "fare": ["fare", "rifare"] +forms "libro": ["libri", "libro"] +"": contains=false check=false suggest=false raw_suggest=false +"CASA": contains=false check=true suggest=true raw_suggest=false +"CASE": contains=false check=true suggest=true raw_suggest=false +"Casa": contains=false check=true suggest=true raw_suggest=false +"Case": contains=false check=true suggest=true raw_suggest=false +"FARE": contains=false check=true suggest=true raw_suggest=false +"Fare": contains=false check=true suggest=true raw_suggest=false +"LIBRI": contains=false check=true suggest=true raw_suggest=false +"LIBRO": contains=false check=true suggest=true raw_suggest=false +"LIBROS": contains=false check=false suggest=false raw_suggest=false +"Libri": contains=false check=true suggest=true raw_suggest=false +"Libro": contains=false check=true suggest=true raw_suggest=false +"Libros": contains=false check=false suggest=false raw_suggest=false +"R ILIBRI": contains=false check=false suggest=false raw_suggest=false +"R ilibri": contains=false check=false suggest=false raw_suggest=false +"RICAS A": contains=false check=false suggest=false raw_suggest=false +"RICASA": contains=false check=true suggest=true raw_suggest=false +"RICASE": contains=false check=false suggest=false raw_suggest=false +"RIFARE": contains=false check=true suggest=true raw_suggest=false +"ROMA": contains=false check=true suggest=true raw_suggest=false +"Ricas a": contains=false check=false suggest=false raw_suggest=false +"Ricasa": contains=false check=true suggest=true raw_suggest=false +"Ricase": contains=false check=false suggest=false raw_suggest=false +"Rifare": contains=false check=true suggest=true raw_suggest=false +"Roma": contains=true check=true suggest=true raw_suggest=true +"casa": contains=true check=true suggest=true raw_suggest=true +"case": contains=true check=true suggest=true raw_suggest=true +"fare": contains=true check=true suggest=true raw_suggest=true +"libri": contains=true check=true suggest=true raw_suggest=true +"libro": contains=true check=true suggest=true raw_suggest=true +"libros": contains=false check=false suggest=false raw_suggest=false +"r ilibri": contains=false check=false suggest=false raw_suggest=false +"ricas a": contains=false check=false suggest=false raw_suggest=false +"ricasa": contains=true check=true suggest=true raw_suggest=true +"ricase": contains=false check=false suggest=false raw_suggest=false +"rifare": contains=true check=true suggest=true raw_suggest=true +"roma": contains=false check=false suggest=false raw_suggest=false +cs: negated conditions and shared Unicode stems +len=4 rules=3 +try="" key="" map=[] rep=[] comments=["original compatibility fixture"] +forms "mladý": ["mladý", "nemladý"] +forms "strom": ["nestrom", "nestromy", "strom", "stromy"] +forms "y": ["y"] +forms "žena": ["žena", "ženě"] +"MLADÝ": contains=false check=true suggest=true raw_suggest=false +"MLADÝY": contains=false check=false suggest=false raw_suggest=false +"Mladý": contains=false check=true suggest=true raw_suggest=false +"Mladýy": contains=false check=false suggest=false raw_suggest=false +"NEMLADÝ": contains=false check=true suggest=true raw_suggest=false +"NESTROM": contains=false check=true suggest=true raw_suggest=false +"NESTROMY": contains=false check=true suggest=true raw_suggest=false +"NEŽENĚ": contains=false check=false suggest=false raw_suggest=false +"Nemladý": contains=false check=true suggest=true raw_suggest=false +"Nestrom": contains=false check=true suggest=true raw_suggest=false +"Nestromy": contains=false check=true suggest=true raw_suggest=false +"Neženě": contains=false check=false suggest=false raw_suggest=false +"STROM": contains=false check=true suggest=true raw_suggest=false +"STROMY": contains=false check=true suggest=true raw_suggest=false +"Strom": contains=false check=true suggest=true raw_suggest=false +"Stromy": contains=false check=true suggest=true raw_suggest=false +"Y": contains=false check=true suggest=true raw_suggest=false +"YY": contains=false check=false suggest=false raw_suggest=false +"Yy": contains=false check=false suggest=false raw_suggest=false +"mladý": contains=true check=true suggest=true raw_suggest=true +"mladýy": contains=false check=false suggest=false raw_suggest=false +"nemladý": contains=true check=true suggest=true raw_suggest=true +"nestrom": contains=true check=true suggest=true raw_suggest=true +"nestromy": contains=true check=true suggest=true raw_suggest=true +"neženě": contains=false check=false suggest=false raw_suggest=false +"strom": contains=true check=true suggest=true raw_suggest=true +"stromy": contains=true check=true suggest=true raw_suggest=true +"y": contains=true check=true suggest=true raw_suggest=true +"yy": contains=false check=false suggest=false raw_suggest=false +"ŽENA": contains=false check=true suggest=true raw_suggest=false +"ŽENY": contains=false check=false suggest=false raw_suggest=false +"ŽENĚ": contains=false check=true suggest=true raw_suggest=false +"Žena": contains=false check=true suggest=true raw_suggest=false +"Ženy": contains=false check=false suggest=false raw_suggest=false +"Ženě": contains=false check=true suggest=true raw_suggest=false +"žena": contains=true check=true suggest=true raw_suggest=true +"ženy": contains=false check=false suggest=false raw_suggest=false +"ženě": contains=true check=true suggest=true raw_suggest=true +ru: Cyrillic flags and suggestions exclusion +len=4 rules=2 +try="" key="" map=[['е', 'ё']] rep=[] comments=["original compatibility fixture"] +forms "дом": ["дом", "домы"] +forms "запрет": [] +forms "кот": ["кот", "коты", "некот", "некоты"] +forms "тайна": ["тайна", "тайнаы"] +"ДОМ": contains=false check=true suggest=true raw_suggest=false +"ДОМЫ": contains=false check=true suggest=true raw_suggest=false +"Дом": contains=false check=true suggest=true raw_suggest=false +"Домы": contains=false check=true suggest=true raw_suggest=false +"ЗАПРЕТ": contains=false check=false suggest=false raw_suggest=false +"ЗАПРЕТЫ": contains=false check=false suggest=false raw_suggest=false +"Запрет": contains=false check=false suggest=false raw_suggest=false +"Запреты": contains=false check=false suggest=false raw_suggest=false +"КОТ": contains=false check=true suggest=true raw_suggest=false +"КОТЫ": contains=false check=true suggest=true raw_suggest=false +"КОт": contains=false check=false suggest=false raw_suggest=false +"Кот": contains=false check=true suggest=true raw_suggest=false +"Коты": contains=false check=true suggest=true raw_suggest=false +"НЕДОМЫ": contains=false check=false suggest=false raw_suggest=false +"НЕКОТ": contains=false check=true suggest=true raw_suggest=false +"НЕКОТЫ": contains=false check=true suggest=true raw_suggest=false +"Недомы": contains=false check=false suggest=false raw_suggest=false +"Некот": contains=false check=true suggest=true raw_suggest=false +"Некоты": contains=false check=true suggest=true raw_suggest=false +"ТАЙНА": contains=false check=true suggest=false raw_suggest=false +"ТАЙНАЫ": contains=false check=true suggest=false raw_suggest=false +"Тайна": contains=false check=true suggest=false raw_suggest=false +"Тайнаы": contains=false check=true suggest=false raw_suggest=false +"дом": contains=true check=true suggest=true raw_suggest=true +"домы": contains=true check=true suggest=true raw_suggest=true +"запрет": contains=false check=false suggest=false raw_suggest=false +"запреты": contains=false check=false suggest=false raw_suggest=false +"кОт": contains=false check=false suggest=false raw_suggest=false +"кот": contains=true check=true suggest=true raw_suggest=true +"коты": contains=true check=true suggest=true raw_suggest=true +"недомы": contains=false check=false suggest=false raw_suggest=false +"некот": contains=true check=true suggest=true raw_suggest=true +"некоты": contains=true check=true suggest=true raw_suggest=true +"тайна": contains=true check=true suggest=false raw_suggest=false +"тайнаы": contains=true check=true suggest=false raw_suggest=false +id: continuation and NOSUGGEST through derivations +len=3 rules=3 +try="abcdeikn" key="qwerty|asdf" map=[] rep=[("dj", "j")] comments=["original compatibility fixture"] +forms "baca": ["baca", "bacakan", "bacakanlah"] +forms "main": ["bermain", "bermainkan", "main", "mainkan", "mainkanlah"] +forms "rahasia": ["rahasia", "rahasiakan", "rahasiakanlah"] +"BACA": contains=false check=true suggest=true raw_suggest=false +"BACAKAN": contains=false check=true suggest=true raw_suggest=false +"BACAKANLAH": contains=false check=true suggest=true raw_suggest=false +"BERBACA": contains=false check=false suggest=false raw_suggest=false +"BERMAIN": contains=false check=true suggest=true raw_suggest=false +"BERMAINKAN": contains=false check=true suggest=true raw_suggest=false +"BERMAINKANLAH": contains=false check=false suggest=false raw_suggest=false +"Baca": contains=false check=true suggest=true raw_suggest=false +"Bacakan": contains=false check=true suggest=true raw_suggest=false +"Bacakanlah": contains=false check=true suggest=true raw_suggest=false +"Berbaca": contains=false check=false suggest=false raw_suggest=false +"Bermain": contains=false check=true suggest=true raw_suggest=false +"Bermainkan": contains=false check=true suggest=true raw_suggest=false +"Bermainkanlah": contains=false check=false suggest=false raw_suggest=false +"MAIN": contains=false check=true suggest=true raw_suggest=false +"MAINKAN": contains=false check=true suggest=true raw_suggest=false +"MAINKANLAH": contains=false check=true suggest=true raw_suggest=false +"MAINKANLAHLAH": contains=false check=false suggest=false raw_suggest=false +"MAINLAH": contains=false check=false suggest=false raw_suggest=false +"Main": contains=false check=true suggest=true raw_suggest=false +"Mainkan": contains=false check=true suggest=true raw_suggest=false +"Mainkanlah": contains=false check=true suggest=true raw_suggest=false +"Mainkanlahlah": contains=false check=false suggest=false raw_suggest=false +"Mainlah": contains=false check=false suggest=false raw_suggest=false +"RAHASIA": contains=false check=true suggest=false raw_suggest=false +"RAHASIAKAN": contains=false check=true suggest=false raw_suggest=false +"RAHASIAKANLAH": contains=false check=true suggest=false raw_suggest=false +"Rahasia": contains=false check=true suggest=false raw_suggest=false +"Rahasiakan": contains=false check=true suggest=false raw_suggest=false +"Rahasiakanlah": contains=false check=true suggest=false raw_suggest=false +"baca": contains=true check=true suggest=true raw_suggest=true +"bacakan": contains=true check=true suggest=true raw_suggest=true +"bacakanlah": contains=true check=true suggest=true raw_suggest=true +"berbaca": contains=false check=false suggest=false raw_suggest=false +"bermain": contains=true check=true suggest=true raw_suggest=true +"bermainkan": contains=true check=true suggest=true raw_suggest=true +"bermainkanlah": contains=false check=false suggest=false raw_suggest=false +"main": contains=true check=true suggest=true raw_suggest=true +"mainkan": contains=true check=true suggest=true raw_suggest=true +"mainkanlah": contains=true check=true suggest=true raw_suggest=true +"mainkanlahlah": contains=false check=false suggest=false raw_suggest=false +"mainlah": contains=false check=false suggest=false raw_suggest=false +"rahasia": contains=true check=true suggest=false raw_suggest=false +"rahasiakan": contains=true check=true suggest=false raw_suggest=false +"rahasiakanlah": contains=true check=true suggest=false raw_suggest=false +pt-sized: 70 distinct flags across the old u128 boundary +len=2 rules=70 +try="" key="" map=[] rep=[] comments=["original compatibility fixture"] +forms "outro": ["outro", "outroõ"] +forms "verbo": ["verbo", "verbo1", "verbo2", "verbo3", "verbo4", "verbo5", "verbo6", "verbo7", "verbo8", "verbo9", "verboA", "verboB", "verboC", "verboD", "verboE", "verboF", "verboG", "verboH", "verboI", "verboJ", "verboK", "verboL", "verboM", "verboN", "verboO", "verboP", "verboQ", "verboR", "verboS", "verboT", "verboU", "verboV", "verboW", "verboX", "verboY", "verboZ", "verboa", "verbob", "verboc", "verbod", "verboe", "verbof", "verbog", "verboh", "verboi", "verboj", "verbok", "verbol", "verbom", "verbon", "verboo", "verbop", "verboq", "verbor", "verbos", "verbot", "verbou", "verbov", "verbow", "verbox", "verboy", "verboz", "verboá", "verboã", "verboç", "verboé", "verboí", "verboó", "verboõ", "verboú"] +"OUTRO": contains=false check=true suggest=true raw_suggest=false +"OUTROA": contains=false check=false suggest=false raw_suggest=false +"OUTROÕ": contains=false check=true suggest=true raw_suggest=false +"Outro": contains=false check=true suggest=true raw_suggest=false +"Outroa": contains=false check=false suggest=false raw_suggest=false +"Outroõ": contains=false check=true suggest=true raw_suggest=false +"VERBO": contains=false check=true suggest=true raw_suggest=false +"VERBO0": contains=false check=false suggest=false raw_suggest=false +"VERBO1": contains=false check=true suggest=true raw_suggest=false +"VERBO2": contains=false check=true suggest=true raw_suggest=false +"VERBO3": contains=false check=true suggest=true raw_suggest=false +"VERBO4": contains=false check=true suggest=true raw_suggest=false +"VERBO5": contains=false check=true suggest=true raw_suggest=false +"VERBO6": contains=false check=true suggest=true raw_suggest=false +"VERBO7": contains=false check=true suggest=true raw_suggest=false +"VERBO8": contains=false check=true suggest=true raw_suggest=false +"VERBO9": contains=false check=true suggest=true raw_suggest=false +"VERBOA": contains=false check=true suggest=true raw_suggest=false +"VERBOB": contains=false check=true suggest=true raw_suggest=false +"VERBOC": contains=false check=true suggest=true raw_suggest=false +"VERBOD": contains=false check=true suggest=true raw_suggest=false +"VERBOE": contains=false check=true suggest=true raw_suggest=false +"VERBOF": contains=false check=true suggest=true raw_suggest=false +"VERBOG": contains=false check=true suggest=true raw_suggest=false +"VERBOH": contains=false check=true suggest=true raw_suggest=false +"VERBOI": contains=false check=true suggest=true raw_suggest=false +"VERBOJ": contains=false check=true suggest=true raw_suggest=false +"VERBOK": contains=false check=true suggest=true raw_suggest=false +"VERBOL": contains=false check=true suggest=true raw_suggest=false +"VERBOM": contains=false check=true suggest=true raw_suggest=false +"VERBON": contains=false check=true suggest=true raw_suggest=false +"VERBOO": contains=false check=true suggest=true raw_suggest=false +"VERBOP": contains=false check=true suggest=true raw_suggest=false +"VERBOQ": contains=false check=true suggest=true raw_suggest=false +"VERBOR": contains=false check=true suggest=true raw_suggest=false +"VERBOS": contains=false check=true suggest=true raw_suggest=false +"VERBOSS": contains=false check=false suggest=false raw_suggest=false +"VERBOT": contains=false check=true suggest=true raw_suggest=false +"VERBOU": contains=false check=true suggest=true raw_suggest=false +"VERBOV": contains=false check=true suggest=true raw_suggest=false +"VERBOW": contains=false check=true suggest=true raw_suggest=false +"VERBOX": contains=false check=true suggest=true raw_suggest=false +"VERBOY": contains=false check=true suggest=true raw_suggest=false +"VERBOZ": contains=false check=true suggest=true raw_suggest=false +"VERBOÁ": contains=false check=true suggest=true raw_suggest=false +"VERBOÃ": contains=false check=true suggest=true raw_suggest=false +"VERBOÇ": contains=false check=true suggest=true raw_suggest=false +"VERBOÉ": contains=false check=true suggest=true raw_suggest=false +"VERBOÍ": contains=false check=true suggest=true raw_suggest=false +"VERBOÓ": contains=false check=true suggest=true raw_suggest=false +"VERBOÕ": contains=false check=true suggest=true raw_suggest=false +"VERBOÚ": contains=false check=true suggest=true raw_suggest=false +"Verbo": contains=false check=true suggest=true raw_suggest=false +"Verbo0": contains=false check=false suggest=false raw_suggest=false +"Verbo1": contains=false check=true suggest=true raw_suggest=false +"Verbo2": contains=false check=true suggest=true raw_suggest=false +"Verbo3": contains=false check=true suggest=true raw_suggest=false +"Verbo4": contains=false check=true suggest=true raw_suggest=false +"Verbo5": contains=false check=true suggest=true raw_suggest=false +"Verbo6": contains=false check=true suggest=true raw_suggest=false +"Verbo7": contains=false check=true suggest=true raw_suggest=false +"Verbo8": contains=false check=true suggest=true raw_suggest=false +"Verbo9": contains=false check=true suggest=true raw_suggest=false +"VerboA": contains=false check=false suggest=false raw_suggest=false +"VerboB": contains=false check=false suggest=false raw_suggest=false +"VerboC": contains=false check=false suggest=false raw_suggest=false +"VerboD": contains=false check=false suggest=false raw_suggest=false +"VerboE": contains=false check=false suggest=false raw_suggest=false +"VerboF": contains=false check=false suggest=false raw_suggest=false +"VerboG": contains=false check=false suggest=false raw_suggest=false +"VerboH": contains=false check=false suggest=false raw_suggest=false +"VerboI": contains=false check=false suggest=false raw_suggest=false +"VerboJ": contains=false check=false suggest=false raw_suggest=false +"VerboK": contains=false check=false suggest=false raw_suggest=false +"VerboL": contains=false check=false suggest=false raw_suggest=false +"VerboM": contains=false check=false suggest=false raw_suggest=false +"VerboN": contains=false check=false suggest=false raw_suggest=false +"VerboO": contains=false check=false suggest=false raw_suggest=false +"VerboP": contains=false check=false suggest=false raw_suggest=false +"VerboQ": contains=false check=false suggest=false raw_suggest=false +"VerboR": contains=false check=false suggest=false raw_suggest=false +"VerboS": contains=false check=false suggest=false raw_suggest=false +"VerboT": contains=false check=false suggest=false raw_suggest=false +"VerboU": contains=false check=false suggest=false raw_suggest=false +"VerboV": contains=false check=false suggest=false raw_suggest=false +"VerboW": contains=false check=false suggest=false raw_suggest=false +"VerboX": contains=false check=false suggest=false raw_suggest=false +"VerboY": contains=false check=false suggest=false raw_suggest=false +"VerboZ": contains=false check=false suggest=false raw_suggest=false +"Verboa": contains=false check=true suggest=true raw_suggest=false +"Verbob": contains=false check=true suggest=true raw_suggest=false +"Verboc": contains=false check=true suggest=true raw_suggest=false +"Verbod": contains=false check=true suggest=true raw_suggest=false +"Verboe": contains=false check=true suggest=true raw_suggest=false +"Verbof": contains=false check=true suggest=true raw_suggest=false +"Verbog": contains=false check=true suggest=true raw_suggest=false +"Verboh": contains=false check=true suggest=true raw_suggest=false +"Verboi": contains=false check=true suggest=true raw_suggest=false +"Verboj": contains=false check=true suggest=true raw_suggest=false +"Verbok": contains=false check=true suggest=true raw_suggest=false +"Verbol": contains=false check=true suggest=true raw_suggest=false +"Verbom": contains=false check=true suggest=true raw_suggest=false +"Verbon": contains=false check=true suggest=true raw_suggest=false +"Verboo": contains=false check=true suggest=true raw_suggest=false +"Verbop": contains=false check=true suggest=true raw_suggest=false +"Verboq": contains=false check=true suggest=true raw_suggest=false +"Verbor": contains=false check=true suggest=true raw_suggest=false +"Verbos": contains=false check=true suggest=true raw_suggest=false +"Verbot": contains=false check=true suggest=true raw_suggest=false +"Verbou": contains=false check=true suggest=true raw_suggest=false +"Verbov": contains=false check=true suggest=true raw_suggest=false +"Verbow": contains=false check=true suggest=true raw_suggest=false +"Verbox": contains=false check=true suggest=true raw_suggest=false +"Verboy": contains=false check=true suggest=true raw_suggest=false +"Verboz": contains=false check=true suggest=true raw_suggest=false +"Verboß": contains=false check=false suggest=false raw_suggest=false +"Verboá": contains=false check=true suggest=true raw_suggest=false +"Verboã": contains=false check=true suggest=true raw_suggest=false +"Verboç": contains=false check=true suggest=true raw_suggest=false +"Verboé": contains=false check=true suggest=true raw_suggest=false +"Verboí": contains=false check=true suggest=true raw_suggest=false +"Verboó": contains=false check=true suggest=true raw_suggest=false +"Verboõ": contains=false check=true suggest=true raw_suggest=false +"Verboú": contains=false check=true suggest=true raw_suggest=false +"outro": contains=true check=true suggest=true raw_suggest=true +"outroa": contains=false check=false suggest=false raw_suggest=false +"outroõ": contains=true check=true suggest=true raw_suggest=true +"verbo": contains=true check=true suggest=true raw_suggest=true +"verbo0": contains=false check=false suggest=false raw_suggest=false +"verbo1": contains=true check=true suggest=true raw_suggest=true +"verbo2": contains=true check=true suggest=true raw_suggest=true +"verbo3": contains=true check=true suggest=true raw_suggest=true +"verbo4": contains=true check=true suggest=true raw_suggest=true +"verbo5": contains=true check=true suggest=true raw_suggest=true +"verbo6": contains=true check=true suggest=true raw_suggest=true +"verbo7": contains=true check=true suggest=true raw_suggest=true +"verbo8": contains=true check=true suggest=true raw_suggest=true +"verbo9": contains=true check=true suggest=true raw_suggest=true +"verboA": contains=true check=true suggest=true raw_suggest=true +"verboB": contains=true check=true suggest=true raw_suggest=true +"verboC": contains=true check=true suggest=true raw_suggest=true +"verboD": contains=true check=true suggest=true raw_suggest=true +"verboE": contains=true check=true suggest=true raw_suggest=true +"verboF": contains=true check=true suggest=true raw_suggest=true +"verboG": contains=true check=true suggest=true raw_suggest=true +"verboH": contains=true check=true suggest=true raw_suggest=true +"verboI": contains=true check=true suggest=true raw_suggest=true +"verboJ": contains=true check=true suggest=true raw_suggest=true +"verboK": contains=true check=true suggest=true raw_suggest=true +"verboL": contains=true check=true suggest=true raw_suggest=true +"verboM": contains=true check=true suggest=true raw_suggest=true +"verboN": contains=true check=true suggest=true raw_suggest=true +"verboO": contains=true check=true suggest=true raw_suggest=true +"verboP": contains=true check=true suggest=true raw_suggest=true +"verboQ": contains=true check=true suggest=true raw_suggest=true +"verboR": contains=true check=true suggest=true raw_suggest=true +"verboS": contains=true check=true suggest=true raw_suggest=true +"verboT": contains=true check=true suggest=true raw_suggest=true +"verboU": contains=true check=true suggest=true raw_suggest=true +"verboV": contains=true check=true suggest=true raw_suggest=true +"verboW": contains=true check=true suggest=true raw_suggest=true +"verboX": contains=true check=true suggest=true raw_suggest=true +"verboY": contains=true check=true suggest=true raw_suggest=true +"verboZ": contains=true check=true suggest=true raw_suggest=true +"verboa": contains=true check=true suggest=true raw_suggest=true +"verbob": contains=true check=true suggest=true raw_suggest=true +"verboc": contains=true check=true suggest=true raw_suggest=true +"verbod": contains=true check=true suggest=true raw_suggest=true +"verboe": contains=true check=true suggest=true raw_suggest=true +"verbof": contains=true check=true suggest=true raw_suggest=true +"verbog": contains=true check=true suggest=true raw_suggest=true +"verboh": contains=true check=true suggest=true raw_suggest=true +"verboi": contains=true check=true suggest=true raw_suggest=true +"verboj": contains=true check=true suggest=true raw_suggest=true +"verbok": contains=true check=true suggest=true raw_suggest=true +"verbol": contains=true check=true suggest=true raw_suggest=true +"verbom": contains=true check=true suggest=true raw_suggest=true +"verbon": contains=true check=true suggest=true raw_suggest=true +"verboo": contains=true check=true suggest=true raw_suggest=true +"verbop": contains=true check=true suggest=true raw_suggest=true +"verboq": contains=true check=true suggest=true raw_suggest=true +"verbor": contains=true check=true suggest=true raw_suggest=true +"verbos": contains=true check=true suggest=true raw_suggest=true +"verbot": contains=true check=true suggest=true raw_suggest=true +"verbou": contains=true check=true suggest=true raw_suggest=true +"verbov": contains=true check=true suggest=true raw_suggest=true +"verbow": contains=true check=true suggest=true raw_suggest=true +"verbox": contains=true check=true suggest=true raw_suggest=true +"verboy": contains=true check=true suggest=true raw_suggest=true +"verboz": contains=true check=true suggest=true raw_suggest=true +"verboß": contains=false check=false suggest=false raw_suggest=false +"verboá": contains=true check=true suggest=true raw_suggest=true +"verboã": contains=true check=true suggest=true raw_suggest=true +"verboç": contains=true check=true suggest=true raw_suggest=true +"verboé": contains=true check=true suggest=true raw_suggest=true +"verboí": contains=true check=true suggest=true raw_suggest=true +"verboó": contains=true check=true suggest=true raw_suggest=true +"verboõ": contains=true check=true suggest=true raw_suggest=true +"verboú": contains=true check=true suggest=true raw_suggest=true diff --git a/crates/proof/tests/fixtures/affix_compatibility_cases.rs b/crates/proof/tests/fixtures/affix_compatibility_cases.rs new file mode 100644 index 000000000..d0c2973b4 --- /dev/null +++ b/crates/proof/tests/fixtures/affix_compatibility_cases.rs @@ -0,0 +1,61 @@ +// Original, deliberately small fixtures for behavior supported before French proofing. +// These are not extracts from installed dictionaries and do not claim full language coverage. +pub struct Case { + pub name: &'static str, + pub aff: String, + pub dic: String, + pub probes: Vec<&'static str>, +} + +pub fn cases() -> Vec { + let mut out = vec![ + Case { + name: "pl: conditional strip, prefix cross products, diacritics", + aff: "SET UTF-8\nTRY aeoiułkr\nPFX b Y 1\nPFX b 0 nie .\nSFX a Y 3\nSFX a 0 y [^y]\nSFX a ek ka ek\nSFX a 0 em .\nSFX c N 1\nSFX c a ą a\nMAP 2\nMAP aą\nMAP oóu\nREP 2\nREP ż rz\nREP u ó\n".into(), + dic: "4\nkot/ab\npiesek/a\nkrowa/c\nWarszawa/c\n".into(), + probes: vec!["kot", "koty", "kotem", "niekoty", "pieska", "pieseka", "niepieska", "krową", "krowy", "Warszawą", "warszawą", "kotą", "nie", ""], + }, + Case { + name: "pt: UTF-8 flags, forbidden words, two suffixes", + aff: "SET UTF-8\nFLAG UTF-8\nFORBIDDENWORD ý\nTRY aeiouçãõ\nSFX A Y 1\nSFX A o a/B o\nSFX B Y 1\nSFX B 0 s .\nPFX P Y 1\nPFX P 0 re .\n".into(), + dic: "4\nbonito/AB\ncasa/B\nfazer/P\nimundo/ýB\n".into(), + probes: vec!["bonito", "bonita", "bonitos", "bonitas", "bonitass", "casa", "casas", "casaa", "refazer", "recasas", "imundo", "imundos", "Imundo", "IMUNDO"], + }, + Case { + name: "it: stripping, non-crossing suffix, proper-name casing", + aff: "SET UTF-8\nSFX A Y 1\nSFX A o i o\nSFX B N 1\nSFX B a e a\nPFX P Y 1\nPFX P 0 ri .\n".into(), + dic: "4\nlibro/A\ncasa/BP\nfare/P\nRoma\n".into(), + probes: vec!["libri", "libros", "case", "ricas a", "ricasa", "ricase", "rifare", "r ilibri", "Roma", "roma", "ROMA", ""], + }, + Case { + name: "cs: negated conditions and shared Unicode stems", + aff: "SET UTF-8\nPFX N Y 1\nPFX N 0 ne .\nSFX S Y 1\nSFX S 0 y [^y]\nSFX E N 1\nSFX E a ě a\n".into(), + dic: "4\nstrom/NS\nžena/E\nmladý/N\ny/S\n".into(), + probes: vec!["stromy", "nestromy", "nestrom", "ženě", "ženy", "neženě", "nemladý", "mladýy", "yy", "Ženě", "STROMY"], + }, + Case { + name: "ru: Cyrillic flags and suggestions exclusion", + aff: "SET UTF-8\nFLAG UTF-8\nNOSUGGEST Н\nFORBIDDENWORD Ф\nSFX Я Y 1\nSFX Я 0 ы .\nPFX П Y 1\nPFX П 0 не .\nMAP 1\nMAP её\n".into(), + dic: "4\nкот/ЯП\nдом/Я\nтайна/НЯ\nзапрет/ФЯ\n".into(), + probes: vec!["кот", "коты", "некоты", "домы", "недомы", "тайна", "тайнаы", "ТАЙНАЫ", "запрет", "запреты", "КОТЫ", "кОт"], + }, + Case { + name: "id: continuation and NOSUGGEST through derivations", + aff: "SET UTF-8\nNOSUGGEST N\nKEY qwerty|asdf\nTRY abcdeikn\nREP 1\nREP dj j\nPFX P Y 1\nPFX P 0 ber .\nSFX A Y 1\nSFX A 0 kan/B .\nSFX B Y 1\nSFX B 0 lah .\n".into(), + dic: "3\nmain/PA\nbaca/A\nrahasia/NA\n".into(), + probes: vec!["main", "bermain", "mainkan", "mainkanlah", "bermainkanlah", "mainlah", "mainkanlahlah", "bacakanlah", "berbaca", "rahasia", "rahasiakan", "RAHASIAKANLAH"], + }, + ]; + let flags: Vec = ('a'..='z').chain('A'..='Z').chain('0'..='9').chain(['á', 'é', 'í', 'ó', 'ú', 'ç', 'ã', 'õ']).collect(); + let mut aff = String::from("SET UTF-8\nFLAG UTF-8\n"); + for flag in &flags { + aff.push_str(&format!("SFX {flag} N 1\nSFX {flag} 0 {flag} .\n")); + } + out.push(Case { + name: "pt-sized: 70 distinct flags across the old u128 boundary", + aff, + dic: format!("2\nverbo/{}\noutro/õ\n", flags.iter().collect::()), + probes: vec!["verboa", "verboz", "verboA", "verboZ", "verbo0", "verbo9", "verboç", "verboõ", "verboß", "outroõ", "outroa"], + }); + out +} diff --git a/crates/proof/tests/french_dictionary.rs b/crates/proof/tests/french_dictionary.rs new file mode 100644 index 000000000..5612a0e61 --- /dev/null +++ b/crates/proof/tests/french_dictionary.rs @@ -0,0 +1,107 @@ +//! Explicit manual real-dictionary gate. Verify the pinned runtime inputs as documented in +//! crates/proof/README.md before running with `--ignored`. Missing data is a failure, +//! never a silently successful test that checked nothing. + +#![cfg(not(target_arch = "wasm32"))] +#![allow(clippy::unwrap_used, clippy::expect_used)] + +use craft_proof::{IssueKind, Options, ProofLang, fr}; + +#[test] +#[ignore = "requires a real French dictionary in WORDCRAFT_DICTIONARIES"] +fn real_french_dictionary_spelling_suggestions_and_dispatch() { + let directory = std::env::var_os("WORDCRAFT_DICTIONARIES").expect("set WORDCRAFT_DICTIONARIES to the test dictionary folder"); + craft_proof::set_dictionaries_folder(Some(std::path::PathBuf::from(&directory))); + let french = ProofLang::from_tag(Some("fr-FR")); + let installed = craft_proof::pack_dictionary_file(french).expect("the real French dictionary must be installed"); + assert_eq!(installed.parent(), Some(std::path::Path::new(&directory)), "do not silently use another system dictionary"); + let aff = installed.with_extension("aff"); + let dictionary = craft_proof::hunspell::load(&aff, &installed).expect("the real French dictionary loads"); + assert!(dictionary.len() > 50_000, "expected Dicollecte, not the synthetic fixture: {}", dictionary.len()); + for word in [ + "maison", + "maisons", + "Paris", + "mangeons", + "finissaient", + "étaient", + "l'arbre", + "l’arbre", + "qu'elles", + "école", + "œuvre", + "aujourd'hui", + "chevaux", + "heureuse", + "va-t-il", + ] { + assert!(fr::is_correct(word), "correct French word: {word}"); + } + for (typo, expected) in [("maisonn", "maison"), ("ecole", "école"), ("l’ecole", "l’école"), ("documant", "document")] { + assert!(!fr::is_correct(typo), "misspelling: {typo}"); + let suggestions = fr::suggest(typo, 8); + assert!(suggestions.iter().any(|s| s == expected), "{typo} -> {suggestions:?}, expected {expected}"); + } + let text = "Une maisonn près de l’école."; + for lang in [ProofLang::from_tag(Some("fr-FR")), ProofLang::from_tag(Some("fr-CA"))] { + let issues = craft_proof::check_text(text, &[(0..text.len(), lang)]); + assert_eq!(issues.len(), 1, "{lang:?}: {issues:?}"); + let issue = &issues[0]; + assert_eq!(&text[issue.start..issue.end], "maisonn"); + assert_eq!(issue.lang, lang); + assert_eq!(issue.message, "Faute d’orthographe possible"); + } + check_combining_marks_and_compounds(&dictionary); + assert!(craft_proof::dictionary_load_error(ProofLang::from_tag(Some("fr-FR"))).is_none()); +} + +fn check_combining_marks_and_compounds(dictionary: &craft_proof::affix::AffixDict) { + let spelling = |text: &str, spans: &[(std::ops::Range, ProofLang)]| { + craft_proof::check_text_with(text, spans, &Options::default(), false, false) + .into_iter() + .filter(|i| i.kind == IssueKind::Spelling) + .map(|i| (i.start, i.end, i.lang)) + .collect::>() + }; + let mut failures = Vec::new(); + for lang in [ProofLang::from_tag(Some("fr-FR")), ProofLang::from_tag(Some("fr-CA"))] { + for text in + ["école", "e\u{301}cole", "l’école", "l’e\u{301}cole", "café", "cafe\u{301}", "porte-monnaie", "va-t-il", "a-t-il", "maison-école"] + { + assert!( + fr::is_correct_with(dictionary, text) || ["va-t-il", "a-t-il", "maison-école"].contains(&text), + "real dictionary recognizes {text:?}" + ); + let issues = spelling(text, &[(0..text.len(), lang)]); + if !issues.is_empty() { + failures.push(format!("correct {lang:?} {text:?}: {issues:?}")); + } + } + for text in ["porte--monnaie", "va--t-il", "maison--école", "e\u{301}colllle", "cafffe\u{301}"] { + assert!(!fr::is_correct_with(dictionary, text), "the explicit dictionary entry must not already accept {text:?}"); + let issues = spelling(text, &[(0..text.len(), lang)]); + let expected = vec![(0, text.len(), lang)]; + if issues != expected { + failures.push(format!("typo {lang:?} {text:?}: {issues:?}, wanted {expected:?}")); + } + } + let text = "e\u{301}cole cafe\u{301} xyzxyz porte--monnaie"; + let foreign = text.find("xyzxyz").unwrap(); + let compound = text.find("porte").unwrap(); + let spans = [(0..foreign, lang), (foreign..compound, ProofLang::Other), (compound..text.len(), lang)]; + let issues = spelling(text, &spans); + if issues != [(compound, text.len(), lang)] { + failures.push(format!("mixed {lang:?}: {issues:?}")); + } + assert!(spelling(text, &[(0..text.len(), ProofLang::Other)]).is_empty()); + // An English word remains in its own dictionary next to the original French bytes. + let text = "e\u{301}cole hello cafe\u{301}"; + let en = text.find("hello").unwrap(); + let spans = [(0..en, lang), (en..en + 5, ProofLang::En), (en + 5..text.len(), lang)]; + let issues = spelling(text, &spans); + if !issues.is_empty() { + failures.push(format!("English boundary {lang:?}: {issues:?}")); + } + } + assert!(failures.is_empty(), "{}", failures.join("\n")); +} diff --git a/crates/proof/tests/french_packs.rs b/crates/proof/tests/french_packs.rs new file mode 100644 index 000000000..64ad46748 --- /dev/null +++ b/crates/proof/tests/french_packs.rs @@ -0,0 +1,124 @@ +//! French uses ordinary Language packs and keeps each regional locale at the public API. +#![allow(clippy::unwrap_used, clippy::expect_used)] + +use craft_proof::affix; +use craft_proof::{IssueKind, Options, ProofLang, check_text_with, is_correct_in_with, suggest_in}; +use std::path::{Path, PathBuf}; + +#[path = "../src/fr/test_dict.rs"] +mod fixture; + +struct Tools(PathBuf); +impl Drop for Tools { + fn drop(&mut self) { + craft_proof::set_dictionaries_folder(None); + craft_proof::packs::set_packs_dir(None); + craft_proof::remove_word("zxqrechargefr"); + let _ = std::fs::remove_dir_all(&self.0); + } +} + +fn pair(dir: &Path, name: &str, aff: &str, dic: &str) { + std::fs::create_dir_all(dir).unwrap(); + std::fs::write(dir.join(format!("{name}.aff")), aff).unwrap(); + std::fs::write(dir.join(format!("{name}.dic")), dic).unwrap(); +} + +#[test] +fn french_packs_regions_reload_and_original_ranges() { + assert!(!fixture::dictionary().is_empty()); + let root = std::env::temp_dir().join(format!("craft-fr-packs-{}", std::process::id())); + let _tools = Tools(root.clone()); + let pack = root.join("packs/fr"); + pair(&pack, "spelling", fixture::AFF, fixture::DIC); + std::fs::write(pack.join("pack.toml"), "locale = 'fr'\nname = 'Français'\nlicence = 'MIT'\n").unwrap(); + std::fs::write(pack.join("hyphenation.pat"), "ma1ison\n").unwrap(); + let folder = root.join("dictionaries"); + std::fs::create_dir_all(&folder).unwrap(); + craft_proof::packs::set_packs_dir(Some(root.join("packs"))); + craft_proof::set_dictionaries_folder(Some(folder.clone())); + let defaults = Options::default(); + let strict = Options { ignore_uppercase: false, ignore_numbers: false, ..defaults }; + check_locales(defaults, strict); + check_typography(strict); + let fr = ProofLang::from_tag(Some("fr-FR")); + let ca = ProofLang::from_tag(Some("fr-CA")); + check_user_word(fr, ca, strict); + check_overrides(folder, fr, ca, strict); +} + +fn check_locales(defaults: Options, strict: Options) { + for tag in ["fr", "fr-FR", "fr-CA", "fr-BE", "fr-CA-u-nu-latn", "fr-u-ca-gregory"] { + let lang = ProofLang::from_tag(Some(tag)); + assert!(matches!(lang, ProofLang::Pack(_)), "{tag}"); + assert!(craft_proof::has_dictionary(Some(tag)), "{tag}"); + assert!(craft_proof::pack_dictionary_file(lang).unwrap().ends_with("fr/spelling.dic"), "{tag}"); + for word in ["école", "e\u{301}cole", "l'arbre", "l’arbre", "maison-école"] { + assert!(is_correct_in_with(word, lang, &strict), "{tag}: {word}"); + } + assert!(!is_correct_in_with("maison--école", lang, &strict)); + assert!(!is_correct_in_with("l'arbres", lang, &strict)); + assert!(is_correct_in_with("SNCF", lang, &defaults)); + assert!(!is_correct_in_with("SNCF", lang, &strict)); + assert!(is_correct_in_with("mp3x", lang, &defaults)); + assert!(!is_correct_in_with("mp3x", lang, &strict)); + assert!(suggest_in("ecole", 6, lang).iter().any(|s| s == "école")); + let text = "🙂 maison\u{338} école"; + let issues = check_text_with(text, &[(0..text.len(), lang)], &strict, false, false); + assert_eq!(issues.len(), 1, "{tag}: {issues:?}"); + assert_eq!(&text[issues[0].start..issues[0].end], "maison\u{338}"); + assert_eq!(issues[0].lang, lang); + assert_eq!(issues[0].kind, IssueKind::Spelling); + assert_eq!(issues[0].message, "Faute d’orthographe possible"); + } +} + +fn check_typography(strict: Options) { + let fr = ProofLang::from_tag(Some("fr-FR")); + let ca = ProofLang::from_tag(Some("fr-CA")); + for lang in [fr, ca] { + assert_eq!(craft_proof::hyphen::hyphen_points_in("maison", &craft_proof::hyphen::Limits::default(), lang), [2]); + } + for tag in ["fr-FR", "fr-BE", "fr-u-ca-gregory", "fr-FR-u-rg-cazzzz"] { + let issues = craft_proof::check_grammar_in("Bonjour!", ProofLang::from_tag(Some(tag))); + assert_eq!(issues.len(), 1, "{tag}: {issues:?}"); + assert_eq!(issues[0].suggestions, ["\u{202f}!"]); + } + assert!(craft_proof::check_grammar_in("Bonjour!", ca).is_empty()); + assert!(craft_proof::check_grammar_in("Bonjour!", ProofLang::from_tag(Some("fr-Latn-CA"))).is_empty()); + assert!(craft_proof::check_grammar_in("Bonjour!", ProofLang::from_tag(Some("nl-NL"))).is_empty()); + assert!(craft_proof::fr::grammar::check_in("Bonjour!", ProofLang::En).is_empty()); + let text = "Bonjour! Salut!"; + let issues = check_text_with(text, &[(0..8, fr), (8..text.len(), ca)], &strict, true, false); + let spacing: Vec<_> = issues.iter().filter(|i| i.kind == IssueKind::Grammar && i.message.contains("fine insécable")).collect(); + assert_eq!(spacing.len(), 1, "{issues:?}"); + assert_eq!(spacing[0].lang, fr); +} + +fn check_user_word(fr: ProofLang, ca: ProofLang, strict: Options) { + craft_proof::add_word("zxqrechargefr"); + for lang in [fr, ca] { + assert!(is_correct_in_with("l’zxqrechargefr", lang, &strict)); + } + craft_proof::remove_word("zxqrechargefr"); + assert!(!is_correct_in_with("l’zxqrechargefr", ca, &strict)); +} + +fn check_overrides(folder: PathBuf, fr: ProofLang, ca: ProofLang, strict: Options) { + // Regional overrides keep the generic pack fallback and the shared reload generation. + pair(&folder, "fr_FR", "SET UTF-8\n", "1\nhexagonefixture\n"); + pair(&folder, "fr_CA", "SET UTF-8\n", "1\nquebecfixture\n"); + let generation = craft_proof::dictionary_generation(); + craft_proof::set_dictionaries_folder(Some(folder.clone())); + assert!(craft_proof::dictionary_generation() > generation); + assert!(is_correct_in_with("hexagonefixture", fr, &strict)); + assert!(!is_correct_in_with("hexagonefixture", ca, &strict)); + assert!(is_correct_in_with("quebecfixture", ca, &strict)); + assert!(!is_correct_in_with("quebecfixture", fr, &strict)); + assert!(craft_proof::pack_dictionary_file(ca).unwrap().ends_with("fr_CA.dic")); + std::fs::remove_file(folder.join("fr_CA.dic")).unwrap(); + std::fs::remove_file(folder.join("fr_CA.aff")).unwrap(); + craft_proof::set_dictionaries_folder(Some(folder)); + assert!(is_correct_in_with("école", ca, &strict), "removed regional override falls back to fr pack"); + assert!(craft_proof::pack_dictionary_file(ca).unwrap().ends_with("fr/spelling.dic")); +} From 3c5ffadd3b3fb4bcbf657a245ad9c480d2b6e304 Mon Sep 17 00:00:00 2001 From: totoz64 <47389794+totoz64@users.noreply.github.com> Date: Tue, 3 Nov 2026 11:53:24 +0100 Subject: [PATCH 02/56] Proofing: retain exact apostrophes in French compounds Check each original compound component before its ASCII-apostrophe alias. Add a curly-only dictionary regression, prove legacy fixture headers before rejecting WCAFF1, and clarify French-specific Pack grammar in the README. Preserve the existing one-letter component policy. --- crates/proof/README.md | 13 ++++++++----- crates/proof/src/fr/mod.rs | 14 +++++++++++++- crates/proof/tests/affix_compatibility.rs | 2 ++ 3 files changed, 23 insertions(+), 6 deletions(-) diff --git a/crates/proof/README.md b/crates/proof/README.md index b4b4b5ba8..4cc4b2ca4 100644 --- a/crates/proof/README.md +++ b/crates/proof/README.md @@ -89,19 +89,22 @@ pub fn load_errors() -> Vec<(String, String)>; // + (locale or folder, pub fn embedded_locales() -> &'static [&'static str]; // + locales with embedded upstream data, not our supplements ("en-us", "en-gb", "en-ca", "en-au", "pl", "pt", "it", "de" by default; the four English ones with CRAFT_PROOF_EMBED=en) // craft_proof (crate root) -pub enum ProofLang { …, Pack(PackLocale), Other } // + Pack: any language without tools of its own (nl, fr, sr-Latn…) +pub enum ProofLang { …, Pack(PackLocale), Other } // + Pack: a language without a dedicated built-in variant (nl, fr, sr-Latn…) pub struct PackLocale; // + Copy; PackLocale::new(tag) -> Option, .as_str() "nl-nl", .primary() "nl", Display impl ProofLang { pub fn pack_locale(self) -> Option; } // + pub fn pack_dictionary_file(lang: ProofLang) -> Option; // + the .dic a Pack language reads now; None = unchecked ``` -`ProofLang::from_tag` now gives `Pack(locale)` for every valid language tag it has no tools for +`ProofLang::from_tag` now gives `Pack(locale)` for every valid language tag without a dedicated built-in variant (`nl-NL` → `Pack("nl-nl")`, `fr-FR`, `ja-JP`, `sr-Latn`…); `Other` is left for `x-none`, `und`, `zxx`, `mul`, `mis`, `i-…` and malformed tags. A `Pack` language is spell-checked and given suggestions from its Hunspell dictionary (dictionaries folder → installed pack → system Hunspell) -through the shared affix engine with default tuning, and hyphenated from its pack's -`hyphenation.pat`; it has no grammar rules and the generic English spelling message. Without a -dictionary or pack it behaves exactly as `Other` did (no marks, English hyphenation fallback). +through the shared affix engine with default tuning (French tuning for `fr` packs), and +hyphenated from its pack's `hyphenation.pat`. Most pack languages use no dedicated grammar +rules; regional variants can reuse a built-in language's rules. French packs use the French +spelling message and the conservative French grammar and typography described above. Without a dictionary or pack, +spelling has no marks and hyphenation falls back to English; French grammar and typography +still apply independently of a spelling dictionary. `has_dictionary(tag)` / `ProofLang::is_proofed()` say whether a `Pack` language has a dictionary now (read on first use, cached). Loaded `Pack` dictionaries share a 256 MB budget (estimated from their files); the least recently used goes first, but never one used in the paragraph being checked, and languages with no dictionary take no room. Downstream `match`es on `ProofLang` need a `Pack(_)` arm; `code()` stays `&'static str` and is `""` for it, as for `Other`: anything that keys, saves or reports a language (settings, caches, JSON/MCP output) uses `tag()`, which is `code()` for the built-ins and the locale (`nl`, `fr-fr`) for a pack language. diff --git a/crates/proof/src/fr/mod.rs b/crates/proof/src/fr/mod.rs index 541fcac0d..c67c3ffc0 100644 --- a/crates/proof/src/fr/mod.rs +++ b/crates/proof/src/fr/mod.rs @@ -44,6 +44,7 @@ pub(crate) fn check(d: &AffixDict, word: &str, opts: &Options) -> bool { if known(d, w) { return true; } + let original = w; let w = w.replace('’', "'"); if known(d, &w) { return true; @@ -56,7 +57,7 @@ pub(crate) fn check(d: &AffixDict, word: &str, opts: &Options) -> bool { { return true; } - w.contains('-') && w.split('-').all(|p| !p.is_empty() && (p.chars().count() <= 1 || known(d, p))) + original.contains('-') && original.split('-').all(|p| !p.is_empty() && (p.chars().count() <= 1 || known(d, p) || known(d, &p.replace('’', "'")))) } fn known(d: &AffixDict, word: &str) -> bool { @@ -148,6 +149,17 @@ mod tests { assert!(!is_correct_with(&d, "maison\u{338}"), "a trailing mark is part of the word"); } + #[test] + fn curly_apostrophes_in_compounds_keep_exact_dictionary_parts() { + let d = AffixDict::from_hunspell("SET UTF-8\n", "4\naujourd’hui\nécole\ncafé\nl'école\n", &[]).unwrap(); + for word in ["aujourd’hui-école", "aujourd’hui-e\u{301}cole", "café-aujourd’hui", "l’école-aujourd’hui"] { + assert!(is_correct_with(&d, word), "{word}"); + } + for word in ["aujourd’hui-écolle", "aujourd’hui--école", "aujourd'hui-école"] { + assert!(!is_correct_with(&d, word), "{word}"); + } + } + #[test] fn explicit_curly_apostrophe_without_iconv() { let d = AffixDict::from_hunspell("SET UTF-8\n", "1\naujourd’hui\n", &[]).unwrap(); diff --git a/crates/proof/tests/affix_compatibility.rs b/crates/proof/tests/affix_compatibility.rs index 6d09e5f90..c18d9fd03 100644 --- a/crates/proof/tests/affix_compatibility.rs +++ b/crates/proof/tests/affix_compatibility.rs @@ -87,6 +87,8 @@ fn legacy_compact_data_is_refused_without_reinterpreting_homonyms() { assert_eq!(hex.len() % 2, 0); let bytes: Vec<_> = hex.as_bytes().as_chunks::<2>().0.iter().map(|pair| u8::from_str_radix(std::str::from_utf8(pair).unwrap(), 16).unwrap()).collect(); + let raw = miniz_oxide::inflate::decompress_to_vec(&bytes).unwrap(); + assert!(raw.starts_with(b"WCAFF1\n"), "fixture must contain WCAFF1 data: {}", case.name); assert!(AffixDict::from_bytes(&bytes).is_err(), "WCAFF1 must be regenerated as WCAFF2: {}", case.name); } } From 870bad52e20a62e0260c90d5d18c5643181377b7 Mon Sep 17 00:00:00 2001 From: totoz64 <47389794+totoz64@users.noreply.github.com> Date: Wed, 4 Nov 2026 17:43:22 +0100 Subject: [PATCH 03/56] M15: Preserve accepted suggestions after the shared collection budget runs out Collector::keep has already validated the stored text. Avoid rechecking identity candidates against an exhausted SuggestSteps budget; validate only changed case and fall back to the accepted original if that validation cannot succeed. Keep the same time/work caps, exclusion rules, parser and ranking. An integrated regression uses the real REP/TRY/affix pipeline and normal budget: it loses the accepted affixed suggestion on parent b5 and retains it with this change, for lower and upper input. No injected state or relaxed limit. Exact-source fmt and strict proof Clippy passed; full local/hosted validation is still being collected. Addresses CodeRabbit4470300723. --- crates/proof/src/affix_suggest.rs | 40 +++++++++++++++++++++++++------ 1 file changed, 33 insertions(+), 7 deletions(-) diff --git a/crates/proof/src/affix_suggest.rs b/crates/proof/src/affix_suggest.rs index 07194c548..b3f07e43c 100644 --- a/crates/proof/src/affix_suggest.rs +++ b/crates/proof/src/affix_suggest.rs @@ -452,13 +452,9 @@ pub(crate) fn suggest_in(d: &AffixDict, word: &str, max: usize, t: &Tuning) -> V let changed: Vec<_> = candidate.split(' ').collect(); original.len() == changed.len() && original.iter().zip(changed).all(|(a, b)| d.can_suggest_cased(a, b)) }; - let t = if eligible(&t) { - t - } else if eligible(&text) { - text.clone() - } else { - continue; - }; + // Collector::keep already accepted text. Collection may have exhausted the shared + // affix budget, so recheck only a changed case and otherwise retain that accepted form. + let t = if t == text || eligible(&t) { t } else { text.clone() }; // Shown as the dictionary's OCONV table writes it (`'` → `’` in French). let t = d.output(&t).into_owned(); if t != word && !out.contains(&t) { @@ -904,4 +900,34 @@ mod tests { assert!(suggest_in(&d, "neer", 4, &english).contains(&"ne'er".to_string())); assert_eq!(suggest_in(&d, "neer", 4, &Tuning::DEFAULT).first().map(String::as_str), Some("ne'er"), "an elision"); } + /// A REP candidate is admitted before costly TRY checks consume the normal shared budget. + /// Finalization must retain that accepted affixed word, including a conservative case fallback. + #[test] + fn accepted_affixed_suggestions_survive_exhausted_collection_budget() { + let input = format!("{}x{}", "a".repeat(20), "a".repeat(19)); + let mut aff = String::from("SET UTF-8\nFLAG num\nTRY "); + aff.extend(('a'..='z').chain((0x100..0x166).filter_map(char::from_u32))); + aff.push_str(&format!("\nREP 1\nREP {input} kots\n")); + // The bounded adversarial rule shape of the existing shared-budget regression. + for f in 1..=1000u32 { + let c = char::from_u32(0x4e00 + f).unwrap(); + aff.push_str(&format!("PFX {f} Y 1\nPFX {f} {c} 0 .\n")); + } + let conts: Vec = (0..286).map(|k| (5000 + k * 7).to_string()).collect(); + for len in 1..=40 { + for k in 0..50 { + let f = 5000 + (len - 1) * 50 + k; + aff.push_str(&format!("SFX {f} Y 1\nSFX {f} 0 {}/{} .\n", "a".repeat(len), conts.join(","))); + } + } + aff.push_str("SFX 9000 Y 1\nSFX 9000 0 s .\n"); + let d = AffixDict::from_hunspell(&aff, "3\nb/1,5000\nab/2\nkot/9000\n", &[]).unwrap(); + assert!(!d.stems().any(|s| s == "kots") && d.can_suggest("kots")); + for word in [input.clone(), input.to_uppercase()] { + let got = suggest_in(&d, &word, 1, &Tuning::DEFAULT); + assert_eq!(got.len(), 1, "accepted affixed candidate lost: {word}: {got:?}"); + assert!(got[0].eq_ignore_ascii_case("kots"), "{word}: {got:?}"); + assert!(d.can_suggest(&got[0])); + } + } } From 55a16b7a724cd7ab3f9873a415fbd6fbcd8b3c96 Mon Sep 17 00:00:00 2001 From: totoz64 <47389794+totoz64@users.noreply.github.com> Date: Wed, 4 Nov 2026 17:56:56 +0100 Subject: [PATCH 04/56] M15: Validate exact suggestion eligibility before admitting candidates Collector::keep now uses the exact-case eligibility guard before insertion, preserving NOSUGGEST, SUBSTANDARD, FORBIDDENWORD and KEEPCASE rules. Finalization can safely retain the admitted original after the collection budget is exhausted, and still validates actual case variants. No fresh budget, parser, ranking or historical fixture change. This completes CodeRabbit4470300723 without the provisional870 exclusion regression. On this exact source: workspace fmt and strict proof Clippy passed; 458 unit tests passed with52 ignored, compatibility2 and French Pack integration1 passed, and the real pinned Dicollecte test passed. The integrated normal-budget regression and all15 suggestion/casing/exclusion tests passed together in the fresh complete execution. Hosted validation of this new SHA is still required. --- crates/proof/src/affix_suggest.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/crates/proof/src/affix_suggest.rs b/crates/proof/src/affix_suggest.rs index b3f07e43c..4d8bfea59 100644 --- a/crates/proof/src/affix_suggest.rs +++ b/crates/proof/src/affix_suggest.rs @@ -248,7 +248,8 @@ impl Collector<'_> { /// Keep a suggestion known to be correct, unless the dictionary says never to offer it. fn keep(&mut self, text: String, cost: u32) { - if !text.split(' ').all(|part| self.d.can_suggest(part)) { + // Reject exact excluded spellings at admission, before later candidates spend the budget. + if !text.split(' ').all(|part| self.d.can_suggest_cased(part, part)) { return; } self.seq += 1; From 1f53b809737c5f3141406387f9aa93c971b4007b Mon Sep 17 00:00:00 2001 From: totoz64 <47389794+totoz64@users.noreply.github.com> Date: Sun, 15 Nov 2026 19:58:06 +0100 Subject: [PATCH 05/56] Proofing: retain eligible exact compound suggestions Address CodeRabbit4575003662 by considering all normalized exact derivations in the displayed-case eligibility guard, without lowercase fallback. Preserve forbidden-word handling, case exclusions, shared budgets and ranking. A real REP regression fails before the fix and passes for NOSUGGEST/SUBSTANDARD compound paths after it, while FORBIDDEN remains rejected; cover WCAFF2 round trips.460 unit tests, compatibility2, French Pack1, real Dicollecte1, formatting and strict all-target proof Clippy pass on Rust1.100. New hosted checks are still required. --- crates/proof/src/affix.rs | 5 +++-- crates/proof/src/affix_suggest.rs | 14 ++++++++++++++ 2 files changed, 17 insertions(+), 2 deletions(-) diff --git a/crates/proof/src/affix.rs b/crates/proof/src/affix.rs index 4c76815bb..b0407c59f 100644 --- a/crates/proof/src/affix.rs +++ b/crates/proof/src/affix.rs @@ -2248,11 +2248,12 @@ impl AffixDict { return false; } // The exact simple-word path includes affixes; asking with no exclusions detects a - // target whose only derivations carry NOSUGGEST, SUBSTANDARD or FORBIDDENWORD. Spend + // target that may carry NOSUGGEST, SUBSTANDARD or FORBIDDENWORD. An eligible exact + // compound derivation still counts, but a lowercase fallback must not rescue it. Spend // the same shared suggestion budget as the normal checker, and abstain if it runs out. match self.simple_word_budgeted(&target, Excluded::default(), true) { None => return false, - Some(true) if !self.simple_word(&target, self.excluded(true)) => return false, + Some(true) if !self.contains_except(&target, self.excluded(true)) => return false, _ => {} } self.can_suggest(changed) diff --git a/crates/proof/src/affix_suggest.rs b/crates/proof/src/affix_suggest.rs index 4d8bfea59..2a102c00b 100644 --- a/crates/proof/src/affix_suggest.rs +++ b/crates/proof/src/affix_suggest.rs @@ -822,6 +822,20 @@ mod tests { assert!(!d.can_suggest_cased("normal", "pour")); } + /// An excluded simple entry does not exclude an eligible exact COMPOUNDRULE derivation. + #[test] + fn rep_keeps_eligible_exact_compound_beside_an_excluded_simple_entry() { + for flag in ["N", "S", "F"] { + let aff = "SET UTF-8\nNOSUGGEST N\nSUBSTANDARD S\nFORBIDDENWORD F\nCOMPOUNDRULE ab\nREP 1\nREP zz foobar\n"; + let d = AffixDict::from_hunspell(aff, &format!("3\nfoobar/{flag}\nfoo/a\nbar/b\n"), &[]).unwrap(); + for d in [&d, &AffixDict::from_bytes(&d.to_bytes().unwrap()).unwrap()] { + assert_eq!(d.contains_suggestible("foobar"), flag != "F", "{flag}: exact compound eligibility"); + let got = suggest_in(d, "zz", 4, &Tuning::DEFAULT); + assert_eq!(got.iter().any(|w| w == "foobar"), flag != "F", "{flag}: {got:?}"); + } + } + } + /// A language's tables come after its dictionary's, a TRY alphabet stands in for a missing TRY /// line, and a split rule decides which missing spaces are offered. #[test] From 30e5deb660ee195fe713f2fee973f5764b956339 Mon Sep 17 00:00:00 2001 From: Call4han Date: Mon, 16 Nov 2026 21:19:24 -0500 Subject: [PATCH 06/56] fix(xfl): read ZIPs with overstated central directory sizes --- crates/xfl/src/lib.rs | 13 +++++++++++++ crates/xfl/src/tests.rs | 17 +++++++++++++++++ 2 files changed, 30 insertions(+) diff --git a/crates/xfl/src/lib.rs b/crates/xfl/src/lib.rs index fbcb3ecc2..7283b56a0 100644 --- a/crates/xfl/src/lib.rs +++ b/crates/xfl/src/lib.rs @@ -318,6 +318,19 @@ fn find_end(data: &[u8]) -> Result<(u64, u64, u64, usize), ZipError> { let Some((_, shift)) = locate_directory(data, count.into(), size.into(), offset.into(), candidate) .filter(|&(dir, _)| directory_is_exact(data, dir, size.into(), count.into(), &mut directory_jumps)) else { + // An overstated size is safe to ignore only when the recorded entries fill + // the byte range from the declared offset to this single-disk end record. + // The classic entry count is below MAX_ENTRIES, so the walk checks every entry. + if count != 0 + && u32_at(data, candidate + 4) == Some(0) + && u16_at(data, candidate + 8) == Some(count) + && let Ok(start) = usize::try_from(offset) + && let Some(measured) = candidate.checked_sub(start).and_then(|n| u32::try_from(n).ok()) + && measured < size + && directory_is_exact(data, start, measured.into(), count.into(), &mut directory_jumps) + { + return Ok((count.into(), measured.into(), offset.into(), candidate)); + } continue; }; if count == 0 && shift > 0 { diff --git a/crates/xfl/src/tests.rs b/crates/xfl/src/tests.rs index 5ae0713ba..5611a92ca 100644 --- a/crates/xfl/src/tests.rs +++ b/crates/xfl/src/tests.rs @@ -108,6 +108,23 @@ fn damaged_archives_are_errors() { assert!(Archive::open(&z).is_err()); } +#[test] +fn reads_a_directory_with_an_overstated_size() { + let mut z = zip(&[("DOMDocument.xml", b"", true), ("LIBRARY/ball.xml", b"", false)]); + let end = z.len() - 22; + let size = u32_at(&z, end + 12).unwrap(); + z[end + 12..end + 16].copy_from_slice(&(size + 13).to_le_bytes()); + + let archive = Archive::open(&z).unwrap(); + assert_eq!(archive.counts().0, 2); + assert_eq!(archive.read("DOMDocument.xml").unwrap().unwrap(), b""); + assert_eq!(archive.read("LIBRARY/ball.xml").unwrap().unwrap(), b""); + + // Keep the overstated end record but remove the last byte of the final entry's name. + z.remove(end - 1); + assert_eq!(Archive::open(&z).err(), Some(ZipError::Damaged("the central directory is outside the archive"))); +} + #[test] fn a_truncated_central_directory_is_damaged() { let z = zip(&[("DOMDocument.xml", b"", true), ("b.xml", b"", true), ("c.xml", b"", false)]); From 841e6a726ba4aba563cc0ed9c1465c8345502666 Mon Sep 17 00:00:00 2001 From: Call4han Date: Mon, 16 Nov 2026 21:35:57 -0500 Subject: [PATCH 07/56] fix(xfl): prefer valid ZIP end records over recovered ones --- crates/xfl/src/lib.rs | 13 +++++++++++-- crates/xfl/src/tests.rs | 26 ++++++++++++++++++++++++++ 2 files changed, 37 insertions(+), 2 deletions(-) diff --git a/crates/xfl/src/lib.rs b/crates/xfl/src/lib.rs index 7283b56a0..f89ec10fe 100644 --- a/crates/xfl/src/lib.rs +++ b/crates/xfl/src/lib.rs @@ -279,6 +279,7 @@ fn find_end(data: &[u8]) -> Result<(u64, u64, u64, usize), ZipError> { // it from an empty EOCD-shaped record inside the preceding archive's comment. Keep it as a // last resort while searching for an older, structurally stronger candidate. let mut empty_sfx = None; + let mut measured_directory = None; let mut fallback = None; // Fake EOCD records in a comment can all describe the same large directory. Cache binary // directory jumps so checking each candidate does not rescan every entry. @@ -329,7 +330,9 @@ fn find_end(data: &[u8]) -> Result<(u64, u64, u64, usize), ZipError> { && measured < size && directory_is_exact(data, start, measured.into(), count.into(), &mut directory_jumps) { - return Ok((count.into(), measured.into(), offset.into(), candidate)); + // Keep scanning for a valid declared size. Among measured candidates, + // prefer the earliest record so a copy in its comment cannot hide it. + measured_directory = Some((count.into(), measured.into(), offset.into(), candidate)); } continue; }; @@ -341,7 +344,13 @@ fn find_end(data: &[u8]) -> Result<(u64, u64, u64, usize), ZipError> { eocd = Some(candidate); break; } - let eocd = eocd.or(empty_sfx).or(fallback).ok_or(ZipError::NotZip)?; + let eocd = eocd.or(empty_sfx); + if eocd.is_none() + && let Some(directory) = measured_directory + { + return Ok(directory); + } + let eocd = eocd.or(fallback).ok_or(ZipError::NotZip)?; let field16 = |o: usize| u16_at(data, eocd + o).ok_or(ZipError::Damaged("the end record is cut short")); let field32 = |o: usize| u32_at(data, eocd + o).ok_or(ZipError::Damaged("the end record is cut short")); let (disk, dir_disk, on_disk, count) = (field16(4)?, field16(6)?, field16(8)?, field16(10)?); diff --git a/crates/xfl/src/tests.rs b/crates/xfl/src/tests.rs index 5611a92ca..6075e4e57 100644 --- a/crates/xfl/src/tests.rs +++ b/crates/xfl/src/tests.rs @@ -323,6 +323,32 @@ fn nonempty_comment_eocd_candidate_does_not_mask_valid_archive() { assert_eq!(archive.read("a.xml").unwrap().unwrap(), b"x"); } +#[test] +fn overstated_comment_eocd_does_not_mask_valid_archive() { + let mut bytes = zip(&[("a.xml", b"x", false)]); + let end = bytes.len() - 22; + let size = u32_at(&bytes, end + 12).unwrap(); + let start = u32_at(&bytes, end + 16).unwrap() as usize; + let fake_start = bytes.len(); + + // Copy the directory and end record into the real comment, then corrupt the copies. + bytes.extend_from_within(start..); + let comment_len = u16::try_from(bytes.len() - fake_start).unwrap(); + bytes[end + 20..end + 22].copy_from_slice(&comment_len.to_le_bytes()); + bytes[fake_start + 42..fake_start + 46].copy_from_slice(&1u32.to_le_bytes()); + let fake_end = bytes.len() - 22; + bytes[fake_end + 12..fake_end + 16].copy_from_slice(&(size + 1).to_le_bytes()); + bytes[fake_end + 16..fake_end + 20].copy_from_slice(&u32::try_from(fake_start).unwrap().to_le_bytes()); + + let archive = Archive::open(&bytes).unwrap(); + assert_eq!(archive.read("a.xml").unwrap().unwrap(), b"x"); + + // If both candidates need recovery, the record before the comment still wins. + bytes[end + 12..end + 16].copy_from_slice(&(size + 1).to_le_bytes()); + let archive = Archive::open(&bytes).unwrap(); + assert_eq!(archive.read("a.xml").unwrap().unwrap(), b"x"); +} + #[test] fn repeated_eocd_directory_candidates_reuse_entry_validation() { let entries = (0..1024).map(|index| Raw::new(&format!("entry-{index:04}.xml"), b"", false)).collect::>(); From 976e4ef8ea3315f066bdfe65bdfa6e313caa196c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 16 Nov 2026 19:01:57 -0800 Subject: [PATCH 08/56] craft-csv: rows of empty cells decide the delimiter when nothing else does sniff_delimiter skipped every record without a non-whitespace character other than the delimiter, so a record such as ";" or ";;;" was blank to the semicolon candidate. A semicolon export of a sheet whose only value is far down (B40001) starts with 40,000 ";" rows, which fill the 64 KiB sample, and the file was read as comma-separated with one column. Records that hold only a candidate's delimiters and whitespace are now kept apart, at most 20 per candidate. When no candidate separates the records with other text, the same rules pick among the candidates whose sample holds only such records. Every result that did not fall back to comma stays the same: a row of tabs alone is still blank to the other candidates and does not outweigh them, as #1209 set out. --- crates/csv/README.md | 2 +- crates/csv/src/lib.rs | 122 +++++++++++++++++++++++++++++++++++++----- 2 files changed, 110 insertions(+), 14 deletions(-) diff --git a/crates/csv/README.md b/crates/csv/README.md index bfd525c8c..8fd264d4c 100644 --- a/crates/csv/README.md +++ b/crates/csv/README.md @@ -11,7 +11,7 @@ mapping a SYLK sheet onto a document are the caller's work. | Function | What it does | |---|---| | `decode_text(bytes)` | UTF-8 and UTF-16 byte order marks; without one, valid UTF-8 is kept; other bytes are Windows-1256 when they read as Arabic, else Windows-1252 | -| `sniff_delimiter(text, quote)` | comma, semicolon or tab: the one with the most consistent field count over the first 20 non-blank records in a 64 KiB sample; when no candidate finds coherent complete records with a delimiter in each, a candidate that finds no complete record counts the delimiters of the first record up to the end of the sample, or up to a quoted field still open there, and a quote inside a field that does not start with one makes that record incoherent; quote boundaries must be coherent, and ties prefer tab, comma, then semicolon | +| `sniff_delimiter(text, quote)` | comma, semicolon or tab: the one with the most consistent field count over the first 20 records with other text in a 64 KiB sample; when none separates those records, the candidates whose records hold only their delimiters and whitespace (rows of empty cells) are compared the same way, leaving out any candidate that found a record with other text; when no candidate finds coherent complete records with a delimiter in each, a candidate that finds no complete record with other text counts the delimiters of the first such record up to the end of the sample, or up to a quoted field still open there (after its rows of empty cells, a record without its delimiter is left out), and a quote inside a field that does not start with one makes that record incoherent; quote boundaries must be coherent, and ties prefer tab, comma, then semicolon | | `parse_records(text, delim, quote, max_fields, on_record)` | records of fields, one callback per record (return `false` to stop); CR, LF and CRLF line ends; quoted fields with doubled quotes and line breaks; a quote in the middle of a field is text | | `records(text, delim, quote, max_records, max_fields)` | the same, collected | | `push_field(out, field, delim)`, `field_len(field, delim)` | one field as written, quoted only when it holds the delimiter, a quote or a line break; its exact length, to enforce a size cap before writing | diff --git a/crates/csv/src/lib.rs b/crates/csv/src/lib.rs index 70f6148a6..395ad2152 100644 --- a/crates/csv/src/lib.rs +++ b/crates/csv/src/lib.rs @@ -33,13 +33,17 @@ pub use decode::{decode_text, decode_utf8}; /// Picks comma, semicolon or tab by consistent field counts in the first non-blank records. /// Quotes start only at a candidate field boundary; candidates with incoherent quoted fields /// are discarded when another coherent candidate separates the records. Ties prefer tab, -/// then comma, then semicolon. Comma is the fallback when no candidate separates the text. +/// then comma, then semicolon. When no candidate separates the records that hold other text, +/// the same rules pick among the candidates whose records hold only their delimiters and +/// whitespace, such as an exported row of empty cells; a candidate that finds a record with +/// other text is left out of that pick. Comma is the fallback when neither pick finds one. /// Only the first 64 KiB are read. A record cut off at the end of that sample is left out, /// except when no candidate finds coherent complete records with a delimiter in each. Then a candidate -/// that finds no complete record counts the delimiters read so far in the first record, and that -/// record is incoherent when it has a quote inside a field that does not start with one. When one -/// of those candidates ends the sample inside a quoted field, each of them counts only up to that -/// field's opening quote. +/// that finds no complete record with other text counts the delimiters read so far in the first +/// such record, unless it found rows of its empty cells and that record has none of its +/// delimiters. That record is incoherent when it has a quote inside a field that does not start +/// with one. When one of those candidates ends the sample inside a quoted field, each of them +/// counts only up to that field's opening quote. pub fn sniff_delimiter(text: &str, quote: char) -> u8 { const SAMPLE_BYTES: usize = 64 * 1024; let mut sample_end = text.len().min(SAMPLE_BYTES); @@ -64,7 +68,15 @@ pub fn sniff_delimiter(text: &str, quote: char) -> u8 { (scan.count, scan.record_has_content, scan.record_coherent, scan.record_bare_quote) = (before_cut.count, before_cut.record_has_content, before_cut.record_coherent, before_cut.record_bare_quote); } - if scan.record_has_content { + if scan.delimiter_only_counts.is_empty() { + if scan.record_has_content { + scan.coherent &= scan.record_coherent && !scan.record_bare_quote; + scan.counts.push(scan.count); + } else { + scan.push_delimiter_only_record(); + } + } else if scan.record_has_content && scan.count > 0 { + // After rows of empty cells, a cut record without this delimiter is left out. scan.coherent &= scan.record_coherent && !scan.record_bare_quote; scan.counts.push(scan.count); } @@ -79,6 +91,8 @@ pub fn sniff_delimiter(text: &str, quote: char) -> u8 { } else if scan.record_has_content { scan.coherent &= scan.record_coherent; scan.counts.push(scan.count); + } else { + scan.push_delimiter_only_record(); } } } @@ -86,23 +100,34 @@ pub fn sniff_delimiter(text: &str, quote: char) -> u8 { } fn pick_delimiter(scans: [DelimiterScan; 3]) -> u8 { - let candidates = - scans.map(|scan| (scan.delimiter, scan.counts.iter().copied().min().unwrap_or(0), scan.counts.iter().sum::(), scan.coherent)); + let with_text = scans.each_ref().map(|scan| (scan.delimiter, scan.counts.as_slice(), scan.coherent)); + // Records of delimiters alone have no quotes, so they are coherent. + let delimiters_only = + scans.each_ref().map(|scan| (scan.delimiter, if scan.counts.is_empty() { scan.delimiter_only_counts.as_slice() } else { &[] }, true)); + best_delimiter(with_text).or_else(|| best_delimiter(delimiters_only)).unwrap_or(b',') +} + +fn best_delimiter(candidates: [(u8, &[usize], bool); 3]) -> Option { + let candidates = candidates + .map(|(delimiter, counts, coherent)| (delimiter, counts.iter().copied().min().unwrap_or(0), counts.iter().sum::(), coherent)); let prefer_coherent = candidates.iter().any(|(_, min, _, coherent)| *min > 0 && *coherent); - let mut best = (b',', 0usize, 0usize); + let mut best: Option<(u8, usize, usize)> = None; for (delimiter, min, total, coherent) in candidates { - if min > 0 && (!prefer_coherent || coherent) && (min, total) > (best.1, best.2) { - best = (delimiter, min, total); + if min > 0 && (!prefer_coherent || coherent) && best.is_none_or(|(_, best_min, best_total)| (min, total) > (best_min, best_total)) { + best = Some((delimiter, min, total)); } } - best.0 + best.map(|(delimiter, _, _)| delimiter) } /// One candidate delimiter's pass over the sample in [`sniff_delimiter`]. struct DelimiterScan { delimiter: u8, - /// Delimiter counts of the complete non-blank records, at most 20. + /// Delimiter counts of the complete records that hold other text, at most 20. counts: Vec, + /// Delimiter counts of the complete records that hold only this candidate's delimiters and + /// whitespace, at most 20. They do not count toward the 20 records above. + delimiter_only_counts: Vec, /// Whether every counted record had coherent quoted fields. coherent: bool, reached_record_limit: bool, @@ -117,10 +142,21 @@ struct DelimiterScan { open_quote: Option, } +impl DelimiterScan { + /// Keeps the open record's delimiter count when the record has no other text and at least + /// one delimiter. + fn push_delimiter_only_record(&mut self) { + if !self.record_has_content && self.count > 0 && self.delimiter_only_counts.len() < 20 { + self.delimiter_only_counts.push(self.count); + } + } +} + fn scan_delimiter(sample: &str, delimiter: u8, quote: char) -> DelimiterScan { let mut scan = DelimiterScan { delimiter, counts: Vec::new(), + delimiter_only_counts: Vec::new(), coherent: true, reached_record_limit: false, count: 0, @@ -158,6 +194,8 @@ fn scan_delimiter(sample: &str, delimiter: u8, quote: char) -> DelimiterScan { scan.reached_record_limit = true; break; } + } else { + scan.push_delimiter_only_record(); } scan.count = 0; after_quote = false; @@ -403,6 +441,64 @@ mod tests { assert_eq!(sniff_delimiter(&format!("a,b,c;\"hello,\";d\n{}", "x;y;z\n".repeat(12_000)), '"'), b';'); } + // A sheet whose only value is far down exports rows of empty cells that fill the whole sample. + #[test] + fn delimiter_sniffing_reads_a_sparse_semicolon_export() { + assert_eq!(sniff_delimiter(&format!("{};7\n", ";\n".repeat(40_000)), '"'), b';'); + } + + #[test] + fn delimiter_sniffing_reads_a_sparse_semicolon_export_with_crlf() { + assert_eq!(sniff_delimiter(&format!("{};7\r\n", ";\r\n".repeat(40_000)), '"'), b';'); + } + + #[test] + fn delimiter_sniffing_reads_a_sparse_tab_export() { + assert_eq!(sniff_delimiter(&format!("{}\t7\r\n", "\t\r\n".repeat(40_000)), '"'), b'\t'); + } + + #[test] + fn delimiter_sniffing_reads_a_short_file_of_empty_semicolon_cells() { + assert_eq!(sniff_delimiter(";;\n;;\n", '"'), b';'); + assert_eq!(sniff_delimiter(";;\r\n;;", '"'), b';'); + } + + #[test] + fn delimiter_sniffing_reads_empty_semicolon_cells_padded_with_whitespace() { + assert_eq!(sniff_delimiter(&"; ; \n".repeat(20_000), '"'), b';'); + } + + #[test] + fn delimiter_sniffing_reads_a_first_record_of_empty_cells_longer_than_the_sample() { + assert_eq!(sniff_delimiter(&format!("{}\n1;2\n", ";".repeat(70_000)), '"'), b';'); + } + + #[test] + fn delimiter_sniffing_leaves_out_a_cut_record_after_a_row_of_empty_cells() { + assert_eq!(sniff_delimiter(&format!(";\n{};7\n", "x".repeat(70_000)), '"'), b';'); + } + + #[test] + fn delimiter_sniffing_counts_a_long_record_after_a_row_of_empty_cells() { + // Delimiters inside the long record's quoted field are text for every candidate. + assert_eq!(sniff_delimiter(&format!("\t\nname\t\"{}\"\n", "x,y".repeat(30_000)), '"'), b'\t'); + assert_eq!(sniff_delimiter(&format!(";\nname;\"{}\"\n", "x,y\t".repeat(20_000)), '"'), b';'); + } + + #[test] + fn delimiter_sniffing_lets_records_with_text_outweigh_records_of_delimiters_alone() { + // Rows of tabs alone are blank to the other candidates and do not outweigh them. + assert_eq!(sniff_delimiter(&format!("{}a;b\nc;d\n", "\t\n".repeat(25)), '"'), b';'); + assert_eq!(sniff_delimiter(&format!("{}a;b\nc;d\n", "\t\t\n".repeat(25)), '"'), b';'); + // The same holds for a record with text cut off at the end of the sample. + assert_eq!(sniff_delimiter(&format!("\t\n{}", "x;".repeat(40_000)), '"'), b';'); + // A candidate with a record of other text is judged on those records alone. + assert_eq!(sniff_delimiter(&format!("title\n{}", ";\n".repeat(25)), '"'), b','); + // Rows of empty cells in a comma file; comma is also the fallback. + assert_eq!(sniff_delimiter("a,b,c,d\n,,,\n,,,\n1,2,3,4\n", '"'), b','); + assert_eq!(sniff_delimiter(&format!("{}x;y\n", ",,,\n".repeat(20_000)), '"'), b','); + } + #[test] fn parser_stops_collecting_fields_at_the_cap() { let (max, extra) = (16_384usize, 50); From 8d5b02457ef0986742465cf69aefeb4dd1d2e7c8 Mon Sep 17 00:00:00 2001 From: r31lin <257763872+r31lin@users.noreply.github.com> Date: Tue, 17 Nov 2026 12:21:21 +0100 Subject: [PATCH 09/56] document-bundle: turn a non-zip file away after four bytes in read_preview_from The zip reader searches a whole file for an end-of-directory record before it gives up on a file that isn't a zip. DesignCraft reads the preview of every recent file this way before the start screen's first frame: 2.6 s for a local 110 MB InDesign document, 43 s on a network share. read_preview_from now checks the zip local-file header first. Fixes #2031 --- crates/document-bundle/src/lib.rs | 48 ++++++++++++++++++++++++++++++- 1 file changed, 47 insertions(+), 1 deletion(-) diff --git a/crates/document-bundle/src/lib.rs b/crates/document-bundle/src/lib.rs index 70a960a1f..845381f30 100644 --- a/crates/document-bundle/src/lib.rs +++ b/crates/document-bundle/src/lib.rs @@ -316,8 +316,19 @@ pub fn read_preview(bytes: &[u8], preview_entry: &str) -> Option> { } /// Read a bounded preview from a seekable file without loading the full bundle into memory. -pub fn read_preview_from(reader: R, preview_entry: &str) -> Option> { +/// +/// A file that does not start with a zip local-file header is turned away after four bytes. The zip +/// reader would otherwise search the whole file for an end-of-directory record it does not have, +/// which takes seconds for a large non-bundle file (an InDesign document in a recent-files list) +/// and minutes on a network share. +pub fn read_preview_from(mut reader: R, preview_entry: &str) -> Option> { const PREVIEW_LIMIT: u64 = 4 << 20; + let mut magic = [0u8; 4]; + reader.read_exact(&mut magic).ok()?; + if &magic != b"PK\x03\x04" { + return None; + } + reader.seek(std::io::SeekFrom::Start(0)).ok()?; let mut zip = zip::ZipArchive::new(reader).ok()?; let entry = zip.by_name(preview_entry).ok()?; if entry.size() > PREVIEW_LIMIT { @@ -409,6 +420,41 @@ mod tests { assert_eq!(read_preview(&bytes, SPEC.preview_entry).as_deref(), Some(&b"png"[..])); } + /// Counts the bytes read through it. + struct Counting { + inner: R, + read: usize, + } + + impl Read for Counting { + fn read(&mut self, buf: &mut [u8]) -> std::io::Result { + let n = self.inner.read(buf)?; + self.read += n; + Ok(n) + } + } + + impl Seek for Counting { + fn seek(&mut self, pos: std::io::SeekFrom) -> std::io::Result { + self.inner.seek(pos) + } + } + + #[test] + fn preview_from_a_reader_reads_a_bundle() { + let bytes = write(br#"{}"#, 4, "Test 0.1", Some(b"png"), &[], &[], SPEC).unwrap(); + assert_eq!(read_preview_from(Cursor::new(&bytes), SPEC.preview_entry).as_deref(), Some(&b"png"[..])); + } + + #[test] + fn preview_from_a_non_zip_reads_only_its_signature() { + let mut file = Counting { inner: Cursor::new(vec![0x42u8; 1 << 20]), read: 0 }; + assert_eq!(read_preview_from(&mut file, SPEC.preview_entry), None); + assert!(file.read <= 4, "read {} bytes of a file that is not a zip", file.read); + let mut empty = Counting { inner: Cursor::new(Vec::new()), read: 0 }; + assert_eq!(read_preview_from(&mut empty, SPEC.preview_entry), None); + } + #[test] fn extracts_legacy_inline_assets() { let loaded = read(br#"{"assetData":{"7":"AQID"},"name":"x"}"#, 4, SPEC).unwrap(); From 9ab8aac5ca01d34fca12bcb5a84679b155d1e2c7 Mon Sep 17 00:00:00 2001 From: Bra1nZ <95569966+Bra1nZ@users.noreply.github.com> Date: Tue, 17 Nov 2026 17:41:20 +0300 Subject: [PATCH 10/56] craft-docx: a package-wide XML element budget bounds hostile files' tree memory --- crates/docx/src/lib.rs | 4 +- crates/docx/src/package.rs | 135 +++++++++++++++++++- crates/docx/src/read.rs | 12 +- crates/docx/src/read/chunk.rs | 165 ++++++++++++++++++++++++- crates/docx/src/xml.rs | 65 +++++++--- crates/docx/tests/it/element_budget.rs | 44 +++++++ crates/docx/tests/it/main.rs | 1 + 7 files changed, 391 insertions(+), 35 deletions(-) create mode 100644 crates/docx/tests/it/element_budget.rs diff --git a/crates/docx/src/lib.rs b/crates/docx/src/lib.rs index c3c3e8df3..68d41ab4d 100644 --- a/crates/docx/src/lib.rs +++ b/crates/docx/src/lib.rs @@ -3,8 +3,8 @@ //! [`read`] turns a `.docx` package into a [`craft_wordmodel::Document`]; [`write`] does the //! reverse. Both are written from the public specification. The reader is lenient (unknown //! markup is skipped, bad numbers fall back to defaults) and bounded (zip entry sizes, total -//! decompressed size, XML depth and element counts are capped), so hostile input yields an -//! error or a best-effort document, never a panic. +//! decompressed size, XML depth, element counts per part and a package-wide element budget are +//! capped), so hostile input yields an error or a best-effort document, never a panic. #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] // The code came from an app whose lints allow this. #![allow(clippy::type_complexity)] diff --git a/crates/docx/src/package.rs b/crates/docx/src/package.rs index 3c7f45d94..6f90f56ba 100644 --- a/crates/docx/src/package.rs +++ b/crates/docx/src/package.rs @@ -1,5 +1,6 @@ //! OPC package access: bounded zip reading, relationships, part names. +use std::cell::Cell; use std::collections::{BTreeMap, HashMap}; use std::sync::Arc; @@ -216,6 +217,14 @@ fn opc_error(e: craft_opc::Error) -> DocxError { /// document keeps as it is (a picture, an embedded object) is handed over rather than copied. pub struct Package { opc: craft_opc::Package, + /// Elements this package's XML parts may still be parsed into. Every XML part read through + /// [`Package::xml`] charges it, so a file of many parts each inside the per-part cap builds + /// bounded tree memory in total — a chart part with no series builds a maximal tree for + /// almost no graphic work, and the trees the reader keeps accumulate. + budget: Cell, + /// What [`Package::reset_budget`] restores: the cap the package was opened with (the default, + /// or a smaller one from [`Package::open_limited_within`]). + budget_cap: usize, } impl Package { @@ -227,8 +236,16 @@ impl Package { /// `max_total` (counting entries that fail their checksum), is an error. A damaged entry is /// left out with a logged warning. pub fn open_limited(bytes: &[u8], max_part: u64, max_total: u64) -> Result { + Package::open_limited_within(bytes, max_part, max_total, xml::MAX_ELEMENTS_TOTAL) + } + + /// [`open_limited`] with an XML element budget of its own (nested documents share their + /// container's, tests use a small one). + pub fn open_limited_within(bytes: &[u8], max_part: u64, max_total: u64, max_elements: usize) -> Result { let limits = craft_opc::Limits::new(MAX_ENTRIES, max_part, max_total); - craft_opc::Package::open(bytes, &limits).map(|opc| Package { opc }).map_err(opc_error) + craft_opc::Package::open(bytes, &limits) + .map(|opc| Package { opc, budget: Cell::new(max_elements), budget_cap: max_elements }) + .map_err(opc_error) } /// The bytes of all its parts. @@ -244,7 +261,27 @@ impl Package { /// A package from parts already in memory (a Flat OPC file, a converted document), by part /// name without the leading `/`. pub fn from_parts(files: BTreeMap>) -> Package { - Package { opc: craft_opc::Package::from_parts(files) } + Package { opc: craft_opc::Package::from_parts(files), budget: Cell::new(xml::MAX_ELEMENTS_TOTAL), budget_cap: xml::MAX_ELEMENTS_TOTAL } + } + + /// Start a read's element budget over: the budget is per read, not per package's lifetime. + pub(crate) fn reset_budget(&self) { + self.budget.set(self.budget_cap); + } + + /// The XML elements left of the package's budget: nested documents open within it. + pub(crate) fn elements_left(&self) -> usize { + self.budget.get() + } + + /// Charge `count` elements a parsed part built against the budget. + pub(crate) fn charge(&self, count: usize) -> Result<(), DocxError> { + let left = self.budget.get(); + if count > left { + return Err(DocxError::Limit(format!("{count} XML elements, {left} left of the package's {} budget", self.budget_cap))); + } + self.budget.set(left - count); + Ok(()) } /// Part bytes by name (leading `/` ignored; case-insensitive). @@ -261,14 +298,28 @@ impl Package { /// [`Package::xml`] for the main document part: malformed XML is an error, not a truncated read. pub fn xml_strict(&self, name: &str) -> Result, DocxError> { match self.get(name) { - Some(b) => xml::parse_strict(b).map(Some), + Some(b) => { + // The parser stops at the remaining budget or the per-part cap, whichever is less: + // a part over what is left of the package's budget is refused before the whole + // per-part tree is built. + let (el, count) = xml::parse_strict_counted(b, self.budget.get().min(xml::MAX_ELEMENTS))?; + self.charge(count)?; + Ok(Some(el)) + } None => Ok(None), } } + /// A package part as a parsed XML tree, charged against the element budget: the parser + /// stops at what is left of the budget or the per-part cap, whichever is less, and the + /// count it built is charged after. A lenient read: malformed XML is a truncated one. pub fn xml(&self, name: &str) -> Result, DocxError> { match self.get(name) { - Some(b) => xml::parse(b).map(Some), + Some(b) => { + let (el, count) = xml::parse_counted(b, self.budget.get().min(xml::MAX_ELEMENTS))?; + self.charge(count)?; + Ok(Some(el)) + } None => Ok(None), } } @@ -448,6 +499,82 @@ mod tests { let junk = EmbeddedManifest::parse(b"R\tnope\trId1\tk\tt\tI\nP\tonly-two\n\t\t\n\xff\xfe"); assert!(junk.parts.is_empty()); } + + /// A file of many parts each inside the per-part cap is bounded in total: every XML part + /// read through the package charges a package-wide budget, and a part over it is skipped + /// (warned), never built. A chart part with no series builds a maximal tree for almost no + /// graphic work, so the trees a reader keeps would otherwise accumulate one per part. + #[test] + fn the_xml_element_budget_is_package_wide() { + let ns = r#"xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main""#; + let rels = r#""#; + let document = format!(r#""#); + let dense = |root: &str| format!(r#"<{root} {ns}>{}"#, "".repeat(900)); + let z = zip_of(&[ + ("word/document.xml", document.into_bytes()), + ("word/_rels/document.xml.rels", rels.as_bytes().to_vec()), + ("word/styles.xml", dense("w:styles").into_bytes()), + ("word/numbering.xml", dense("w:numbering").into_bytes()), + ]); + let pkg = Package::open_limited_within(&z, MAX_PART, MAX_TOTAL, 1_000).unwrap(); + // styles (900 elements) reads; numbering (900 more) is over what is left and is skipped + // with a warning, not built. + let read = || crate::read::read_opened(&pkg, None); + let (first, warned) = crate::test_log::warnings(read); + assert!(first.is_ok(), "{:?}", first.err()); + let refused: Vec<_> = warned.iter().filter(|w| w.contains("numbering") && w.contains("XML element")).collect(); + assert_eq!(refused.len(), 1, "{warned:?}"); + // The budget is per read: a second read starts it over and behaves the same. + let (second, warned) = crate::test_log::warnings(read); + assert!(second.is_ok(), "{:?}", second.err()); + assert_eq!(warned.iter().filter(|w| w.contains("numbering") && w.contains("XML element")).count(), 1, "{warned:?}"); + } + + /// The main document part itself is strict: over the budget it is an error, not a + /// best-effort read of a tree the file then paid for. + #[test] + fn a_main_part_over_the_element_budget_is_refused() { + let ns = r#"xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main""#; + let document = format!(r#"{}"#, "".repeat(20)); + let z = zip_of(&[("word/document.xml", document.into_bytes())]); + let pkg = Package::open_limited_within(&z, MAX_PART, MAX_TOTAL, 10).unwrap(); + assert!(matches!(crate::read::read_opened(&pkg, None), Err(DocxError::Limit(_)))); + } + + /// A part over what is left of the package's budget is refused while parsing, not after the + /// whole per-part tree is built: the parser stops at the remaining budget or the per-part + /// cap, whichever is less, so the file pays for at most what is left of the budget. + #[test] + fn a_part_over_the_remaining_budget_is_refused_while_parsing() { + let ns = r#"xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main""#; + let document = format!(r#"{}"#, "".repeat(200)); + let z = zip_of(&[("word/document.xml", document.into_bytes())]); + // 200 elements: inside the per-part cap, over the package's 100 budget. The parse + // refuses at the budget, so the error is the parse's, not the charge's, and names + // the effective limit for this parse (the remaining budget), not the whole budget. + let pkg = Package::open_limited_within(&z, MAX_PART, MAX_TOTAL, 100).unwrap(); + let e = crate::read::read_opened(&pkg, None).expect_err("refused"); + assert_eq!(e, DocxError::Limit("over the XML element budget for this parse: at most 100 elements".into())); + } + + /// A part parsed earlier shrinks what is left of the budget: the next part is refused while + /// parsing at the remaining, not at the whole budget, and the error names the effective limit + /// for this parse (the remaining), not the package's budget. + #[test] + fn an_earlier_part_reduces_the_remaining_budget_the_next_part_names_it() { + let ns = r#"xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main""#; + let styles = format!(r#"{}"#, "".repeat(60)); + let settings = format!(r#"{}"#, "".repeat(60)); + let z = zip_of(&[("word/styles.xml", styles.into_bytes()), ("word/settings.xml", settings.into_bytes())]); + // 100 elements of budget. The styles part parses (the main-part path: `xml_strict`) and + // charges its 61 elements, leaving 39. + let pkg = Package::open_limited_within(&z, MAX_PART, MAX_TOTAL, 100).unwrap(); + pkg.xml_strict("word/styles.xml").unwrap(); + // The settings part needs 61 elements, over the 39 left and under the per-part cap: the + // parse refuses at the remaining, so the error names 39, not the package's 100 budget. + let e = pkg.xml("word/settings.xml").expect_err("refused"); + assert_eq!(e, DocxError::Limit("over the XML element budget for this parse: at most 39 elements".into())); + } } #[cfg(test)] diff --git a/crates/docx/src/read.rs b/crates/docx/src/read.rs index 746225e97..18c9ea47a 100644 --- a/crates/docx/src/read.rs +++ b/crates/docx/src/read.rs @@ -154,9 +154,11 @@ pub(crate) fn read_opened(pkg: &Package, chunks: Option) -> Resul read_opened_in(pkg, ChunkState::new(chunks)).map(|(doc, ..)| doc) } -/// [`read_opened`] with what chunks may still bring in; also gives the chunks, chunk bytes and -/// graphic work left of that. -fn read_opened_in(pkg: &Package, chunks: ChunkState) -> Result<(Document, usize, u64, usize), DocxError> { +/// [`read_opened`] with what chunks may still bring in; also gives the chunks, chunk bytes, +/// graphic work and XML elements left of that. +fn read_opened_in(pkg: &Package, chunks: ChunkState) -> Result<(Document, usize, u64, usize, usize), DocxError> { + // The budget is per read, so a package read twice (tests, a Flat OPC conversion) starts over. + pkg.reset_budget(); let root_rels = pkg.rels(""); let main = root_rels.by_type(rt::OFFICE_DOC).filter(|r| !r.external).map(|r| r.target.clone()).unwrap_or_else(|| "word/document.xml".to_string()); let Some(root) = pkg.xml_strict(&main)? else { @@ -371,11 +373,11 @@ fn read_opened_in(pkg: &Package, chunks: ChunkState) -> Result<(Document, usize, if r.shape_ids { keep_glued_ids(&mut r.doc, &r.glued); } - let (left, bytes, graphic) = (r.chunks.left, r.chunks.bytes, r.chunks.graphic); + let (left, bytes, graphic, elements) = (r.chunks.left, r.chunks.bytes, r.chunks.graphic, pkg.elements_left()); let mut doc = r.doc; doc.skipped_parts.extend(pkg.skipped().iter().cloned()); doc.ensure_nonempty(); - Ok((doc, left, bytes, graphic)) + Ok((doc, left, bytes, graphic, elements)) } /// Most move ranges open at once, and most move names tracked, per file. diff --git a/crates/docx/src/read/chunk.rs b/crates/docx/src/read/chunk.rs index 2dc1674a7..9bdde064d 100644 --- a/crates/docx/src/read/chunk.rs +++ b/crates/docx/src/read/chunk.rs @@ -110,11 +110,17 @@ impl Reader<'_> { log::warn!("docx: alternative format chunks nest deeper than {MAX_CHUNK_NESTING}; the inner ones are left out"); return None; } - let pkg = - Package::open_limited(bytes, MAX_PART, self.chunks.bytes).map_err(|e| log::warn!("docx: unreadable nested document chunk: {e}")).ok()?; + // The nested document shares the file's element budget: open_limited_within, not a + // fresh cap — nesting goes deep, so 5 packages each getting 16M is the OOM class the + // budget exists for. The container's own parse spent part of the chain, so the cap is + // the lesser of the chain and what the container has left. + let cap = self.chunks.elements.min(self.pkg.elements_left()); + let pkg = Package::open_limited_within(bytes, MAX_PART, self.chunks.bytes, cap) + .map_err(|e| log::warn!("docx: unreadable nested document chunk: {e}")) + .ok()?; self.chunks.bytes = self.chunks.bytes.saturating_sub(pkg.size()); let state = ChunkState { nesting: self.chunks.nesting + 1, depth: depth + 1, ..self.chunks }; - let (doc, left, bytes, graphic) = match super::read_opened_in(&pkg, state) { + let (doc, left, bytes, graphic, elements) = match super::read_opened_in(&pkg, state) { Ok(read) => read, Err(e) => { log::warn!("docx: unreadable nested document chunk: {e}"); @@ -125,6 +131,16 @@ impl Reader<'_> { self.chunks.left = left; self.chunks.bytes = bytes; self.chunks.graphic = graphic; + self.chunks.elements = elements; + // The nested document's XML usage comes out of the container's budget too: a later + // sibling chunk and the container's own remaining parts parse against what is left + // of it. The charge can't refuse: the cap is the lesser of the file's remaining + // elements and what the container has left, and the container's budget doesn't move + // while the nested read goes. + let spent = cap.saturating_sub(elements); + if let Err(e) = self.pkg.charge(spent) { + log::warn!("docx: nested document chunk outspent the container's element budget: {e}"); + } Some(doc) } } @@ -139,6 +155,9 @@ pub(crate) struct ChunkState<'a> { /// Graphic work left in the file's budget ([`super::MAX_GRAPHIC_WORK`]): nested documents' /// charts and diagrams count against it too. pub graphic: usize, + /// XML elements left in the file's budget: nested packages share their container's + /// ([`crate::xml::MAX_ELEMENTS_TOTAL`]), not one of their own. + pub elements: usize, /// How deep in nested WordprocessingML chunks this reader is. pub nesting: u8, /// The XML depth its stories start at (a nested document's: that of the chunk naming it). @@ -148,7 +167,15 @@ pub(crate) struct ChunkState<'a> { impl<'a> ChunkState<'a> { pub fn new(import: Option>) -> Self { - ChunkState { left: MAX_CHUNKS, bytes: MAX_TOTAL, graphic: super::MAX_GRAPHIC_WORK, nesting: 0, depth: 0, import } + ChunkState { + left: MAX_CHUNKS, + bytes: MAX_TOTAL, + graphic: super::MAX_GRAPHIC_WORK, + elements: crate::xml::MAX_ELEMENTS_TOTAL, + nesting: 0, + depth: 0, + import, + } } } @@ -198,8 +225,8 @@ mod tests { let outer = package(r#""#, ("rIdC", "aFChunk", "afchunk.docx"), ("word/afchunk.docx", &inner)); let pkg = Package::open(&outer).unwrap(); let read = |graphic| { - let (d, .., left) = super::super::read_opened_in(&pkg, ChunkState { graphic, ..ChunkState::new(None) }).unwrap(); - (drawn(&d), left) + let (d, .., work, _) = super::super::read_opened_in(&pkg, ChunkState { graphic, ..ChunkState::new(None) }).unwrap(); + (drawn(&d), work) }; let (shown, left) = read(super::super::MAX_GRAPHIC_WORK); assert!(shown); @@ -207,4 +234,130 @@ mod tests { // With the file's budget spent, the nested document doesn't get one of its own. assert_eq!(read(0), (false, 0)); } + + /// A package whose body is `body`, with the document relationships `rels` (id, type, target) + /// and the parts `(name, bytes)` they name. + fn package_parts(body: &str, rels: &[(&str, &str, &str)], parts: &[(&str, &[u8])]) -> Vec { + let ns = r#"xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:wp="http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing" xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main""#; + let rels_xml = + |inner: &str| format!(r#"{inner}"#); + let rel = |(id, ty, target): &(&str, &str, &str)| { + format!(r#""#) + }; + let names: String = rels.iter().map(rel).collect::>().join(""); + let mut files: Vec<(&str, Vec)> = vec![ + ("_rels/.rels", rels_xml(&rel(&("rId1", "officeDocument", "word/document.xml"))).into_bytes()), + ("word/document.xml", format!(r#"{body}"#).into_bytes()), + ("word/_rels/document.xml.rels", rels_xml(&names).into_bytes()), + ]; + files.extend(parts.iter().map(|(name, bytes)| (*name, bytes.to_vec()))); + let mut zw = zip::ZipWriter::new(std::io::Cursor::new(Vec::new())); + for (name, bytes) in files { + zw.start_file(name, zip::write::SimpleFileOptions::default()).unwrap(); + zw.write_all(&bytes).unwrap(); + } + zw.finish().unwrap().into_inner() + } + + /// Whether the body holds a paragraph with `s`. + fn has(d: &Document, s: &str) -> bool { + d.body.iter().any(|b| b.as_para().map(|p| p.text.contains(s)).unwrap_or(false)) + } + + #[test] + fn a_nested_documents_elements_come_out_of_the_files_budget() { + // Three levels: the outer's altChunk names the inner, whose altChunk names the + // innermost. The chain spends down: the inner's own parse charges the file's budget, + // so the innermost opens with what the inner has left, not a fresh cap. + let innermost = package(r#"innermost"#, ("rIdZ", "chart", "charts/z.xml"), ("word/charts/z.xml", b"")); + let inner = package( + r#"inner"#, + ("rIdD", "aFChunk", "afchunk.docx"), + ("word/afchunk.docx", &innermost), + ); + let outer = package(r#""#, ("rIdC", "aFChunk", "afchunk.docx"), ("word/afchunk.docx", &inner)); + let pkg = Package::open(&outer).unwrap(); + let read = |elements| { + let (d, ..) = super::super::read_opened_in(&pkg, ChunkState { elements, ..ChunkState::new(None) }).unwrap(); + (has(&d, "inner"), has(&d, "innermost")) + }; + // With room, both levels flow in. + assert_eq!(read(crate::xml::MAX_ELEMENTS_TOTAL), (true, true)); + // The inner's own parse (its rels, then its main part) charged the file's budget: the + // innermost is left out instead of getting one of its own (before this, each nested + // package started with the full 16M). + assert_eq!(read(10), (true, false)); + } + + #[test] + fn a_nested_documents_elements_charge_the_container() { + // The nested document's XML usage comes out of the container's budget too: the cap + // the nested package was given, minus its returned remainder, is charged, so the + // container's remaining parts parse against what is left of the shared cap — not a + // budget that ignores the chunk. + let nested = package(r#"inner"#, ("rIdZ", "chart", "charts/z.xml"), ("word/charts/z.xml", b"")); + let body = r#"after"#; + let with = package(&format!(r#"{body}"#), ("rIdC", "aFChunk", "afchunk.docx"), ("word/afchunk.docx", &nested)); + let without = package(body, ("rIdZ", "chart", "charts/z.xml"), ("word/charts/z.xml", b"")); + let read = |outer: &[u8]| { + let pkg = Package::open(outer).unwrap(); + let (d, ..) = super::super::read_opened_in(&pkg, ChunkState { elements: 10, ..ChunkState::new(None) }).unwrap(); + (has(&d, "inner"), pkg.elements_left()) + }; + let (inner_in, charged) = read(&with); + assert!(inner_in); + let (_, base) = read(&without); + assert!(charged < base, "the nested document's usage is the container's: {charged} of {base}"); + } + + #[test] + fn a_grandchilds_reservation_charges_every_level() { + // Three levels: the innermost's reservation comes out of the inner's budget, and the + // inner's out of the outer's — the chain charges every container, so the outer's + // remainder is smaller with the deeper chain than with a shallow one. + let innermost = package(r#"leaf"#, ("rIdZ", "chart", "charts/z.xml"), ("word/charts/z.xml", b"")); + let inner = package( + r#"mid"#, + ("rIdD", "aFChunk", "afchunk.docx"), + ("word/afchunk.docx", &innermost), + ); + let outer = package(r#""#, ("rIdC", "aFChunk", "afchunk.docx"), ("word/afchunk.docx", &inner)); + let pkg = Package::open(&outer).unwrap(); + let (d, .., elements) = super::super::read_opened_in(&pkg, ChunkState::new(None)).unwrap(); + assert!(has(&d, "mid"), "the inner document didn't flow in"); + assert!(has(&d, "leaf"), "the innermost document didn't flow in"); + // The same container with a shallow chain: one reservation instead of two. + let shallow = package(r#""#, ("rIdC", "aFChunk", "afchunk.docx"), ("word/afchunk.docx", &innermost)); + let pkg = Package::open(&shallow).unwrap(); + let (.., shallow_elements) = super::super::read_opened_in(&pkg, ChunkState::new(None)).unwrap(); + assert!(elements < shallow_elements, "every level's reservation is charged: {elements} of {shallow_elements}"); + } + + #[test] + fn a_charged_budget_bounds_the_containers_part_and_the_sibling_after_it() { + // The container's budget pays for the parts it parses (the section's header, read + // during the chunk's own walk) and for the chunks after the first one: with a budget + // that fits the grandchild chunk and the header but not the sibling document's XML, + // the sibling is left out; skip the header's charge and it would flow in. + let hdr = r#"headheadhead"#; + let gc = package(r#"gc"#, ("rIdZ", "chart", "charts/z.xml"), ("word/charts/z.xml", b"")); + let sibling = + package(&r#"sibling"#.repeat(8), ("rIdZ", "chart", "charts/z.xml"), ("word/charts/z.xml", b"")); + let inner = package_parts( + r#"mid"#, + &[("rIdD", "aFChunk", "afchunk.docx"), ("rIdH", "header", "header1.xml"), ("rIdS", "aFChunk", "afchunk2.docx")], + &[("word/afchunk.docx", &gc), ("word/header1.xml", hdr.as_bytes()), ("word/afchunk2.docx", &sibling)], + ); + let outer = package(r#""#, ("rIdC", "aFChunk", "afchunk.docx"), ("word/afchunk.docx", &inner)); + let pkg = Package::open(&outer).unwrap(); + let read = |elements| { + let (d, ..) = super::super::read_opened_in(&pkg, ChunkState { elements, ..ChunkState::new(None) }).unwrap(); + (has(&d, "mid"), has(&d, "gc"), has(&d, "sibling")) + }; + // With room, everything flows in. + assert_eq!(read(crate::xml::MAX_ELEMENTS_TOTAL), (true, true, true)); + // The grandchild chunk and the header fit the file's budget; the sibling document's + // XML (8 paragraphs) doesn't, so it's left out instead of getting a fresh cap. + assert_eq!(read(40), (true, true, false)); + } } diff --git a/crates/docx/src/xml.rs b/crates/docx/src/xml.rs index fa50d217a..46da6911d 100644 --- a/crates/docx/src/xml.rs +++ b/crates/docx/src/xml.rs @@ -10,6 +10,10 @@ use crate::DocxError; pub const MAX_DEPTH: usize = 256; /// Maximum number of elements in one part. pub const MAX_ELEMENTS: usize = 8_000_000; +/// Maximum number of elements summed over every part a read parses: a file of many parts each +/// inside [`MAX_ELEMENTS`] would otherwise cost a tree per part, and the trees a reader keeps +/// (the main part's, charts' and diagrams') accumulate. +pub const MAX_ELEMENTS_TOTAL: usize = MAX_ELEMENTS * 2; /// Maximum number of attributes on one element (#3702). pub const MAX_ATTRS: usize = 1024; @@ -329,19 +333,31 @@ pub fn parse(bytes: &[u8]) -> Result { parse_ns(bytes, &[]) } +/// [`parse`], with the number of elements it built, stopping early at `max` elements: the caller +/// charges the count against a package-wide budget (see [`MAX_ELEMENTS_TOTAL`]), and a part over +/// what is left of it is refused before the whole per-part tree is built. +pub fn parse_counted(bytes: &[u8], max: usize) -> Result<(El, usize), DocxError> { + parse_with(bytes, &[], false, max) +} + +/// [`parse_counted`], strict, for a part whose loss would be silent data loss (the main +/// document): a mismatched end tag or an element left open at the end of the data is an error, +/// not a cue to stop reading. +pub fn parse_strict_counted(bytes: &[u8], max: usize) -> Result<(El, usize), DocxError> { + parse_with(bytes, &[], true, max) +} + /// [`parse`] with `extra` namespaces (prefix, URI) mapped to canonical prefixes first, so a /// related vocabulary (WordprocessingML 2003) reads with the prefixes the reader knows. pub fn parse_ns(bytes: &[u8], extra: &[(&'static str, &str)]) -> Result { - parse_with(bytes, extra, false) + parse_with(bytes, extra, false, MAX_ELEMENTS).map(|(e, _)| e) } -/// [`parse`] for a part whose loss would be silent data loss (the main document): a mismatched end -/// tag or an element left open at the end of the data is an error, not a cue to stop reading. -pub fn parse_strict(bytes: &[u8]) -> Result { - parse_with(bytes, &[], true) -} - -fn parse_with(bytes: &[u8], extra: &[(&'static str, &str)], strict: bool) -> Result { +/// The XML parser everything else goes through: transcodes UTF-16, walks the events and builds +/// the tree depth-first, stopping at `max` elements and counting the ones it built. A mismatched +/// end tag or an element left open at the end of the data is an error when `strict`, a cue to +/// stop reading when not. +fn parse_with(bytes: &[u8], extra: &[(&'static str, &str)], strict: bool, max: usize) -> Result<(El, usize), DocxError> { let namespaces: Vec<(&str, &str)> = extra.iter().copied().chain(NAMESPACES.iter().copied()).chain(OTHER_NAMESPACES.iter().copied()).chain(STRICT.iter().copied()).collect(); // The prefix of an element: its namespace's, with two exceptions for Strict documents @@ -375,7 +391,9 @@ fn parse_with(bytes: &[u8], extra: &[(&'static str, &str)], strict: bool) -> Res max_depth: MAX_DEPTH + 1, // Text stretches count as nodes too: two for each element. max_nodes: 2 * MAX_ELEMENTS, - max_elements: MAX_ELEMENTS, + // The parse stops here before the whole tree is built: a part over what is left of the + // package's element budget pays for at most that, not for the per-part cap. + max_elements: max, max_attrs: MAX_ATTRS, max_attrs_total: 2 * MAX_ELEMENTS, }; @@ -383,17 +401,27 @@ fn parse_with(bytes: &[u8], extra: &[(&'static str, &str)], strict: bool) -> Res if strict { options = options.strict(); } - let root = options.parse(bytes).map_err(|e| if e.is_limit() { DocxError::Limit(e.to_string()) } else { DocxError::Xml(e.to_string()) })?; - Ok(from_tree(root)) + let root = options.parse(bytes).map_err(|e| match &e { + craft_xml::Error::TooManyElements(_) => DocxError::Limit(format!("over the XML element budget for this parse: at most {max} elements")), + e if e.is_limit() => DocxError::Limit(e.to_string()), + e => DocxError::Xml(e.to_string()), + })?; + Ok(from_tree_counted(root)) } -/// The `craft-xml` tree as this module's (whose shape the reader was written against). +/// The `craft-xml` tree as this module's (whose shape the reader was written against), with the +/// number of elements the subtree holds (the caller charges it against a package-wide budget). // shortcut: one copy of each parsed part; read craft_xml::El directly when the reader is ported to it. -fn from_tree(e: craft_xml::El) -> El { +fn from_tree_counted(e: craft_xml::El) -> (El, usize) { let mut kids = Vec::with_capacity(e.children.len()); + let mut count = 1usize; for n in e.children { match n { - craft_xml::Node::El(c) => kids.push(Node::El(from_tree(c))), + craft_xml::Node::El(c) => { + let (kid, built) = from_tree_counted(c); + count += built; + kids.push(Node::El(kid)); + } craft_xml::Node::Text(t) | craft_xml::Node::CData(t) => match kids.last_mut() { Some(Node::Text(prev)) => prev.push_str(&t), _ => kids.push(Node::Text(t)), @@ -401,7 +429,7 @@ fn from_tree(e: craft_xml::El) -> El { craft_xml::Node::Pi { .. } | craft_xml::Node::Comment(_) => {} } } - El { name: e.name, attrs: e.attrs, kids } + (El { name: e.name, attrs: e.attrs, kids }, count) } /// This module's tree as `craft-xml`'s, for the shared readers (`craft-drawingml`, `craft-math`) @@ -515,12 +543,13 @@ mod tests { fn strict_parsing_rejects_a_dropped_entity_and_trailing_markup() { let bad = [&b"before &unknown; after"[..], b"", b""]; for xml in bad { - assert!(parse_strict(xml).is_err(), "{}", String::from_utf8_lossy(xml)); + assert!(parse_strict_counted(xml, MAX_ELEMENTS).is_err(), "{}", String::from_utf8_lossy(xml)); } assert!( - parse_strict( + parse_strict_counted( b"x & y -" +", + MAX_ELEMENTS ) .is_ok() ); diff --git a/crates/docx/tests/it/element_budget.rs b/crates/docx/tests/it/element_budget.rs new file mode 100644 index 000000000..6b220ae7c --- /dev/null +++ b/crates/docx/tests/it/element_budget.rs @@ -0,0 +1,44 @@ +//! The package-wide XML element budget: a file of many parts each inside the per-part +//! cap reads bounded, where every part used to build its own tree and the trees the +//! reader keeps accumulated. + +use crate::fixtures; +use craft_docx::read; + +const W_NS: &str = r#"xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships""#; + +#[test] +fn a_file_of_element_budget_parts_still_reads() { + // Nine chart parts of 2M elements each: 18M over the package's 16M budget. The later + // parts are skipped with a warning instead of built, and the file still reads. Before + // the budget, every part's whole tree was parsed and the chart trees stayed cached for + // the whole read (~230 MB per 2M-element part, measured), so a file like this cost one + // tree per part and scales linearly with the part count. + let parts = 9usize; + let chunk = "".repeat(2_000_000); + let chart_xml = format!(r#"{chunk}"#); + let mut document = format!( + r#""# + ); + for i in 0..parts { + document.push_str(&format!( + r#""# + )); + } + document.push_str(""); + let mut rels = String::from(r#""#); + for i in 0..parts { + rels.push_str(&format!( + r#""# + )); + } + rels.push_str(""); + let mut entries: Vec<(&str, Vec)> = vec![("word/document.xml", document.into_bytes()), ("word/_rels/document.xml.rels", rels.into_bytes())]; + for i in 0..parts { + entries.push((Box::leak(format!("word/charts/chart{i}.xml").into_boxed_str()), chart_xml.clone().into_bytes())); + } + let refs: Vec<(&str, &[u8])> = entries.iter().map(|(n, b)| (*n, b.as_slice())).collect(); + let z = fixtures::zip(&refs); + let doc = read(&z).expect("a file over the element budget still reads, the extra parts skipped"); + assert_eq!(doc.body.len(), parts, "the document's own paragraphs read"); +} diff --git a/crates/docx/tests/it/main.rs b/crates/docx/tests/it/main.rs index 926cb5154..942d946ae 100644 --- a/crates/docx/tests/it/main.rs +++ b/crates/docx/tests/it/main.rs @@ -16,6 +16,7 @@ mod default_size; mod drawing_payload; mod east_asian_lang; mod east_asian_layout; +mod element_budget; mod emphasis_marks; mod fixtures; mod font_table; From 09938cd99e9189890ace95006de4c6fc2211e468 Mon Sep 17 00:00:00 2001 From: Mauro Mazzieri Date: Tue, 17 Nov 2026 15:53:20 +0000 Subject: [PATCH 11/56] craft-rtf: page fields show each page's number Ported from storytold/wordcraft#6264 (issue storytold/wordcraft#6222), written before the RTF reader moved here. A PAGE, NUMPAGES, SECTIONPAGES, SECTION or PAGEREF field whose result is plain text in one formatting comes in as a field, with its lock, so the layout works out the number; \chpgn is a PAGE field and keeps a tracked insertion or deletion; a result whose text was hidden stays as read. --- crates/flow/src/to_doc.rs | 23 ++-- crates/rtf/src/doc.rs | 8 +- crates/rtf/src/doc/field.rs | 144 ++++++++++++++++++++ crates/rtf/src/doc/reader.rs | 6 + crates/rtf/src/doc/tests_fields.rs | 208 +++++++++++++++++++++++++++++ crates/rtf/src/doc/text.rs | 36 +++-- crates/rtf/src/doc/word.rs | 8 +- 7 files changed, 409 insertions(+), 24 deletions(-) create mode 100644 crates/rtf/src/doc/field.rs create mode 100644 crates/rtf/src/doc/tests_fields.rs diff --git a/crates/flow/src/to_doc.rs b/crates/flow/src/to_doc.rs index 0375c448c..8d9d4dca3 100644 --- a/crates/flow/src/to_doc.rs +++ b/crates/flow/src/to_doc.rs @@ -284,6 +284,18 @@ impl<'a> Builder<'a> { /// `cp` as a run may keep it: without its link and font once the runs' copies of them are /// over budget. + /// A run's properties with its tracked insertion, deletion and formatting change. + fn tracked_props(&mut self, f: &Fmt) -> CharProps { + let mut cp = self.budget(char_props(f)); + cp.ins = f.ins.as_ref().map(|m| self.revision(RevisionKind::Insert, m)); + cp.del = f.del.as_ref().map(|m| self.revision(RevisionKind::Delete, m)); + if let Some(c) = &f.fmt_change { + let old = self.budget(char_props(&c.old)); + cp.fmt_change = PropChange::boxed(self.revision(RevisionKind::Format, &c.mark), old); + } + cp + } + fn budget(&mut self, mut cp: CharProps) -> CharProps { let n = cp.link.as_ref().map_or(0, String::len).saturating_add(cp.font.as_ref().map_or(0, String::len)); match self.run_strings.checked_add(n).filter(|&t| t <= MAX_RUN_STRINGS) { @@ -553,13 +565,7 @@ impl<'a> Builder<'a> { match i { Inline::Text(t, f) => { let t = clean_text(t); - let mut cp = self.budget(char_props(f)); - cp.ins = f.ins.as_ref().map(|m| self.revision(RevisionKind::Insert, m)); - cp.del = f.del.as_ref().map(|m| self.revision(RevisionKind::Delete, m)); - if let Some(c) = &f.fmt_change { - let old = self.budget(char_props(&c.old)); - cp.fmt_change = PropChange::boxed(self.revision(RevisionKind::Format, &c.mark), old); - } + let mut cp = self.tracked_props(f); if p.kind == Kind::Code { // Code's font comes from its style, before a change as after it. if cp.font.as_deref() == Some(MONO_FONT) { @@ -633,7 +639,8 @@ impl<'a> Builder<'a> { } } Inline::Field { instr, result, fmt, locked } => { - let cp = self.budget(char_props(fmt)); + // A field inserted or deleted with tracked changes keeps them (RTF `\chpgn`). + let cp = self.tracked_props(fmt); let (instr, result) = (clean_text(instr), clean_text(result)); if instr.trim().is_empty() { append(&mut out, &result, &cp, None); diff --git a/crates/rtf/src/doc.rs b/crates/rtf/src/doc.rs index 77254151f..0426a4b7a 100644 --- a/crates/rtf/src/doc.rs +++ b/crates/rtf/src/doc.rs @@ -22,7 +22,10 @@ //! code page's bytes stream through one decoder, so a lead byte and its trail byte decode //! together and a run that looks like a UTF-8 BOM is not mistaken for one; the formatting words //! above, stylesheet-based -//! headings and `\outlinelevel`, lists through `\ls`/`\ilvl`, fields, bookmarks, pictures and +//! headings and `\outlinelevel`, lists through `\ls`/`\ilvl`, fields (in `import`, a page field +//! such as `PAGE` or `NUMPAGES` whose result is plain text in one paragraph stays a field, +//! `\fldlock` locking it, and `\chpgn` is a `PAGE` field; otherwise a field is its result's text), +//! bookmarks, pictures and //! tables, footnotes, endnotes (`\footnote` with `\ftnalt`) and comments (author, initials, date, //! text, the commented range). Group nesting, picture sizes and the number of notes and comments //! are capped. Not kept: custom note marks, comment replies (`\atnparent`), notes inside @@ -38,6 +41,7 @@ use craft_flow::{self as model, Cell, FBlock, FTable, Flow, Fmt, Inline, Kind, L use crate::date; mod export; +mod field; mod parse; mod reader; mod state; @@ -58,3 +62,5 @@ use word::hyperlink; #[cfg(test)] mod tests; +#[cfg(test)] +mod tests_fields; diff --git a/crates/rtf/src/doc/field.rs b/crates/rtf/src/doc/field.rs new file mode 100644 index 000000000..78d5f7d81 --- /dev/null +++ b/crates/rtf/src/doc/field.rs @@ -0,0 +1,144 @@ +//! Page fields kept as fields (#6222). The reader writes a field's result (`\fldrslt`) into the +//! paragraph like any text, which for a page number is the number Word last stored. When the +//! group of a field the layout works out from where it lands closes (`PAGE`, `NUMPAGES`, +//! `SECTIONPAGES`, `SECTION`, `PAGEREF`), a result that is plain text in one formatting, in the +//! paragraph the field started in, is replaced by an [`Inline::Field`] holding the instruction +//! (`\fldinst`) and that result, as for a DOCX field. Any other field, a result over several +//! paragraphs or formats, or one holding pictures or other objects stays what the reader made of +//! it: a field's result is drawn as one piece that does not wrap, so a long `MERGEFIELD` result +//! in a narrow table cell would overflow it. Only `import` keeps fields: `parse`, the flow +//! reader, reads their results as text. + +use super::reader::Reader; +use super::state::Dest; +use super::{Fmt, Inline}; + +/// The open fields read so far; deeper nesting keeps its results as text. +const MAX_OPEN: usize = 32; + +/// A field being read in the body text. +pub(super) struct OpenField { + /// The depth of the `{\field` group. + depth: usize, + /// Its instruction, in [`Reader::fields`]. + index: usize, + /// The paragraph it started in ([`Reader::para_seq`]). + para: u64, + /// The paragraph's inlines when it started, and the length of the last one when that was + /// text: a result in the same formatting runs on in that text. + start: usize, + tail_from: Option, + /// Its result group was met in the text (not inside another field's instruction). + result: bool, + locked: bool, + /// Hidden text of its result was left out: the result is not what showed. + hidden: bool, +} + +impl Reader { + /// `\field`, after its instruction slot is made: note where its result starts. + pub(super) fn open_field(&mut self) { + // Hidden text drops the result: the field stays hidden with it. + if !self.marks_on || self.st.dest != Dest::Body || self.st.hidden || self.open_fields.len() >= MAX_OPEN { + return; + } + let Some(index) = self.st.field else { return }; + let tail_from = match self.para.inlines.last() { + Some(Inline::Text(t, _)) => Some(t.len()), + _ => None, + }; + let (depth, para, start) = (self.depth(), self.para_seq, self.para.inlines.len()); + self.open_fields.push(OpenField { depth, index, para, start, tail_from, result: false, locked: false, hidden: false }); + } + + /// `\fldrslt` and `\fldlock`, read in a field's group. + pub(super) fn field_word(&mut self, w: &str) { + let (depth, field, body) = (self.depth(), self.st.field, self.st.dest == Dest::Body); + let Some(f) = self.open_fields.last_mut() else { return }; + match w { + "fldrslt" if body && field == Some(f.index) && depth == f.depth + 1 => f.result = true, + "fldlock" if depth == f.depth => f.locked = true, + _ => {} + } + } + + /// `\chpgn`, the current page number: a `PAGE` field. + pub(super) fn page_number_symbol(&mut self) { + if self.marks_on && self.st.dest == Dest::Body && !self.st.hidden { + // Tracked like text, so Accept and Reject apply to it. + let fmt = self.text_fmt(); + self.para.inlines.push(Inline::Field { instr: "PAGE".into(), result: String::new(), fmt, locked: false }); + self.para_has = true; + } + } + + /// Hidden text left out of the body: an open field's result is then not what showed, and the + /// field is left as read rather than made a field that would show. + pub(super) fn hidden_text_dropped(&mut self) { + if let Some(f) = self.open_fields.last_mut() + && f.result + { + f.hidden = true; + } + } + + /// A group closes: if it is an open field's, make the field. + pub(super) fn close_field_group(&mut self) { + if self.open_fields.last().is_none_or(|f| f.depth != self.depth()) { + return; + } + let Some(f) = self.open_fields.pop() else { return }; + if !f.result || f.hidden || f.para != self.para_seq { + return; + } + let instr = self.fields.get(f.index).map_or("", |s| s.trim()); + if !page_dependent(instr) { + return; + } + let Some((result, fmt)) = result_text(&self.para.inlines, &f, &self.st.fmt) else { return }; + let field = Inline::Field { instr: instr.to_string(), result, fmt, locked: f.locked }; + let inlines = &mut self.para.inlines; + inlines.truncate(f.start); + if let (Some(n), Some(Inline::Text(t, _))) = (f.tail_from, inlines.last_mut()) { + t.truncate(n); + } + inlines.push(field); + self.para_has = true; + } +} + +/// A field whose result the layout works out from the page it lands on. `STYLEREF` is not one +/// here: the layout looks its style up by name, and a running head whose style the RTF names +/// differently would show an error instead of Word's text. +fn page_dependent(instr: &str) -> bool { + let name = instr.split_whitespace().next().unwrap_or(""); + ["PAGE", "NUMPAGES", "SECTIONPAGES", "SECTION", "PAGEREF"].iter().any(|n| name.eq_ignore_ascii_case(n)) +} + +/// The text the field's result added to the paragraph and its formatting, when that is plain +/// text in one formatting with no tracked change; `None` otherwise. An empty result takes the +/// field group's formatting. +fn result_text(inlines: &[Inline], f: &OpenField, group: &Fmt) -> Option<(String, Fmt)> { + if inlines.len() < f.start { + return None; + } + let mut runs: Vec<(&str, &Fmt)> = Vec::new(); + if let Some(n) = f.tail_from { + let Some(Inline::Text(t, fmt)) = f.start.checked_sub(1).and_then(|i| inlines.get(i)) else { return None }; + let tail = t.get(n..)?; + if !tail.is_empty() { + runs.push((tail, fmt)); + } + } + for i in inlines.get(f.start..)? { + match i { + Inline::Text(t, fmt) => runs.push((t, fmt)), + _ => return None, + } + } + match runs.as_slice() { + [] => Some((String::new(), group.clone())), + [(t, fmt)] if fmt.ins.is_none() && fmt.del.is_none() && fmt.fmt_change.is_none() => Some(((*t).to_string(), (*fmt).clone())), + _ => None, + } +} diff --git a/crates/rtf/src/doc/reader.rs b/crates/rtf/src/doc/reader.rs index c0cc1c1ea..4c8a8b652 100644 --- a/crates/rtf/src/doc/reader.rs +++ b/crates/rtf/src/doc/reader.rs @@ -56,6 +56,10 @@ pub(super) struct Reader { pub(super) ov_list: i32, pub(super) ov_ls: i32, pub(super) fields: Vec, + /// The fields being read in the text, innermost last (`import` only). + pub(super) open_fields: Vec, + /// Counts the paragraphs ended, so a field knows whether its result stayed in one. + pub(super) para_seq: u64, // Picture being read. pub(super) pict_depth: Option, pub(super) pict_hex: Vec, @@ -344,6 +348,7 @@ impl Reader { if self.sub.as_ref().is_some_and(|s| s.depth == self.depth()) { self.end_sub(); } + self.close_field_group(); let closing = self.st.dest; // Destination-level commits. match closing { @@ -428,6 +433,7 @@ impl Reader { /// End the current paragraph (`\par`, `\cell`). pub(super) fn end_para(&mut self, in_cell: bool) { + self.para_seq += 1; let read = std::mem::take(&mut self.para); let props = self.para_props(&self.st); let mut p = Para { inlines: read.inlines, mark_ins: read.mark_ins, mark_del: read.mark_del, ..props }; diff --git a/crates/rtf/src/doc/tests_fields.rs b/crates/rtf/src/doc/tests_fields.rs new file mode 100644 index 000000000..ae1ab691f --- /dev/null +++ b/crates/rtf/src/doc/tests_fields.rs @@ -0,0 +1,208 @@ +//! Page fields read from RTF (#6222): a page-dependent field whose result is plain text in one +//! paragraph comes in as a field, so the layout works out its number; other fields stay their +//! result's text. Written by hand from the RTF specification's `\field`, `\fldinst`, `\fldrslt`, +//! `\fldlock` and `\chpgn`. + +use super::*; +use craft_wordmodel::para::InlineObject; + +/// The fields of each paragraph of a story, with the paragraph's text. +/// A paragraph's text with its fields (code, result, locked). +type ParaFields = (String, Vec<(String, String, bool)>); + +fn fields_of(blocks: &craft_wordmodel::Blocks) -> Vec { + blocks + .iter() + .filter_map(|b| if let craft_wordmodel::Block::Para(p) = &**b { Some(p) } else { None }) + .map(|p| { + let fields = p + .objects + .iter() + .filter_map(|o| match o { + InlineObject::Field { instr, result, locked, .. } => Some((instr.clone(), result.clone(), *locked)), + _ => None, + }) + .collect(); + (p.text.clone(), fields) + }) + .collect() +} + +fn footer(d: &craft_wordmodel::Document) -> Vec { + let id = d.last_section.footers.default.expect("a footer"); + fields_of(&d.parts[&id].blocks) +} + +#[test] +fn a_page_field_in_the_footer_is_a_field_not_its_stored_number() { + // As Word writes it: the text before the field has the same formatting as its result. + let rtf = br"{\rtf1\ansi\sectd +{\footerr \pard {\fs16 Pag. }{\field{\*\fldinst {\fs16 PAGE }}{\fldrslt {\fs16 2}}}\sectd \ltrsect{\par}} +\pard One\page Two\par}"; + let d = import(rtf).unwrap(); + let f = footer(&d); + assert_eq!(f.len(), 1, "{f:?}"); + assert_eq!(f[0].1, [("PAGE".to_string(), "2".to_string(), false)], "{f:?}"); + // "Pag. " stays text before the field: the result's run did not take it along. + assert!(f[0].0.starts_with("Pag. "), "{f:?}"); + assert_eq!(f[0].0.matches("Pag. ").count(), 1, "{f:?}"); +} + +#[test] +fn page_fields_in_the_body_keep_their_code_result_and_lock() { + let rtf = br#"{\rtf1\ansi +\pard Page {\field{\*\fldinst PAGE \\* roman}{\fldrslt ii}} of {\field\fldlock{\*\fldinst NUMPAGES}{\fldrslt 4}}\par +\pard {\field{\*\fldinst SECTIONPAGES}{\fldrslt }}x\par}"#; + let d = import(rtf).unwrap(); + let f = fields_of(&d.body); + assert_eq!(f[0].1, [("PAGE \\* roman".to_string(), "ii".to_string(), false), ("NUMPAGES".to_string(), "4".to_string(), true)], "{f:?}"); + assert!(f[0].0.starts_with("Page ") && f[0].0.contains(" of "), "{f:?}"); + // An empty result is still a field: the layout fills it in. + assert_eq!(f[1].1, [("SECTIONPAGES".to_string(), String::new(), false)], "{f:?}"); +} + +#[test] +fn other_fields_stay_the_text_of_their_result() { + // A field's result is drawn as one piece that does not wrap: a long merge field in a narrow + // cell keeps its text, which wraps, as before. + let rtf = br#"{\rtf1\ansi +\pard Before {\field{\*\fldinst DATE \\@ "dd/MM/yyyy"}{\fldrslt 11/11/2026}} after\par +\trowd\cellx600\pard\intbl {\field{\*\fldinst MERGEFIELD Approvato}{\fldrslt Presidente della Rete (Rossi Mario)}}\cell\row +\pard {\field{\*\fldinst AUTHOR}{\fldrslt }}x\par}"#; + let d = import(rtf).unwrap(); + let f = fields_of(&d.body); + assert_eq!((f[0].0.as_str(), f[0].1.len()), ("Before 11/11/2026 after", 0), "{f:?}"); + let cell = d.body.iter().find_map(|b| b.as_table()).and_then(|t| t.rows.first()).and_then(|r| r.cells.first()).unwrap(); + let cf = fields_of(&cell.blocks); + assert_eq!((cf[0].0.as_str(), cf[0].1.len()), ("Presidente della Rete (Rossi Mario)", 0), "{cf:?}"); + assert!(f.last().is_some_and(|(t, fl)| t == "x" && fl.is_empty()), "{f:?}"); +} + +#[test] +fn fields_that_cannot_be_one_field_stay_text() { + let rtf = br#"{\rtf1\ansi +\pard {\field{\*\fldinst{HYPERLINK "http://a.b"}}{\fldrslt{link}}}\par +\pard {\field{\*\fldinst TOC \\o "1-3"}{\fldrslt {Heading one\tab 1\par Heading two\tab 2}}}\par +\pard {\field{\*\fldinst PAGEREF a}{\fldrslt {\b 1}2}}\par +\pard {\field{\*\fldinst IF {\field{\*\fldinst PAGE}{\fldrslt 1}} = 1 "one" "many"}{\fldrslt one}}\par +\pard {\field{\*\fldinst PAGE}}\par +\pard {\field{\*\fldinst PAGE}{\fldrslt 1\par 2}}\par}"#; + let d = import(rtf).unwrap(); + let f = fields_of(&d.body); + let texts: Vec<&str> = f.iter().map(|(t, _)| t.as_str()).collect(); + // A link stays a link; a result over two paragraphs or in two formats stays its text. + assert_eq!(&texts[..4], ["link", "Heading one\t1", "Heading two\t2", "12"], "{f:?}"); + // The PAGE inside IF's instruction is part of the code, not a field of the paragraph. + assert_eq!(texts[4], "one", "{f:?}"); + // A field with no result group at all is left as it was (nothing). + assert!(f[5].0.is_empty(), "{f:?}"); + assert_eq!(&texts[6..8], ["1", "2"], "{f:?}"); + assert!(f.iter().all(|(_, fl)| fl.is_empty()), "{f:?}"); +} + +#[test] +fn a_table_of_contents_keeps_its_links_and_its_page_numbers_become_fields() { + // The shape Word writes: the TOC result spans paragraphs; each entry is a link around its + // text and a PAGEREF to the heading's bookmark. + let rtf = br#"{\rtf1\ansi +\pard {\field{\*\fldinst TOC \\o "1-3" \\h}{\fldrslt {\field{\*\fldinst HYPERLINK \\l "_Toc1"}{\fldrslt {One\tab {\field{\*\fldinst PAGEREF _Toc1 \\h}{\fldrslt 3}}}}}\par +{\field{\*\fldinst HYPERLINK \\l "_Toc2"}{\fldrslt {Two\tab {\field{\*\fldinst PAGEREF _Toc2 \\h}{\fldrslt 5}}}}}}}\par +\pard {\*\bkmkstart _Toc1}Heading{\*\bkmkend _Toc1}\par}"#; + let d = import(rtf).unwrap(); + let f = fields_of(&d.body); + assert_eq!(f[0].1, [("PAGEREF _Toc1 \\h".to_string(), "3".to_string(), false)], "{f:?}"); + assert_eq!(f[1].1, [("PAGEREF _Toc2 \\h".to_string(), "5".to_string(), false)], "{f:?}"); + assert!(f[0].0.starts_with("One\t") && f[1].0.starts_with("Two\t"), "{f:?}"); + // The entry text still links to its heading. + let p = d.body[0].as_para().unwrap(); + assert!(p.props_at(0).link.is_some(), "{:?}", p.runs); +} + +#[test] +fn hidden_styleref_tracked_and_object_results_stay_as_read() { + let rtf = br#"{\rtf1\ansi{\*\revtbl{Unknown;}{Ann;}} +\pard a{\v {\field{\*\fldinst PAGE}{\fldrslt 2}}}b\par +\pard {\field{\*\fldinst STYLEREF "heading 1"}{\fldrslt Intro}}\par +\pard {\field{\*\fldinst PAGE}{\fldrslt {\revised\revauth1 2}}}\par +\pard {\field{\*\fldinst PAGE}{\fldrslt A{\*\bkmkstart m}B{\*\bkmkend m}}}\par}"#; + let d = import(rtf).unwrap(); + let f = fields_of(&d.body); + // Hidden: neither the result nor a field. + assert_eq!((f[0].0.as_str(), f[0].1.len()), ("ab", 0), "{f:?}"); + // STYLEREF keeps Word's text. + assert_eq!((f[1].0.as_str(), f[1].1.len()), ("Intro", 0), "{f:?}"); + // A tracked result and one holding a bookmark stay text. + assert_eq!((f[2].0.as_str(), f[2].1.len()), ("2", 0), "{f:?}"); + // (The bookmark's start and end are object characters in the paragraph's text.) + assert_eq!((f[3].0.replace('\u{FFFC}', ""), f[3].1.len()), ("AB".to_string(), 0), "{f:?}"); +} + +#[test] +fn the_page_number_symbol_is_a_page_field() { + let d = import(br"{\rtf1\ansi{\footer \pard Page \chpgn\par}\pard Body\par}").unwrap(); + let f = footer(&d); + assert_eq!(f[0].1, [("PAGE".to_string(), String::new(), false)], "{f:?}"); +} + +#[test] +fn truncated_and_hostile_fields_do_not_crash() { + for rtf in [ + &br"{\rtf1{\field{\*\fldinst PAGE}{\fldrslt 2"[..], + br"{\rtf1{\field{\*\fldinst PAGE}{\fldrslt 2}", + br"{\rtf1{\field\field\field{\*\fldinst PAGE}}}}", + br"{\rtf1{\field{\fldrslt x}{\*\fldinst PAGE}}\par}", + br"{\rtf1 a{\field{\*\fldinst PAGE}{\fldrslt 1\par 2}}\par}", + ] { + let _ = import(rtf); + } + let mut deep = String::from(r"{\rtf1 "); + for _ in 0..300 { + deep.push_str(r"{\field{\*\fldinst PAGE}{\fldrslt "); + } + deep.push('x'); + let _ = import(deep.as_bytes()); +} + +#[test] +fn the_flow_reader_keeps_field_results_as_text() { + // `parse` asks for no fields, as before: the result is the paragraph's text. + let f = parse(br"{\rtf1\ansi\pard Pag. {\field{\*\fldinst PAGE}{\fldrslt 2}}\par}").unwrap(); + match &f.blocks[0] { + FBlock::Para(p) => { + assert!(p.inlines.iter().all(|i| matches!(i, Inline::Text(..))), "{:?}", p.inlines); + assert_eq!(p.text(), "Pag. 2"); + } + b => panic!("{b:?}"), + } +} + +#[test] +fn a_tracked_page_symbol_keeps_its_insertion_and_deletion() { + let rtf = br"{\rtf1\ansi{\*\revtbl{Unknown;}{Ann;}} +\pard Page {\revised\revauth1 \chpgn}\par +\pard Page {\deleted\revauthdel1 \chpgn}\par}"; + let d = import(rtf).unwrap(); + let f = fields_of(&d.body); + assert_eq!(f[0].1.len(), 1, "{f:?}"); + assert_eq!(f[1].1.len(), 1, "{f:?}"); + // Each field sits in a run carrying its tracked change, so Accept and Reject apply to it. + let marked = |i: usize, ins: bool| { + let p = d.body[i].as_para().unwrap(); + p.runs.iter().any(|r| if ins { r.props.ins.is_some() } else { r.props.del.is_some() }) + }; + assert!(marked(0, true), "{:?}", d.body[0].as_para().unwrap().runs); + assert!(marked(1, false), "{:?}", d.body[1].as_para().unwrap().runs); +} + +#[test] +fn a_result_whose_text_is_hidden_inside_it_stays_as_read() { + // `\v` inside the result: what showed was nothing, so no field that would show a number. + let rtf = br"{\rtf1\ansi +\pard x{\field{\*\fldinst PAGE}{\fldrslt \v 2}}y\par +\pard x{\field{\*\fldinst PAGE}{\fldrslt }}y\par}"; + let d = import(rtf).unwrap(); + let f = fields_of(&d.body); + assert_eq!((f[0].0.as_str(), f[0].1.len()), ("xy", 0), "{f:?}"); + // A result that is really empty is still a field. + assert_eq!(f[1].1.len(), 1, "{f:?}"); +} diff --git a/crates/rtf/src/doc/text.rs b/crates/rtf/src/doc/text.rs index dceaef6d0..ad997c680 100644 --- a/crates/rtf/src/doc/text.rs +++ b/crates/rtf/src/doc/text.rs @@ -189,31 +189,39 @@ impl Reader { } } + /// The current formatting with its tracked changes (insertion, deletion, formatting change). + pub(super) fn text_fmt(&mut self) -> Fmt { + let mut f = self.st.fmt.clone(); + let r = self.st.rev; + if r.ins { + f.ins = Some(self.rev_mark(r.auth, r.dttm)); + } + if r.del { + f.del = Some(self.rev_mark(r.authdel, r.dttmdel)); + } + let c = &self.st.chg_c; + if let Some(words) = c.old.clone() { + let mark = self.rev_mark(c.auth, c.date); + let old = self.old_fmt(&words); + f.fmt_change = Some(Box::new(model::FmtChange { mark, old })); + } + f + } + pub(super) fn text(&mut self, s: &str) { match self.st.dest { Dest::Body => { if self.st.hidden { + self.hidden_text_dropped(); return; } - let mut f = self.st.fmt.clone(); if s.contains([MARK_OPEN, MARK_CLOSE]) { + let f = self.st.fmt.clone(); self.para.push_text(&s.replace([MARK_OPEN, MARK_CLOSE], "\u{FFFD}"), &f); self.para_has = true; return; } - let r = self.st.rev; - if r.ins { - f.ins = Some(self.rev_mark(r.auth, r.dttm)); - } - if r.del { - f.del = Some(self.rev_mark(r.authdel, r.dttmdel)); - } - let c = &self.st.chg_c; - if let Some(words) = c.old.clone() { - let mark = self.rev_mark(c.auth, c.date); - let old = self.old_fmt(&words); - f.fmt_change = Some(Box::new(model::FmtChange { mark, old })); - } + let f = self.text_fmt(); self.para.push_text(s, &f); self.para_has = true; } diff --git a/crates/rtf/src/doc/word.rs b/crates/rtf/src/doc/word.rs index 2eb86692f..49367a7d1 100644 --- a/crates/rtf/src/doc/word.rs +++ b/crates/rtf/src/doc/word.rs @@ -75,6 +75,7 @@ impl Reader { "row" => self.end_row(), "line" | "softline" => self.ch('\n'), "tab" => self.ch('\t'), + "chpgn" => self.page_number_symbol(), "page" | "softpage" => self.ch('\u{000C}'), "column" => self.ch('\u{000E}'), "emdash" => self.ch('—'), @@ -283,8 +284,13 @@ impl Reader { self.defs.push(d); } } - "field" => self.start_field(), + "field" => { + self.start_field(); + self.open_field(); + } + "fldlock" => self.field_word(w), "fldrslt" => { + self.field_word(w); let link = self.st.field.and_then(|i| self.fields.get(i)).and_then(|s| hyperlink(s)); if link.is_some() { self.st.fmt.link = link.as_deref().and_then(model::kept_link); From a62ce81f2447b1791a8d8c0aa6317fb6388f189b Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 17 Nov 2026 11:54:40 -0500 Subject: [PATCH 12/56] Expose consuming parsed certificate and revocation components --- crates/pkcs7/src/revocation.rs | 53 ++++++++++++++++++- crates/pkcs7/src/x509.rs | 90 +++++++++++++++++++++++++++++++++ crates/pkcs7/tests/it/crypto.rs | 53 +++++++++++++++++++ 3 files changed, 194 insertions(+), 2 deletions(-) diff --git a/crates/pkcs7/src/revocation.rs b/crates/pkcs7/src/revocation.rs index 0aa9be9c6..dfb398cae 100644 --- a/crates/pkcs7/src/revocation.rs +++ b/crates/pkcs7/src/revocation.rs @@ -63,6 +63,27 @@ pub struct CertificateList { pub revoked: Vec<(Vec, Time)>, } +/// Owned parsed components for adapters. This is not a signature or trust verdict. +/// Consuming conversion moves buffers without reparsing or cloning signed material. +pub struct CertificateListParts { + pub tbs: Vec, + pub sig_alg: Vec, + pub signature: Vec, + pub issuer_raw: Vec, + pub this_update: Time, + pub next_update: Option".repeat(59)); + let mut zip = zip::ZipWriter::new(std::io::Cursor::new(Vec::new())); + zip.start_file("word/document.xml", zip::write::SimpleFileOptions::default()).unwrap(); + zip.write_all(bad_xml.as_bytes()).unwrap(); + let bad = zip.finish().unwrap().into_inner(); + let sibling = package_parts(r#"sibling"#, &[], &[]); + let outer = package_parts( + r#""#, + &[("bad", "aFChunk", "bad.docx"), ("good", "aFChunk", "good.docx")], + &[("word/bad.docx", &bad), ("word/good.docx", &sibling)], + ); + for (cap, included, remaining) in [(69, true, 0), (68, false, 4)] { + let pkg = Package::open_limited_within(&outer, MAX_PART, MAX_TOTAL, cap).unwrap(); + let doc = super::super::read_opened(&pkg, None).unwrap(); + assert_eq!(has(&doc, "sibling"), included, "budget {cap}"); + assert_eq!(pkg.elements_left(), remaining, "budget {cap}"); + } + } } From 4078682a5179b831c73303ff37a24d9b17749cfa Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 18 Nov 2026 01:17:12 -0500 Subject: [PATCH 42/56] mesh: expose strict UTF-8 URI percent decoding --- crates/mesh/src/gltf.rs | 10 ++++++++++ crates/mesh/src/tests/gltf.rs | 29 +++++++++++++++++++++++++++++ 2 files changed, 39 insertions(+) diff --git a/crates/mesh/src/gltf.rs b/crates/mesh/src/gltf.rs index c92051b84..d074f1ed1 100644 --- a/crates/mesh/src/gltf.rs +++ b/crates/mesh/src/gltf.rs @@ -120,6 +120,16 @@ pub fn uri_decode(s: &str) -> String { String::from_utf8_lossy(&percent_decode(s)).into_owned() } +/// Percent-decode a URI, rejecting decoded bytes that are not UTF-8. +/// +/// As with [`uri_decode`], incomplete or non-hex escapes stay literal and `+` stays +/// `+`. This does not validate or confine a filesystem path; callers must retain +/// their own reference policy. Decoding is linear and output is no larger than input. +/// Use this instead of the lossy decoder when a resolver requires exact UTF-8 names. +pub fn uri_decode_strict(s: &str) -> Option { + String::from_utf8(percent_decode(s)).ok() +} + /// [`uri_decode`] as bytes, so escaped bytes that are not UTF-8 survive. fn percent_decode(s: &str) -> Vec { let b = s.as_bytes(); diff --git a/crates/mesh/src/tests/gltf.rs b/crates/mesh/src/tests/gltf.rs index 8892fe241..c47b911df 100644 --- a/crates/mesh/src/tests/gltf.rs +++ b/crates/mesh/src/tests/gltf.rs @@ -950,3 +950,32 @@ fn morph_targets_and_other_scenes_are_named_in_warnings() { let s = parse(&one_mesh(&b, plain.clone())).unwrap(); assert!(s.warnings.is_empty(), "{:?}", s.warnings); } + +#[test] +fn strict_uri_decoding_preserves_exact_names_and_rejects_invalid_utf8() { + use crate::gltf::uri_decode_strict; + for (input, expected) in [ + ("", Some("")), + ("a+b", Some("a+b")), + ("a%20b", Some("a b")), + ("é/%E2%82%AC", Some("é/€")), + ("%", Some("%")), + ("%2", Some("%2")), + ("%GG", Some("%GG")), + ("%252e%252e", Some("%2e%2e")), + ("%2e%2e%2fmesh.bin", Some("../mesh.bin")), + ("%00", Some("\0")), + ("%FF", None), + ("%C0%AF", None), + ("%ED%A0%80", None), + ("%E2%82", None), + ] { + assert_eq!(uri_decode_strict(input).as_deref(), expected, "{input}"); + } + // Keep the existing API's replacement-character behavior unchanged. + assert_eq!(uri_decode("%FF"), "�"); + let input = "%41%GG+é".repeat(100_000); + let decoded = uri_decode_strict(&input).unwrap(); + assert_eq!(decoded, "A%GG+é".repeat(100_000)); + assert!(decoded.len() <= input.len()); +} From 133b15453c0d695db0245776c46feb045e605693 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 18 Nov 2026 01:21:44 -0500 Subject: [PATCH 43/56] fix(rtf): retain hidden-result and empty-field revision state --- crates/rtf/src/doc/field.rs | 22 +++++++++++++++------- crates/rtf/src/doc/tests_fields.rs | 27 +++++++++++++++++++++++++++ 2 files changed, 42 insertions(+), 7 deletions(-) diff --git a/crates/rtf/src/doc/field.rs b/crates/rtf/src/doc/field.rs index 78d5f7d81..ccc12f4cf 100644 --- a/crates/rtf/src/doc/field.rs +++ b/crates/rtf/src/doc/field.rs @@ -64,7 +64,11 @@ impl Reader { /// `\chpgn`, the current page number: a `PAGE` field. pub(super) fn page_number_symbol(&mut self) { - if self.marks_on && self.st.dest == Dest::Body && !self.st.hidden { + if self.st.dest == Dest::Body && self.st.hidden { + self.hidden_text_dropped(); + return; + } + if self.marks_on && self.st.dest == Dest::Body { // Tracked like text, so Accept and Reject apply to it. let fmt = self.text_fmt(); self.para.inlines.push(Inline::Field { instr: "PAGE".into(), result: String::new(), fmt, locked: false }); @@ -75,10 +79,11 @@ impl Reader { /// Hidden text left out of the body: an open field's result is then not what showed, and the /// field is left as read rather than made a field that would show. pub(super) fn hidden_text_dropped(&mut self) { - if let Some(f) = self.open_fields.last_mut() - && f.result - { - f.hidden = true; + // An omitted nested result is also omitted from each enclosing result. + for f in &mut self.open_fields { + if f.result { + f.hidden = true; + } } } @@ -95,8 +100,11 @@ impl Reader { if !page_dependent(instr) { return; } - let Some((result, fmt)) = result_text(&self.para.inlines, &f, &self.st.fmt) else { return }; - let field = Inline::Field { instr: instr.to_string(), result, fmt, locked: f.locked }; + let instr = instr.to_string(); + // An empty result has no run to carry the group's revision marks. + let group = self.text_fmt(); + let Some((result, fmt)) = result_text(&self.para.inlines, &f, &group) else { return }; + let field = Inline::Field { instr, result, fmt, locked: f.locked }; let inlines = &mut self.para.inlines; inlines.truncate(f.start); if let (Some(n), Some(Inline::Text(t, _))) = (f.tail_from, inlines.last_mut()) { diff --git a/crates/rtf/src/doc/tests_fields.rs b/crates/rtf/src/doc/tests_fields.rs index ae1ab691f..4931356e8 100644 --- a/crates/rtf/src/doc/tests_fields.rs +++ b/crates/rtf/src/doc/tests_fields.rs @@ -206,3 +206,30 @@ fn a_result_whose_text_is_hidden_inside_it_stays_as_read() { // A result that is really empty is still a field. assert_eq!(f[1].1.len(), 1, "{f:?}"); } + +#[test] +fn hidden_page_symbols_and_nested_results_do_not_reappear_as_fields() { + for result in [r"{\v\chpgn}", r"{\field{\*\fldinst DATE}{\fldrslt {\v 2}}}"] { + let rtf = format!(r"{{\rtf1\ansi\pard x{{\field{{\*\fldinst PAGE}}{{\fldrslt {result}}}}}y\par}}"); + let d = import(rtf.as_bytes()).unwrap(); + let f = fields_of(&d.body); + assert_eq!(f[0], ("xy".into(), Vec::new()), "{result}: {f:?}"); + } + // A visible nested result remains eligible for conversion by its enclosing PAGE field. + let d = import(br"{\rtf1\ansi{\field{\*\fldinst PAGE}{\fldrslt {\field{\*\fldinst DATE}{\fldrslt 2}}}}\par}").unwrap(); + assert_eq!(fields_of(&d.body)[0].1, [("PAGE".into(), "2".into(), false)]); +} + +#[test] +fn empty_page_fields_keep_insertion_and_deletion_marks() { + for (mark, insertion) in [(r"\revised\revauth1", true), (r"\deleted\revauthdel1", false)] { + let rtf = format!(r"{{\rtf1\ansi{{\*\revtbl{{Unknown;}}{{Ann;}}}}\pard {{{mark}{{\field{{\*\fldinst PAGE}}{{\fldrslt }}}}}}\par}}"); + let d = import(rtf.as_bytes()).unwrap(); + let fields = fields_of(&d.body); + assert_eq!(fields[0].1, [("PAGE".into(), String::new(), false)]); + let p = d.body[0].as_para().unwrap(); + assert_eq!(p.text, "\u{FFFC}", "the sole character is the field marker"); + let props = p.props_at(0); + assert!(if insertion { props.ins.is_some() } else { props.del.is_some() }, "{mark}: {props:?}"); + } +} From 1139798521fa28a0b474ab9c5580edeaf72f822c Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 18 Nov 2026 01:22:10 -0500 Subject: [PATCH 44/56] refactor(pkcs7): define certificate representations from one schema --- crates/pkcs7/src/x509.rs | 126 ++++++++++----------------------------- 1 file changed, 33 insertions(+), 93 deletions(-) diff --git a/crates/pkcs7/src/x509.rs b/crates/pkcs7/src/x509.rs index 5738e9c46..ae8c45fbb 100644 --- a/crates/pkcs7/src/x509.rs +++ b/crates/pkcs7/src/x509.rs @@ -106,9 +106,39 @@ impl Name { } } -/// A parsed certificate. -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct Certificate { +// One field schema keeps the parsed representation and consuming adapter in sync. +// Visibility belongs to Certificate; parts are explicitly unverified public data. +macro_rules! certificate_representations { + ($( $(#[$attr:meta])* $vis:vis $field:ident: $ty:ty, )*) => { + /// A parsed certificate. Signed material remains private until consumed. + /// + /// ```compile_fail + /// fn replace_signed_bytes(cert: &mut craft_pkcs7::x509::Certificate) { + /// cert.tbs.clear(); + /// } + /// ``` + #[derive(Clone, Debug, PartialEq, Eq)] + pub struct Certificate { + $( $(#[$attr])* $vis $field: $ty, )* + } + + /// Owned parsed components for adapters. This is not a signature or trust verdict. + /// Consuming conversion moves buffers without reparsing or cloning signed material. + pub struct CertificateParts { + $( $(#[$attr])* pub $field: $ty, )* + } + + impl Certificate { + /// Move parsed fields into a caller-owned representation; verification remains separate. + pub fn into_parts(self) -> CertificateParts { + let Self { $( $field, )* } = self; + CertificateParts { $( $field, )* } + } + } + }; +} + +certificate_representations! { /// The whole DER encoding. pub raw: Vec, tbs: Vec, @@ -144,96 +174,6 @@ pub struct Certificate { pub unknown_critical: Vec, } -/// Owned parsed components for adapters. This is not a signature or trust verdict. -/// Consuming conversion moves buffers without reparsing or cloning signed material. -pub struct CertificateParts { - /// The whole DER encoding. - pub raw: Vec, - pub tbs: Vec, - pub sig_alg: Vec, - pub signature: Vec, - pub serial: Vec, - pub issuer: Name, - pub subject: Name, - pub not_before: Time, - pub not_after: Time, - pub public_key: PublicKey, - /// Basic constraints: a CA certificate. - pub is_ca: bool, - /// Whether the certificate has a basicConstraints extension at all (old v1 roots don't). - pub has_basic_constraints: bool, - /// Basic constraints `pathLenConstraint`: how many CA certificates may follow this one - /// before the end-entity certificate. - pub path_len: Option, - /// Key usage bits (bit 0 = digitalSignature, 1 = nonRepudiation, 5 = keyCertSign), if present. - pub key_usage: Option, - pub subject_key_id: Option>, - /// Authority key identifier (2.5.29.35), when present. - pub authority_key_id: Option>, - /// Extended key usage OIDs (2.5.29.37), when present. - pub extended_key_usage: Option>, - /// OCSP responder URLs from the Authority Information Access (1.3.6.1.5.5.7.1.1). - pub ocsp_urls: Vec, - /// CRL distribution point URLs (2.5.29.31). - pub crl_urls: Vec, - /// The `version` field: 0 for v1, 1 for v2, 2 for v3. - pub version: u64, - /// OIDs of extensions marked critical that this crate does not process (RFC 5280 §4.2). - pub unknown_critical: Vec, -} - -impl Certificate { - /// Move parsed fields into a caller-owned representation; verification remains separate. - pub fn into_parts(self) -> CertificateParts { - let Self { - raw, - tbs, - sig_alg, - signature, - serial, - issuer, - subject, - not_before, - not_after, - public_key, - is_ca, - has_basic_constraints, - path_len, - key_usage, - subject_key_id, - authority_key_id, - extended_key_usage, - ocsp_urls, - crl_urls, - version, - unknown_critical, - } = self; - CertificateParts { - raw, - tbs, - sig_alg, - signature, - serial, - issuer, - subject, - not_before, - not_after, - public_key, - is_ca, - has_basic_constraints, - path_len, - key_usage, - subject_key_id, - authority_key_id, - extended_key_usage, - ocsp_urls, - crl_urls, - version, - unknown_critical, - } - } -} - /// Extensions this crate reads or may safely ignore when they are critical: the ones /// `Extensions::read` handles, subject/issuer alternative names, and certificate policies /// (accepted as any policy). From 2dc55f434142ce20e4b89c5986199849a65f6f8b Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Wed, 18 Nov 2026 13:35:40 +0700 Subject: [PATCH 45/56] test(texture): make preserved golden float type explicit (#2131) --- crates/texture/src/lib.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/texture/src/lib.rs b/crates/texture/src/lib.rs index 54dffcb17..884488ac6 100644 --- a/crates/texture/src/lib.rs +++ b/crates/texture/src/lib.rs @@ -1124,7 +1124,7 @@ mod tests { let cases = [ (0.3, 0.7, [true, false], [1.473_799_7, -0.072_800_055, 0.645_000_2, 0.733_799_8]), (0.3, 0.7, [false, true], [1.473_799_7, -0.072_800_055, 0.645_000_2, 0.733_799_8]), - (1.2, -0.4, [true, false], [-1.722_999_5, 0.127_000_57, 0.089_999_32, 1.939_999_3]), + (1.2, -0.4, [true, false], [-1.722_999_5, 0.127_000_57, 0.089_999_32_f32, 1.939_999_3]), (1.2, -0.4, [false, true], [-1.057_000_3, -1.094, 0.756_000_1, 2.606_000_2]), (-0.15, 1.1, [true, false], [2.051, -1.76, 0.090_000_15, 1.311_000_1]), (-0.15, 1.1, [false, true], [-1.834_000_6, 0.015_999_317, 0.608_000_5, 2.458_000_7]), From 5ae0786c5bb1206d70c5d26cd3778253deed06b6 Mon Sep 17 00:00:00 2001 From: chasse20 Date: Wed, 18 Nov 2026 01:54:53 -0500 Subject: [PATCH 46/56] Publish MCMAT v3 as a bounded procedural source archive --- crates/mcmat/README.md | 21 +-- crates/mcmat/src/lib.rs | 283 ++++++++++++++++++---------------------- 2 files changed, 133 insertions(+), 171 deletions(-) diff --git a/crates/mcmat/README.md b/crates/mcmat/README.md index 074a0ac44..2f69e68c9 100644 --- a/crates/mcmat/README.md +++ b/crates/mcmat/README.md @@ -1,17 +1,10 @@ # craft-mcmat -A bounded reader and writer for portable MaterialCraft `.mcmat` ZIP packages. A package -contains `material.json`, named texture maps and a source package. Applications interpret -parameter values and cook or render maps themselves; this crate does not depend on an app's -model. It supports callers that read either version 1 or version 2 of the manifest, or both. +The MCMAT v3 portable material is a ZIP containing a version-only `material.json`, one +`source.sbs`, and the required source assets under `resources/`. The sole root-level +material graph in the SBS is the entry. Applications inspect its exposed controls and +cook its outputs through MaterialCraft. Texture maps and MaterialX documents are generated +by exporters. Earlier archives must be republished from their original projects. -`is_material` checks for a manifest with a bounded ZIP index; `Material::open` takes caller-provided version, entry-count, map-count, per-entry and total -expanded-byte limits. Each subsequent `read` and `read_source` shares that budget, including -repeated references to the same ZIP member. Duplicate member names are refused. The manifest -preserves unknown fields at the top level and on maps; parameter, input and preset objects are -kept as JSON values so their unknown fields survive too. `write` preserves the caller's source -entry name and map names, and rejects duplicate archive member names through `craft-zip`. - -The source package is opaque. Version 1 commonly names `source.mcraft`; MaterialCraft's version 2 -writer names `source.sbs`. Callers that invoke another application must preserve the source's -format and extension rather than infer it from `.mcmat` alone. +`Material::open` checks archive entries and expansion budgets before returning source +files. `write` compresses the XML and version marker and preserves source asset bytes. diff --git a/crates/mcmat/src/lib.rs b/crates/mcmat/src/lib.rs index 75b8709ef..076fe636a 100644 --- a/crates/mcmat/src/lib.rs +++ b/crates/mcmat/src/lib.rs @@ -1,133 +1,126 @@ #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] #![forbid(unsafe_code)] -//! Bounded interchange for MaterialCraft portable materials (`.mcmat`). -//! -//! The manifest and its version belong to the format, while interpreting parameter values, -//! cooking maps and opening the source package belong to the caller. Unknown fields survive -//! deserialization and serialization, including fields added by later versions. - -use std::collections::BTreeMap; +//! The clean-room MCMAT v3 source archive. Applications interpret the SBS entry graph. use craft_zip::{Archive, Compression, Writer}; -use serde::{Deserialize, Serialize}; -use serde_json::Value; +use serde::Deserialize; +use std::collections::{BTreeMap, BTreeSet}; -pub const FORMAT: &str = "craft-material"; +pub const VERSION: u32 = 3; pub const MANIFEST_ENTRY: &str = "material.json"; +pub const SOURCE_ENTRY: &str = "source.sbs"; +const MARKER: &[u8] = br#"{"version":3}"#; -/// A portable manifest; typed parameter values remain JSON so applications can adapt their own model. -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct Manifest { - pub format: String, - pub version: u32, - pub name: String, - pub graph: String, - pub size: [u32; 2], - pub maps: Vec, - #[serde(default)] - pub parameters: Vec, - #[serde(default)] - pub inputs: Vec, - #[serde(default)] - pub presets: Vec, - pub source: String, - #[serde(flatten)] - pub extra: BTreeMap, -} - -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct MapEntry { - pub usage: String, - pub file: String, - #[serde(flatten)] - pub extra: BTreeMap, -} - -/// All limits are supplied by the consumer, including the versions it understands. #[derive(Clone, Copy, Debug)] pub struct Limits { - pub min_version: u32, - pub max_version: u32, pub max_entries: u64, - pub max_maps: usize, pub max_manifest_bytes: u64, pub max_entry_bytes: u64, pub max_total_bytes: u64, } +impl Default for Limits { + fn default() -> Self { + Self { max_entries: 100_000, max_manifest_bytes: 64 << 20, max_entry_bytes: 256 << 20, max_total_bytes: 1 << 30 } + } +} + #[derive(Debug, thiserror::Error)] pub enum Error { #[error("invalid portable material: {0}")] Invalid(String), - #[error("unsupported portable material version {0}")] + #[error("unsupported .mcmat version {0} (expected 3). Republish from the original authoring project")] Version(u32), - #[error("portable material limit: {0}")] - Limit(String), #[error("portable material archive: {0}")] Archive(#[from] craft_zip::Error), } -/// Whether a bounded ZIP index contains a material manifest. This does not validate the manifest. +/// File sniffing also recognizes old manifests so the reader can give republishing guidance. pub fn is_material(bytes: &[u8], max_entries: u64) -> bool { - Archive::open(bytes, craft_zip::Limits { max_entries, max_total_bytes: 0 }) - .is_ok_and(|archive| !archive.has_duplicate_names() && archive.contains(MANIFEST_ENTRY)) + Archive::open(bytes, craft_zip::Limits { max_entries, max_total_bytes: 0 }).is_ok_and(|archive| archive.contains(MANIFEST_ENTRY)) } -/// Manifest and original archive, retaining one shared expanded-byte budget across reads. -pub struct Material<'a> { - pub manifest: Manifest, - archive: Archive<'a>, - max_entry_bytes: u64, +fn valid_resource(name: &str) -> bool { + name.len() <= 4096 + && name.starts_with("resources/") + && !name.contains(['\\', ':']) + && !name.chars().any(char::is_control) + && name.split('/').all(|part| !matches!(part, "" | "." | "..")) } -impl<'a> Material<'a> { - pub fn open(bytes: &'a [u8], limits: Limits) -> Result { +#[derive(Debug)] +pub struct Material { + pub source: Vec, + /// Keys are paths relative to source.sbs, including the resources/ prefix. + pub resources: BTreeMap>, +} + +impl Material { + pub fn open(bytes: &[u8], limits: Limits) -> Result { let mut archive = Archive::open(bytes, craft_zip::Limits { max_entries: limits.max_entries, max_total_bytes: limits.max_total_bytes })?; - if archive.has_duplicate_names() { - return Err(Error::Invalid("duplicate archive entries".into())); + if archive.has_duplicate_names() || archive.has_overlapping_files()? { + return Err(Error::Invalid("duplicate or overlapping archive entries".into())); } - let json = archive.read(MANIFEST_ENTRY, limits.max_manifest_bytes)?.ok_or_else(|| Error::Invalid("material.json is missing".into()))?; - let manifest: Manifest = serde_json::from_slice(&json).map_err(|e| Error::Invalid(format!("material.json: {e}")))?; - if manifest.format != FORMAT { - return Err(Error::Invalid(format!("format `{}`", manifest.format))); + let json = archive.read(MANIFEST_ENTRY, limits.max_manifest_bytes)?.ok_or_else(|| Error::Invalid("missing material.json".into()))?; + #[derive(Deserialize)] + struct Version { + version: u32, } - if !(limits.min_version..=limits.max_version).contains(&manifest.version) { - return Err(Error::Version(manifest.version)); + let marker: Version = serde_json::from_slice(&json).map_err(|err| Error::Invalid(format!("material.json: {err}")))?; + if marker.version != VERSION { + return Err(Error::Version(marker.version)); } - if manifest.maps.len() > limits.max_maps { - return Err(Error::Limit(format!("{} maps exceeds {}", manifest.maps.len(), limits.max_maps))); + #[derive(Deserialize)] + #[serde(deny_unknown_fields)] + struct Marker { + version: u32, } - Ok(Self { manifest, archive, max_entry_bytes: limits.max_entry_bytes }) - } - - /// Read one named member, charging it to the same budget as previous reads. - pub fn read(&mut self, name: &str) -> Result, Error> { - self.archive.read(name, self.max_entry_bytes)?.ok_or_else(|| Error::Invalid(format!("{name} is missing"))) - } - - pub fn read_source(&mut self) -> Result, Error> { - self.read(&self.manifest.source.clone()) + if !serde_json::from_slice::(&json).is_ok_and(|m| m.version == VERSION) { + return Err(Error::Invalid("material.json must contain only the version".into())); + } + let source = archive.read(SOURCE_ENTRY, limits.max_entry_bytes)?.ok_or_else(|| Error::Invalid("missing source.sbs".into()))?; + let mut resources = BTreeMap::new(); + let mut seen = BTreeSet::new(); + for index in 0..archive.len() { + let name = archive.entry_name(index)?.ok_or_else(|| Error::Invalid("invalid entry name".into()))?; + if name == SOURCE_ENTRY || name == MANIFEST_ENTRY { + continue; + } + if name.strip_suffix('/').is_some_and(|dir| dir == "resources" || valid_resource(dir)) { + continue; + } + if !valid_resource(&name) || !seen.insert(name.to_ascii_lowercase()) { + return Err(Error::Invalid(format!("invalid or ambiguous resource path `{name}`"))); + } + let data = archive.read(&name, limits.max_entry_bytes)?.ok_or_else(|| Error::Invalid(format!("missing `{name}`")))?; + resources.insert(name, data); + } + Ok(Self { source, resources }) } } -/// Write a manifest, its named maps, and the source. Duplicate member names are rejected. -pub fn write(manifest: &Manifest, maps: &[(String, Vec)], source: &[u8]) -> Result, Error> { - // Flattened fields must not serialize a second copy of a known key. - const KNOWN: &[&str] = &["format", "version", "name", "graph", "size", "maps", "parameters", "inputs", "presets", "source"]; - if manifest.extra.keys().any(|key| KNOWN.contains(&key.as_str())) - || manifest.maps.iter().any(|map| map.extra.contains_key("usage") || map.extra.contains_key("file")) - { - return Err(Error::Invalid("an extra field duplicates a known field".into())); - } - let json = serde_json::to_vec_pretty(manifest).map_err(|e| Error::Invalid(format!("material.json: {e}")))?; +/// Write one SBS document with its referenced source assets. +pub fn write<'a>(source: &[u8], resources: impl IntoIterator) -> Result, Error> { + let limits = Limits::default(); let mut writer = Writer::new(); - writer.add(MANIFEST_ENTRY, &json, Compression::Deflated)?; - for (name, bytes) in maps { - writer.add(name, bytes, Compression::Stored)?; + let mut seen = BTreeSet::new(); + let mut total = (source.len() as u64).saturating_add(MARKER.len() as u64); + if source.len() as u64 > limits.max_entry_bytes { + return Err(Error::Invalid("source.sbs exceeds the entry limit".into())); + } + writer.add(MANIFEST_ENTRY, MARKER, Compression::Deflated)?; + writer.add(SOURCE_ENTRY, source, Compression::Deflated)?; + for (name, bytes) in resources { + if !valid_resource(name) || !seen.insert(name.to_ascii_lowercase()) { + return Err(Error::Invalid(format!("invalid or ambiguous resource path `{name}`"))); + } + total = total.saturating_add(bytes.len() as u64); + if bytes.len() as u64 > limits.max_entry_bytes || total > limits.max_total_bytes || seen.len() as u64 + 2 > limits.max_entries { + return Err(Error::Invalid(format!("archive limits exceeded at `{name}`"))); + } + let compression = if name.ends_with(".svg") { Compression::Deflated } else { Compression::Stored }; + writer.add(name, bytes, compression)?; } - writer.add(&manifest.source, source, Compression::Stored)?; Ok(writer.finish()?) } @@ -135,82 +128,58 @@ pub fn write(manifest: &Manifest, maps: &[(String, Vec)], source: &[u8]) -> mod tests { use super::*; - fn limits() -> Limits { - Limits { - min_version: 1, - max_version: 2, - max_entries: 100, - max_maps: 4, - max_manifest_bytes: 4096, - max_entry_bytes: 100, - max_total_bytes: 8192, - } - } - - fn sample(version: u32) -> Manifest { - serde_json::from_value(serde_json::json!({ - "format": "craft-material", "version": version, "name": "Stone", "graph": "Stone", "size": [64, 64], - "maps": [{"usage": "baseColor", "file": "maps/base.png", "colorSpace": "srgb", "futureMap": true}], - "parameters": [{"id": "rough", "value": {"t": "float", "v": 0.25}, "futureParam": 42}], - "inputs": [{"identifier": "curvature", "kind": "gray"}], "presets": [], - "source": if version == 1 { "source.mcraft" } else { "source.sbs" }, "futureField": {"keep": true} - })) - .unwrap() - } - #[test] - fn both_protocol_versions_keep_unknown_fields_and_payloads() { - for version in [1, 2] { - let manifest = sample(version); - let bytes = write(&manifest, &[("maps/base.png".into(), vec![1, 2, 3])], b"source").unwrap(); - assert!(is_material(&bytes, 100)); - assert!(!is_material(&bytes, 1)); - let mut material = Material::open(&bytes, limits()).unwrap(); - assert_eq!(material.manifest, manifest); - assert_eq!(material.read("maps/base.png").unwrap(), [1, 2, 3]); - assert_eq!(material.read_source().unwrap(), b"source"); - let json = serde_json::to_value(&material.manifest).unwrap(); - assert_eq!(json["futureField"]["keep"], true); - assert_eq!(json["maps"][0]["futureMap"], true); - assert_eq!(json["parameters"][0]["futureParam"], 42); + fn procedural_source_and_assets_round_trip_under_one_budget() { + let bytes = write(b"", [("resources/oak.png", b"image".as_slice())]).unwrap(); + let pkg = Material::open(&bytes, Limits::default()).unwrap(); + assert_eq!(pkg.source, b""); + assert_eq!(pkg.resources["resources/oak.png"], b"image"); + let mut archive = Archive::open(&bytes, craft_zip::Limits { max_entries: 3, max_total_bytes: 128 }).unwrap(); + assert_eq!(archive.read(MANIFEST_ENTRY, 32).unwrap().unwrap(), MARKER); + assert_eq!(archive.is_stored(SOURCE_ENTRY), Some(false)); + assert_eq!(archive.is_stored("resources/oak.png"), Some(true)); + for limits in [ + Limits { max_entries: 2, ..Default::default() }, + Limits { max_entry_bytes: 2, ..Default::default() }, + Limits { max_total_bytes: 24, ..Default::default() }, + ] { + assert!(Material::open(&bytes, limits).is_err()); } } #[test] - fn limits_apply_to_the_manifest_maps_and_aggregate_reads() { - let manifest = sample(2); - let bytes = write(&manifest, &[("maps/base.png".into(), vec![1; 8])], &[2; 8]).unwrap(); - let mut unsupported = limits(); - unsupported.max_version = 1; - assert!(matches!(Material::open(&bytes, unsupported), Err(Error::Version(2)))); - let mut no_maps = limits(); - no_maps.max_maps = 0; - assert!(matches!(Material::open(&bytes, no_maps), Err(Error::Limit(_)))); - let mut tiny_entry = limits(); - tiny_entry.max_entry_bytes = 7; - assert!(Material::open(&bytes, tiny_entry).unwrap().read("maps/base.png").is_err()); - let json_len = serde_json::to_vec_pretty(&manifest).unwrap().len() as u64; - let mut aggregate = limits(); - aggregate.max_total_bytes = json_len + 15; - let mut material = Material::open(&bytes, aggregate).unwrap(); - assert_eq!(material.read("maps/base.png").unwrap().len(), 8); - assert!(material.read_source().is_err()); + fn rejects_previous_versions_before_requiring_the_v3_layout() { + for version in [0, 1, 2, 4] { + let mut zip = Writer::new(); + zip.add(MANIFEST_ENTRY, format!(r#"{{"format":"craft-material","version":{version}}}"#).as_bytes(), Compression::Deflated).unwrap(); + let bytes = zip.finish().unwrap(); + assert!(is_material(&bytes, 2)); + assert!(matches!(Material::open(&bytes, Limits::default()), Err(Error::Version(v)) if v == version)); + } } #[test] - fn refuses_extra_fields_that_duplicate_known_keys() { - let mut manifest = sample(2); - manifest.extra.insert("version".into(), 3.into()); - assert!(write(&manifest, &[], b"source").is_err()); - manifest.extra.remove("version"); - manifest.maps[0].extra.insert("file".into(), "other".into()); - assert!(write(&manifest, &[], b"source").is_err()); + fn v3_requires_source_and_a_version_only_marker() { + for (marker, source) in [(MARKER, None), (br#"{"version":3,"graph":"Other"}"#.as_slice(), Some(b"".as_slice()))] { + let mut zip = Writer::new(); + zip.add(MANIFEST_ENTRY, marker, Compression::Deflated).unwrap(); + if let Some(source) = source { + zip.add(SOURCE_ENTRY, source, Compression::Deflated).unwrap(); + } + assert!(Material::open(&zip.finish().unwrap(), Limits::default()).is_err()); + } } #[test] - fn refuses_duplicate_names_on_write() { - let manifest = sample(2); - let duplicate = [("maps/base.png".to_string(), vec![1]), ("maps/base.png".to_string(), vec![2])]; - assert!(write(&manifest, &duplicate, b"source").is_err()); + fn rejects_ambiguous_or_nonlocal_resource_members() { + for name in ["resources/../../x", "resources/a\\x", "/x", "maps/color.png", "resources/C:/x", "preview.png"] { + assert!(write(b"x", [(name, &b"x"[..])]).is_err()); + let mut zip = Writer::new(); + zip.add(MANIFEST_ENTRY, MARKER, Compression::Stored).unwrap(); + zip.add(SOURCE_ENTRY, b"x", Compression::Deflated).unwrap(); + zip.add(name, b"x", Compression::Stored).unwrap(); + assert!(Material::open(&zip.finish().unwrap(), Limits::default()).is_err()); + } + assert!(write(b"x", [("resources/A", &b"a"[..]), ("resources/a", &b"b"[..])]).is_err()); } } From b3960accde1b540b2fe9364f8b6b848284564601 Mon Sep 17 00:00:00 2001 From: FredApps Date: Wed, 18 Nov 2026 08:08:01 +0100 Subject: [PATCH 47/56] psd: reject invalid quilt bounds and discard unsupported templates --- crates/psd/src/smart.rs | 16 +++++++++++++++- crates/psd/src/smart/write.rs | 30 +++++++++++++++++++++++++++++- 2 files changed, 44 insertions(+), 2 deletions(-) diff --git a/crates/psd/src/smart.rs b/crates/psd/src/smart.rs index efa3cee2e..9a95c61f3 100644 --- a/crates/psd/src/smart.rs +++ b/crates/psd/src/smart.rs @@ -134,8 +134,11 @@ impl Warp { let rows = quilt_patches(&slice_y)?; if !slice_x.is_empty() || !slice_y.is_empty() { // The evaluator normalizes over bounds, not stored slice coordinates. - // Infer a missing rectangle only when both explicit axes define it. + // Infer an absent rectangle only when both explicit axes define it. if !(w.bounds[2] > w.bounds[0] && w.bounds[3] > w.bounds[1]) { + if d.get("bounds").is_some() { + return Err(PsdError::Unsupported("invalid explicit quilt bounds".into())); + } let (Some(&left), Some(&right), Some(&top), Some(&bottom)) = (slice_x.first(), slice_x.last(), slice_y.first(), slice_y.last()) else { return Err(PsdError::Unsupported("quilt divisions need bounds or both axes".into())); @@ -1074,6 +1077,17 @@ mod tests { .with("Rght", Value::Double(40.0)) .with("Btom", Value::Double(10.0)); assert!(Warp::try_from_descriptor(&equal.with("bounds", Value::Descriptor(bounds))).is_err()); + let wrong_type = quilt_descriptor(vec![0.0, 10.0, 20.0], vec![0.0, 10.0]).with("bounds", Value::Integer(1)); + assert!(Warp::try_from_descriptor(&wrong_type).is_err()); + let invalid_bounds = Descriptor::new("bounds") + .with("Left", Value::Double(0.0)) + .with("Top ", Value::Double(0.0)) + .with("Rght", Value::Double(40.0)) + .with("Btom", Value::Double(0.0)); + let explicit_invalid = quilt_descriptor(vec![0.0, 10.0, 20.0], vec![0.0, 10.0]).with("bounds", Value::Descriptor(invalid_bounds)); + assert!(Warp::try_from_descriptor(&explicit_invalid).is_err()); + let data = placed_layer_data("invalid bounds", [0.0; 8], |d| d.with("quiltWarp", Value::Descriptor(explicit_invalid))); + assert!(matches!(SmartObject::from_placed_layer_data(&data), Err(PsdError::Unsupported(_)))); let missing = quilt_descriptor(vec![0.0, 10.0, 20.0], vec![]); assert!(Warp::try_from_descriptor(&missing).is_err()); } diff --git a/crates/psd/src/smart/write.rs b/crates/psd/src/smart/write.rs index d409d726c..413b0f406 100644 --- a/crates/psd/src/smart/write.rs +++ b/crates/psd/src/smart/write.rs @@ -180,7 +180,8 @@ impl SmartObject { } set(&mut d, "warp", Value::Descriptor(warp.to_descriptor())); // The imported `quiltWarp` stays while it still says what the warp is. - let kept = t.get_object("quiltWarp").is_some_and(|q| Warp::from_descriptor(q).as_ref() == self.warp.as_ref()); + let kept = + t.get_object("quiltWarp").is_some_and(|q| Warp::try_from_descriptor(q).is_ok_and(|parsed| parsed.as_ref() == self.warp.as_ref())); if !kept { match quilt { Some(q) => set_before(&mut d, "quiltWarp", Value::Descriptor(q), "warp"), @@ -289,6 +290,33 @@ mod tests { ] } + #[test] + fn templates_drop_unsupported_quilts_but_retain_valid_none() { + let bounds = [0.0, 0.0, 20.0, 10.0]; + let unfl = |values| Value::UnitFloats { unit: *b"#Pxl", values }; + let unequal = + Descriptor::new("warp").with("warpStyle", Value::Enumerated { type_id: Id::new("warpStyle"), value: Id::new("warpCustom") }).with( + "customEnvelopeWarp", + Value::Descriptor( + Descriptor::new("customEnvelopeWarp").with("quiltSliceX", unfl(vec![0.0, 5.0, 20.0])).with("quiltSliceY", unfl(vec![0.0, 10.0])), + ), + ); + assert!(Warp::try_from_descriptor(&unequal).is_err()); + let valid_none = Warp::none(bounds).to_descriptor(); + assert!(matches!(Warp::try_from_descriptor(&valid_none), Ok(None))); + for (quilt, keep) in [(unequal, false), (valid_none, true)] { + let template = Descriptor::new("null").with("quiltWarp", Value::Descriptor(quilt.clone())); + let bytes = placed(None).to_placed_layer_data(&PlacedLayerOptions { + placed: "layer", + resolution: 72.0, + filter_fx: None, + template: Some(&template), + }); + let written = VersionedDescriptor::parse_prefix(&bytes[8..]).unwrap().0.descriptor; + assert_eq!(written.get_object("quiltWarp"), keep.then_some(&quilt)); + assert!(SmartObject::from_placed_layer_data(&bytes).unwrap().warp.is_none()); + } + } #[test] fn placed_layer_data_reads_back_and_passes_the_strict_check() { let filter = Descriptor::new("filterFX") From b0f25d641840bea1dda99c1e5e0c8db9221bcf28 Mon Sep 17 00:00:00 2001 From: chasse20 Date: Wed, 18 Nov 2026 02:15:10 -0500 Subject: [PATCH 48/56] Compress raw MCMAT source assets --- crates/mcmat/src/lib.rs | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/crates/mcmat/src/lib.rs b/crates/mcmat/src/lib.rs index 076fe636a..fe328cceb 100644 --- a/crates/mcmat/src/lib.rs +++ b/crates/mcmat/src/lib.rs @@ -118,7 +118,11 @@ pub fn write<'a>(source: &[u8], resources: impl IntoIterator limits.max_entry_bytes || total > limits.max_total_bytes || seen.len() as u64 + 2 > limits.max_entries { return Err(Error::Invalid(format!("archive limits exceeded at `{name}`"))); } - let compression = if name.ends_with(".svg") { Compression::Deflated } else { Compression::Stored }; + let extension = name.rsplit_once('.').map(|(_, ext)| ext.to_ascii_lowercase()); + let compression = match extension.as_deref() { + Some("png" | "jpg" | "jpeg" | "webp" | "gif" | "exr" | "woff" | "woff2") => Compression::Stored, + _ => Compression::Deflated, + }; writer.add(name, bytes, compression)?; } Ok(writer.finish()?) @@ -147,6 +151,14 @@ mod tests { } } + #[test] + fn compresses_unencoded_source_assets() { + let bytes = write(b"", [("resources/shape.svg", b"".as_slice()), ("resources/font.ttf", b"font".as_slice())]).unwrap(); + let mut archive = Archive::open(&bytes, craft_zip::Limits { max_entries: 4, max_total_bytes: 128 }).unwrap(); + assert_eq!(archive.is_stored("resources/shape.svg"), Some(false)); + assert_eq!(archive.is_stored("resources/font.ttf"), Some(false)); + } + #[test] fn rejects_previous_versions_before_requiring_the_v3_layout() { for version in [0, 1, 2, 4] { From be556bedcbc3fcd63d3146fd7fcec9bc488fc7ae Mon Sep 17 00:00:00 2001 From: FredApps Date: Wed, 18 Nov 2026 08:43:10 +0100 Subject: [PATCH 49/56] psd: align quilt serialization and strict slice admission --- crates/psd/src/smart.rs | 77 ++++++++++++++++++++++++++++------- crates/psd/src/smart/write.rs | 71 ++++++++++++++++++++++++++++---- 2 files changed, 126 insertions(+), 22 deletions(-) diff --git a/crates/psd/src/smart.rs b/crates/psd/src/smart.rs index 9a95c61f3..7ed444f45 100644 --- a/crates/psd/src/smart.rs +++ b/crates/psd/src/smart.rs @@ -74,11 +74,17 @@ fn quad_from(t: [f64; 8]) -> [[f64; 2]; 4] { /// The patch boundaries of a custom envelope: a list of numbers, or (as Photoshop writes a /// `quiltWarp`) an object array whose body holds them under the same key. -fn quilt_slices(env: &Descriptor, key: &str) -> Vec { - match env.get(key) { - Some(Value::ObjectArray(o)) => o.body.get_numbers(key), - _ => env.get_numbers(key), - } +fn quilt_slices(env: &Descriptor, key: &str) -> Result> { + let Some(value) = env.get(key) else { return Ok(vec![]) }; + // Filtering nonnumbers would change the number and positions of patches. + // Only absence, not a malformed or empty present value, means one patch. + let value = if let Value::ObjectArray(o) = value { o.body.get(key) } else { Some(value) }; + let values = match value { + Some(Value::UnitFloats { values, .. }) => Some(values.clone()), + Some(Value::List(values)) => values.iter().map(Value::as_number).collect::>>(), + _ => None, + }; + values.filter(|values| !values.is_empty()).ok_or_else(|| PsdError::Unsupported("invalid quilt slice values".into())) } /// The public mesh has no slice coordinates, so only uniform divisions can be @@ -90,18 +96,23 @@ fn quilt_patches(slices: &[f64]) -> Result { if slices.len() < 2 || slices.iter().any(|v| !v.is_finite()) { return Err(PsdError::Unsupported("invalid quilt divisions".into())); } - let step = slices[1] - slices[0]; - if !step.is_finite() || step <= 0.0 { + let patches = slices.len() - 1; + let extent = slices[patches] - slices[0]; + if !extent.is_finite() || extent <= 0.0 { return Err(PsdError::Unsupported("invalid quilt divisions".into())); } - let tolerance = step.abs() * 1e-9; - if slices.windows(2).any(|pair| { - let width = pair[1] - pair[0]; - !width.is_finite() || width <= 0.0 || (width - step).abs() > tolerance - }) { + // Compare against the same endpoint interpolation the writer uses. At large + // coordinate offsets a uniform grid can have differently rounded adjacent widths. + let tolerance = (extent / patches as f64) * 1e-9; + if slices.windows(2).any(|pair| pair[1] <= pair[0]) + || slices.iter().enumerate().any(|(i, value)| { + let expected = slices[0] + extent * (i as f64 / patches as f64); + (value - expected).abs() > tolerance + }) + { return Err(PsdError::Unsupported("unequal quilt divisions".into())); } - Ok(slices.len() - 1) + Ok(patches) } impl Warp { /// Reads a `warp` descriptor; `None` for no warp (the identity, or a custom warp without a @@ -128,8 +139,8 @@ impl Warp { style, }; if let Some(env) = d.get_object("customEnvelopeWarp") { - let slice_x = quilt_slices(env, "quiltSliceX"); - let slice_y = quilt_slices(env, "quiltSliceY"); + let slice_x = quilt_slices(env, "quiltSliceX")?; + let slice_y = quilt_slices(env, "quiltSliceY")?; let cols = quilt_patches(&slice_x)?; let rows = quilt_patches(&slice_y)?; if !slice_x.is_empty() || !slice_y.is_empty() { @@ -1065,8 +1076,44 @@ mod tests { } assert_eq!(quilt_patches(&[]).unwrap(), 1); assert_eq!(quilt_patches(&[0.0, 10.0, 20.0]).unwrap(), 2); + assert_eq!(quilt_patches(&[1e16, 1e16 + 2.0, 1e16 + 6.0, 1e16 + 8.0]).unwrap(), 3); + assert!(quilt_patches(&[1e16, 1e16 + 4.0, 1e16 + 6.0, 1e16 + 8.0]).is_err()); } + #[test] + fn quilt_slice_values_are_strict_in_lists_and_object_arrays() { + let list = Value::List(vec![Value::Integer(0), Value::Double(10.0), Value::UnitFloat { unit: *b"#Pxl", value: 20.0 }]); + let unfl = Value::UnitFloats { unit: *b"#Pxl", values: vec![0.0, 10.0, 20.0] }; + let bad_list = Value::List(vec![Value::Double(0.0), Value::Text(UnicodeString::new("bad")), Value::Double(10.0), Value::Double(20.0)]); + for wrapped in [false, true] { + for (value, valid) in [ + (list.clone(), true), + (unfl.clone(), true), + (bad_list.clone(), false), + (Value::List(vec![]), false), + (Value::UnitFloats { unit: *b"#Pxl", values: vec![] }, false), + (Value::Integer(1), false), + ] { + let value = if wrapped { + Value::ObjectArray(ObjectArray { prefix: 3, body: Descriptor::new("UntF").with("quiltSliceX", value) }) + } else { + value + }; + let mut d = quilt_descriptor(vec![0.0, 10.0, 20.0], vec![0.0, 10.0]); + let Value::Descriptor(env) = &mut d.items.iter_mut().find(|(key, _)| key.is("customEnvelopeWarp")).unwrap().1 else { + panic!("envelope") + }; + env.items.iter_mut().find(|(key, _)| key.is("quiltSliceX")).unwrap().1 = value; + assert_eq!(Warp::try_from_descriptor(&d).is_ok(), valid); + let bytes = placed_layer_data("slices", [0.0; 8], |parent| parent.with("quiltWarp", Value::Descriptor(d))); + assert_eq!(SmartObject::from_placed_layer_data(&bytes).is_ok(), valid); + } + } + let absent = Descriptor::new("customEnvelopeWarp"); + assert!(quilt_slices(&absent, "quiltSliceX").unwrap().is_empty()); + let missing_body = absent.with("quiltSliceX", Value::ObjectArray(ObjectArray { prefix: 0, body: Descriptor::new("UntF") })); + assert!(quilt_slices(&missing_body, "quiltSliceX").is_err()); + } #[test] fn quilt_endpoints_define_or_match_the_normalization_bounds() { let equal = quilt_descriptor(vec![0.0, 10.0, 20.0], vec![0.0, 10.0]); diff --git a/crates/psd/src/smart/write.rs b/crates/psd/src/smart/write.rs index 413b0f406..0c9eb4588 100644 --- a/crates/psd/src/smart/write.rs +++ b/crates/psd/src/smart/write.rs @@ -78,7 +78,10 @@ impl Warp { /// Style, bend, distortions, axis, bounds and order: the keys a `warp` and a `quiltWarp` /// share, in Photoshop's order. fn head(&self, class: &str) -> Descriptor { - let [l, t, r, b] = self.bounds; + self.head_with_bounds(class, self.bounds) + } + + fn head_with_bounds(&self, class: &str, [l, t, r, b]: [f64; 4]) -> Descriptor { let bounds = Descriptor::new("classFloatRect") .with("Top ", Value::Double(t)) .with("Left", Value::Double(l)) @@ -119,15 +122,20 @@ impl Warp { /// The `quiltWarp` descriptor of a split warp, in Photoshop's layout: the control points, /// `deformNumCols` × `deformNumRows` of them, and the patch boundaries (`quiltSliceX` / - /// `quiltSliceY`) evenly across the warp's bounds. `None` for any other warp. + /// `quiltSliceY`) evenly across the warp's bounds. Invalid axes use 0..1 because this standalone + /// method has no content size; the placed-layer writer supplies that size when available. + /// `None` for any other warp. pub fn quilt_descriptor(&self) -> Option { if !self.is_split() { return None; } - let [l, t, r, b] = self.bounds; + // The header and the divisions must describe the same rectangle, including + // when a caller leaves bounds at their default or supplies an invalid axis. + let axis = |lo: f64, hi: f64| if (hi - lo).is_finite() && hi > lo { (lo, hi) } else { (0.0, 1.0) }; + let (l, r) = axis(self.bounds[0], self.bounds[2]); + let (t, b) = axis(self.bounds[1], self.bounds[3]); let slices = |key: &str, n: usize, lo: f64, hi: f64| { - let (lo, hi) = if (hi - lo).is_finite() && hi > lo { (lo, hi) } else { (0.0, 1.0) }; - let values: Vec = (0..=n).map(|i| lo + (hi - lo) * i as f64 / n as f64).collect(); + let values: Vec = (0..=n).map(|i| lo + (hi - lo) * (i as f64 / n as f64)).collect(); let prefix = values.len() as u32; Value::ObjectArray(ObjectArray { prefix, body: Descriptor::new("UntF").with(key, Value::UnitFloats { unit: *b"#Pxl", values }) }) }; @@ -137,7 +145,7 @@ impl Warp { .with("meshPoints", self.mesh_points()); let count = |n: usize| Value::Integer(i32::try_from(n.saturating_mul(3).saturating_add(1)).unwrap_or(i32::MAX)); Some( - self.head("quiltWarp") + self.head_with_bounds("quiltWarp", [l, t, r, b]) .with("deformNumRows", count(self.rows)) .with("deformNumCols", count(self.cols)) .with("customEnvelopeWarp", Value::Descriptor(envelope)), @@ -159,7 +167,13 @@ impl SmartObject { /// The warp written, over the content (or `[0, 0, 0, 0]` without a size) when there is none. fn warp_or_none(&self) -> Warp { let [w, h] = self.size.unwrap_or([0.0; 2]); - self.warp.clone().unwrap_or_else(|| Warp::none([0.0, 0.0, w, h])) + let mut warp = self.warp.clone().unwrap_or_else(|| Warp::none([0.0, 0.0, w, h])); + // Match Warp::apply's whole-rectangle fallback before encoding explicit + // quilt slices. Otherwise default bounds would change the mapping on readback. + if warp.is_split() && !(warp.bounds[2] > warp.bounds[0] && warp.bounds[3] > warp.bounds[1]) { + warp.bounds = [0.0, 0.0, w, h]; + } + warp } /// The data of a `SoLd` block (`soLD`, version 4, a version-16 descriptor, padded to 4). @@ -290,6 +304,49 @@ mod tests { ] } + #[test] + fn quilt_writer_uses_one_rectangle_for_header_slices_and_roundtrip() { + for (bounds, expected) in [ + ([0.0; 4], [0.0, 0.0, 1.0, 1.0]), + ([2.0, 3.0, 22.0, 13.0], [2.0, 3.0, 22.0, 13.0]), + ([2.0, 3.0, 22.0, 3.0], [2.0, 0.0, 22.0, 1.0]), + ([f64::NAN, 3.0, 22.0, 13.0], [0.0, 3.0, 1.0, 13.0]), + ([-f64::MAX, 0.0, f64::MAX, 1.0], [0.0, 0.0, 1.0, 1.0]), + ([0.0, 0.0, 1e308, 10.0], [0.0, 0.0, 1e308, 10.0]), + ] { + let warp = Warp { style: "warpCustom".into(), bounds, cols: 2, rows: 1, mesh: grid(2, 1, 20.0, 10.0), ..Warp::default() }; + let descriptor = warp.quilt_descriptor().unwrap(); + let back = Warp::try_from_descriptor(&descriptor).unwrap().unwrap(); + assert_eq!(back.bounds, expected); + assert_eq!((back.cols, back.rows, &back.mesh), (2, 1, &warp.mesh)); + assert_eq!(back.quilt_descriptor().unwrap(), descriptor); + } + let high_offset = Warp { + style: "warpCustom".into(), + bounds: [1e16, 0.0, 1e16 + 8.0, 10.0], + cols: 3, + rows: 1, + mesh: grid(3, 1, 20.0, 10.0), + ..Warp::default() + }; + assert_eq!(Warp::try_from_descriptor(&high_offset.quilt_descriptor().unwrap()).unwrap(), Some(high_offset)); + // At the placed-layer boundary content size is available: preserve the + // evaluator's fallback mapping, not merely the ability to parse the output. + for bounds in [[0.0; 4], [2.0, 3.0, 22.0, 3.0], [f64::NAN, 0.0, 20.0, 10.0]] { + let warp = Warp { style: "warpCustom".into(), bounds, cols: 2, rows: 1, mesh: grid(2, 1, 20.0, 10.0), ..Warp::default() }; + let so = SmartObject { size: Some([20.0, 10.0]), ..placed(Some(warp.clone())) }; + let bytes = so.to_placed_layer_data(&PlacedLayerOptions::default()); + let back = SmartObject::from_placed_layer_data(&bytes).unwrap(); + let parsed = back.warp.as_ref().unwrap(); + assert_eq!(parsed.bounds, [0.0, 0.0, 20.0, 10.0]); + for p in [[0.0, 0.0], [5.0, 4.0], [10.0, 5.0], [20.0, 10.0]] { + assert_eq!(parsed.apply(p, 20.0, 10.0), warp.apply(p, 20.0, 10.0)); + } + let template = VersionedDescriptor::parse_prefix(&bytes[8..]).unwrap().0.descriptor; + let rewritten = back.to_placed_layer_data(&PlacedLayerOptions { template: Some(&template), ..Default::default() }); + assert_eq!(SmartObject::from_placed_layer_data(&rewritten).unwrap(), back); + } + } #[test] fn templates_drop_unsupported_quilts_but_retain_valid_none() { let bounds = [0.0, 0.0, 20.0, 10.0]; From e9ec4813311264ee1857079c2edd10a70e2389a6 Mon Sep 17 00:00:00 2001 From: FredApps Date: Wed, 18 Nov 2026 09:11:45 +0100 Subject: [PATCH 50/56] psd: preserve canonical quilt grids across numeric extremes --- crates/psd/src/smart.rs | 54 +++++++++++++++++++++++++++++------ crates/psd/src/smart/write.rs | 53 ++++++++++++++++++++++++++++++---- 2 files changed, 94 insertions(+), 13 deletions(-) diff --git a/crates/psd/src/smart.rs b/crates/psd/src/smart.rs index 7ed444f45..0cd5ac433 100644 --- a/crates/psd/src/smart.rs +++ b/crates/psd/src/smart.rs @@ -67,6 +67,10 @@ fn finite(value: f64) -> f64 { if value.is_finite() { value } else { 0.0 } } +/// A usable normalization rectangle needs finite positive extents on both axes. +fn valid_bounds([l, t, r, b]: [f64; 4]) -> bool { + [l, t, r, b].iter().all(|v| v.is_finite()) && (r - l).is_finite() && r > l && (b - t).is_finite() && b > t +} /// The corner quad (top-left, top-right, bottom-right, bottom-left) from x0 y0 … x3 y3. fn quad_from(t: [f64; 8]) -> [[f64; 2]; 4] { [[t[0], t[1]], [t[2], t[3]], [t[4], t[5]], [t[6], t[7]]] @@ -102,12 +106,14 @@ fn quilt_patches(slices: &[f64]) -> Result { return Err(PsdError::Unsupported("invalid quilt divisions".into())); } // Compare against the same endpoint interpolation the writer uses. At large - // coordinate offsets a uniform grid can have differently rounded adjacent widths. + // coordinate offsets a uniform grid can have differently rounded adjacent widths, + // including coincident boundaries. Only canonical rounded positions are accepted; + // the model keeps the patch count and evaluates in its uniform parameter domain. let tolerance = (extent / patches as f64) * 1e-9; - if slices.windows(2).any(|pair| pair[1] <= pair[0]) - || slices.iter().enumerate().any(|(i, value)| { + if slices.windows(2).any(|pair| pair[1] < pair[0]) + || slices.iter().enumerate().take(patches).skip(1).any(|(i, value)| { let expected = slices[0] + extent * (i as f64 / patches as f64); - (value - expected).abs() > tolerance + !expected.is_finite() || (value - expected).abs() > tolerance }) { return Err(PsdError::Unsupported("unequal quilt divisions".into())); @@ -122,7 +128,10 @@ impl Warp { } /// Reads a warp, rejecting unequal or invalid quilt divisions rather than - /// interpreting them as equal-sized patches. Nonfinite geometry becomes zero. + /// interpreting them as equal-sized patches. Canonical uniform boundaries may coincide + /// after floating-point rounding; their patch count is retained. This is the internal + /// uniform-model contract, not a guarantee of other readers' handling of coincident slices. + /// Nonfinite geometry becomes zero. pub fn try_from_descriptor(d: &Descriptor) -> Result> { let style = d.get_enum("warpStyle").unwrap_or_else(|| "warpNone".to_string()); let side = |b: &Descriptor, k: &str| finite(b.get_number(k).unwrap_or(0.0)); @@ -146,7 +155,7 @@ impl Warp { if !slice_x.is_empty() || !slice_y.is_empty() { // The evaluator normalizes over bounds, not stored slice coordinates. // Infer an absent rectangle only when both explicit axes define it. - if !(w.bounds[2] > w.bounds[0] && w.bounds[3] > w.bounds[1]) { + if !valid_bounds(w.bounds) { if d.get("bounds").is_some() { return Err(PsdError::Unsupported("invalid explicit quilt bounds".into())); } @@ -155,6 +164,9 @@ impl Warp { return Err(PsdError::Unsupported("quilt divisions need bounds or both axes".into())); }; w.bounds = [left, top, right, bottom]; + if !valid_bounds(w.bounds) { + return Err(PsdError::Unsupported("invalid inferred quilt bounds".into())); + } } for (slices, start, end) in [(&slice_x, w.bounds[0], w.bounds[2]), (&slice_y, w.bounds[1], w.bounds[3])] { if let (Some(&first), Some(&last)) = (slices.first(), slices.last()) { @@ -187,7 +199,7 @@ impl Warp { /// The warp of a content point (content pixels → content pixels). pub fn apply(&self, p: [f64; 2], w: f64, h: f64) -> [f64; 2] { - let [l, t, r, b] = if self.bounds[2] > self.bounds[0] && self.bounds[3] > self.bounds[1] { self.bounds } else { [0.0, 0.0, w, h] }; + let [l, t, r, b] = if valid_bounds(self.bounds) { self.bounds } else { [0.0, 0.0, w, h] }; let (bw, bh) = (r - l, b - t); let (u, v) = ((p[0] - l) / bw, (p[1] - t) / bh); if self.style == "warpCustom" { @@ -1078,6 +1090,14 @@ mod tests { assert_eq!(quilt_patches(&[0.0, 10.0, 20.0]).unwrap(), 2); assert_eq!(quilt_patches(&[1e16, 1e16 + 2.0, 1e16 + 6.0, 1e16 + 8.0]).unwrap(), 3); assert!(quilt_patches(&[1e16, 1e16 + 4.0, 1e16 + 6.0, 1e16 + 8.0]).is_err()); + let lo = 3.0 * 2.0_f64.powi(970); + assert!((f64::MAX - lo).is_finite()); + assert!((lo + (f64::MAX - lo)).is_infinite()); + assert_eq!(quilt_patches(&[lo, f64::MAX]).unwrap(), 1); + assert_eq!(quilt_patches(&[1e16, 1e16, 1e16, 1e16 + 2.0, 1e16 + 2.0]).unwrap(), 4); + for invalid in [vec![0.0, 0.0, 20.0], vec![0.0, 10.0, 10.0, 20.0], vec![1e16, 1e16 + 2.0, 1e16, 1e16 + 2.0]] { + assert!(quilt_patches(&invalid).is_err()); + } } #[test] @@ -1135,8 +1155,26 @@ mod tests { assert!(Warp::try_from_descriptor(&explicit_invalid).is_err()); let data = placed_layer_data("invalid bounds", [0.0; 8], |d| d.with("quiltWarp", Value::Descriptor(explicit_invalid))); assert!(matches!(SmartObject::from_placed_layer_data(&data), Err(PsdError::Unsupported(_)))); - let missing = quilt_descriptor(vec![0.0, 10.0, 20.0], vec![]); + let mut missing = quilt_descriptor(vec![0.0, 10.0, 20.0], vec![0.0, 10.0]); + let Value::Descriptor(env) = &mut missing.items.iter_mut().find(|(key, _)| key.is("customEnvelopeWarp")).unwrap().1 else { + panic!("envelope") + }; + env.items.retain(|(key, _)| !key.is("quiltSliceY")); assert!(Warp::try_from_descriptor(&missing).is_err()); + let bounds = |top, bottom| { + Descriptor::new("bounds") + .with("Left", Value::Double(0.0)) + .with("Top ", Value::Double(top)) + .with("Rght", Value::Double(20.0)) + .with("Btom", Value::Double(bottom)) + }; + let present = missing.clone().with("bounds", Value::Descriptor(bounds(0.0, 10.0))); + let parsed = Warp::try_from_descriptor(&present).unwrap().unwrap(); + assert_eq!((parsed.cols, parsed.rows), (2, 1)); + assert_eq!(parsed.bounds, [0.0, 0.0, 20.0, 10.0]); + // Even the absent slice axis needs a finite normalization extent. + let overflow = missing.with("bounds", Value::Descriptor(bounds(-f64::MAX, f64::MAX))); + assert!(Warp::try_from_descriptor(&overflow).is_err()); } #[test] fn finite_warp_views_preserve_raw_descriptor_values() { diff --git a/crates/psd/src/smart/write.rs b/crates/psd/src/smart/write.rs index 0c9eb4588..f1edf82df 100644 --- a/crates/psd/src/smart/write.rs +++ b/crates/psd/src/smart/write.rs @@ -3,7 +3,7 @@ //! read back. Came from PhotoCraft's `crates/io/src/smart_map/placed.rs`, on this crate's //! placement types: the caller works out the quad and the warp from its own geometry. -use super::{SmartObject, Warp}; +use super::{SmartObject, Warp, valid_bounds}; use crate::descriptor::{Descriptor, Id, ObjectArray, UnicodeString, Value, VersionedDescriptor}; use crate::io::WriteExt; @@ -124,7 +124,9 @@ impl Warp { /// `deformNumCols` × `deformNumRows` of them, and the patch boundaries (`quiltSliceX` / /// `quiltSliceY`) evenly across the warp's bounds. Invalid axes use 0..1 because this standalone /// method has no content size; the placed-layer writer supplies that size when available. - /// `None` for any other warp. + /// Canonical boundaries may coincide after rounding at large offsets. The shared reader + /// preserves their uniform-model parameterization; external reader interoperability for + /// coincident slices is not guaranteed. `None` for any other warp. pub fn quilt_descriptor(&self) -> Option { if !self.is_split() { return None; @@ -135,7 +137,17 @@ impl Warp { let (l, r) = axis(self.bounds[0], self.bounds[2]); let (t, b) = axis(self.bounds[1], self.bounds[3]); let slices = |key: &str, n: usize, lo: f64, hi: f64| { - let values: Vec = (0..=n).map(|i| lo + (hi - lo) * (i as f64 / n as f64)).collect(); + let values: Vec = (0..=n) + .map(|i| { + if i == 0 { + lo + } else if i == n { + hi + } else { + lo + (hi - lo) * (i as f64 / n as f64) + } + }) + .collect(); let prefix = values.len() as u32; Value::ObjectArray(ObjectArray { prefix, body: Descriptor::new("UntF").with(key, Value::UnitFloats { unit: *b"#Pxl", values }) }) }; @@ -170,7 +182,7 @@ impl SmartObject { let mut warp = self.warp.clone().unwrap_or_else(|| Warp::none([0.0, 0.0, w, h])); // Match Warp::apply's whole-rectangle fallback before encoding explicit // quilt slices. Otherwise default bounds would change the mapping on readback. - if warp.is_split() && !(warp.bounds[2] > warp.bounds[0] && warp.bounds[3] > warp.bounds[1]) { + if warp.is_split() && !valid_bounds(warp.bounds) { warp.bounds = [0.0, 0.0, w, h]; } warp @@ -313,6 +325,7 @@ mod tests { ([f64::NAN, 3.0, 22.0, 13.0], [0.0, 3.0, 1.0, 13.0]), ([-f64::MAX, 0.0, f64::MAX, 1.0], [0.0, 0.0, 1.0, 1.0]), ([0.0, 0.0, 1e308, 10.0], [0.0, 0.0, 1e308, 10.0]), + ([3.0 * 2.0_f64.powi(970), 0.0, f64::MAX, 10.0], [3.0 * 2.0_f64.powi(970), 0.0, f64::MAX, 10.0]), ] { let warp = Warp { style: "warpCustom".into(), bounds, cols: 2, rows: 1, mesh: grid(2, 1, 20.0, 10.0), ..Warp::default() }; let descriptor = warp.quilt_descriptor().unwrap(); @@ -332,7 +345,7 @@ mod tests { assert_eq!(Warp::try_from_descriptor(&high_offset.quilt_descriptor().unwrap()).unwrap(), Some(high_offset)); // At the placed-layer boundary content size is available: preserve the // evaluator's fallback mapping, not merely the ability to parse the output. - for bounds in [[0.0; 4], [2.0, 3.0, 22.0, 3.0], [f64::NAN, 0.0, 20.0, 10.0]] { + for bounds in [[0.0; 4], [2.0, 3.0, 22.0, 3.0], [f64::NAN, 0.0, 20.0, 10.0], [-f64::MAX, 0.0, f64::MAX, 10.0]] { let warp = Warp { style: "warpCustom".into(), bounds, cols: 2, rows: 1, mesh: grid(2, 1, 20.0, 10.0), ..Warp::default() }; let so = SmartObject { size: Some([20.0, 10.0]), ..placed(Some(warp.clone())) }; let bytes = so.to_placed_layer_data(&PlacedLayerOptions::default()); @@ -348,6 +361,36 @@ mod tests { } } #[test] + fn canonically_collapsed_boundaries_preserve_both_axes_mapping() { + let lo = 1e16; + let hi = lo + 2.0; + for (cols, rows, bounds, axis) in + [(4, 1, [lo, 0.0, hi, 10.0], "quiltSliceX"), (1, 4, [0.0, lo, 20.0, hi], "quiltSliceY"), (4, 4, [lo, lo, hi, hi], "quiltSliceX")] + { + let warp = Warp { style: "warpCustom".into(), bounds, cols, rows, mesh: grid(cols, rows, 20.0, 10.0), ..Warp::default() }; + let descriptor = warp.quilt_descriptor().unwrap(); + let env = descriptor.get_object("customEnvelopeWarp").unwrap(); + let Value::ObjectArray(slices) = env.get(axis).unwrap() else { panic!("slices") }; + let values = slices.body.get_numbers(axis); + assert_eq!(values, vec![lo, lo, lo, hi, hi]); + // The first, middle and last intervals all have rounded coincident endpoints. + assert_eq!(values[0], values[1]); + assert_eq!(values[1], values[2]); + assert_eq!(values[3], values[4]); + let so = placed(Some(warp.clone())); + let bytes = so.to_placed_layer_data(&PlacedLayerOptions::default()); + let back = SmartObject::from_placed_layer_data(&bytes).unwrap(); + assert_eq!(back.warp, Some(warp.clone())); + let parsed = back.warp.as_ref().unwrap(); + for p in [[bounds[0], bounds[1]], [bounds[2], bounds[1]], [bounds[0], bounds[3]], [bounds[2], bounds[3]]] { + assert_eq!(parsed.apply(p, 20.0, 10.0), warp.apply(p, 20.0, 10.0)); + } + let template = VersionedDescriptor::parse_prefix(&bytes[8..]).unwrap().0.descriptor; + let rewritten = back.to_placed_layer_data(&PlacedLayerOptions { template: Some(&template), ..Default::default() }); + assert_eq!(SmartObject::from_placed_layer_data(&rewritten).unwrap(), back); + } + } + #[test] fn templates_drop_unsupported_quilts_but_retain_valid_none() { let bounds = [0.0, 0.0, 20.0, 10.0]; let unfl = |values| Value::UnitFloats { unit: *b"#Pxl", values }; From c9862964df7f73ad37706539a06e346fc4865ca3 Mon Sep 17 00:00:00 2001 From: FredApps Date: Wed, 18 Nov 2026 09:38:28 +0100 Subject: [PATCH 51/56] psd: require complete numeric explicit quilt bounds --- crates/psd/src/smart.rs | 42 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) diff --git a/crates/psd/src/smart.rs b/crates/psd/src/smart.rs index 0cd5ac433..32cec043c 100644 --- a/crates/psd/src/smart.rs +++ b/crates/psd/src/smart.rs @@ -153,6 +153,13 @@ impl Warp { let cols = quilt_patches(&slice_x)?; let rows = quilt_patches(&slice_y)?; if !slice_x.is_empty() || !slice_y.is_empty() { + // Defaulting a missing or nonnumeric side to zero would invent an + // explicit rectangle. Numeric nonfinite sides still follow finite(). + if d.get("bounds").is_some() + && !d.get_object("bounds").is_some_and(|b| ["Left", "Top ", "Rght", "Btom"].iter().all(|key| b.get_number(key).is_some())) + { + return Err(PsdError::Unsupported("incomplete explicit quilt bounds".into())); + } // The evaluator normalizes over bounds, not stored slice coordinates. // Infer an absent rectangle only when both explicit axes define it. if !valid_bounds(w.bounds) { @@ -1177,6 +1184,41 @@ mod tests { assert!(Warp::try_from_descriptor(&overflow).is_err()); } #[test] + fn explicit_quilt_bounds_require_every_numeric_side() { + let sides = [("Left", 0.0), ("Top ", 0.0), ("Rght", 20.0), ("Btom", 10.0)]; + for omit_y in [false, true] { + let mut quilt = quilt_descriptor(vec![0.0, 10.0, 20.0], vec![0.0, 10.0]); + if omit_y { + let Value::Descriptor(env) = &mut quilt.items.iter_mut().find(|(key, _)| key.is("customEnvelopeWarp")).unwrap().1 else { + panic!("envelope") + }; + env.items.retain(|(key, _)| !key.is("quiltSliceY")); + } + let complete = sides.iter().fold(Descriptor::new("bounds"), |d, (key, value)| d.with(key, Value::Double(*value))); + assert!(Warp::try_from_descriptor(&quilt.clone().with("bounds", Value::Descriptor(complete))).unwrap().is_some()); + for (side, _) in sides { + for missing in [true, false] { + let bounds = sides.iter().fold(Descriptor::new("bounds"), |d, (key, value)| { + if *key != side { + d.with(key, Value::Double(*value)) + } else if missing { + d + } else { + d.with(key, Value::Text(UnicodeString::new("not a number"))) + } + }); + let invalid = quilt.clone().with("bounds", Value::Descriptor(bounds)); + assert!( + matches!(Warp::try_from_descriptor(&invalid), Err(PsdError::Unsupported(_))), + "{side}, missing={missing}, omit_y={omit_y}" + ); + let bytes = placed_layer_data("incomplete", [0.0; 8], |d| d.with("quiltWarp", Value::Descriptor(invalid))); + assert!(matches!(SmartObject::from_placed_layer_data(&bytes), Err(PsdError::Unsupported(_)))); + } + } + } + } + #[test] fn finite_warp_views_preserve_raw_descriptor_values() { let mut warp = quilt_descriptor(vec![0.0, 10.0, 20.0], vec![0.0, 10.0]); let bounds = Descriptor::new("bounds") From d78a99a0a79dcec0ee9cdc49a415c7fd38607454 Mon Sep 17 00:00:00 2001 From: FredApps Date: Wed, 18 Nov 2026 10:10:41 +0100 Subject: [PATCH 52/56] psd: validate explicit bounds in unsliced quilt context --- crates/psd/src/smart.rs | 121 +++++++++++++++++++++++++++++++--- crates/psd/src/smart/write.rs | 8 ++- 2 files changed, 117 insertions(+), 12 deletions(-) diff --git a/crates/psd/src/smart.rs b/crates/psd/src/smart.rs index 32cec043c..8cc140490 100644 --- a/crates/psd/src/smart.rs +++ b/crates/psd/src/smart.rs @@ -71,6 +71,20 @@ fn finite(value: f64) -> f64 { fn valid_bounds([l, t, r, b]: [f64; 4]) -> bool { [l, t, r, b].iter().all(|v| v.is_finite()) && (r - l).is_finite() && r > l && (b - t).is_finite() && b > t } +/// Explicit quilt rectangles must be complete even without subdivision keys. +fn validate_quilt_bounds(d: &Descriptor) -> Result<()> { + if d.get("bounds").is_none() { + return Ok(()); + } + let bounds = d + .get_object("bounds") + .and_then(|b| Some([b.get_number("Left")?, b.get_number("Top ")?, b.get_number("Rght")?, b.get_number("Btom")?])) + .ok_or_else(|| PsdError::Unsupported("incomplete explicit quilt bounds".into()))?; + if !valid_bounds(bounds.map(finite)) { + return Err(PsdError::Unsupported("invalid explicit quilt bounds".into())); + } + Ok(()) +} /// The corner quad (top-left, top-right, bottom-right, bottom-left) from x0 y0 … x3 y3. fn quad_from(t: [f64; 8]) -> [[f64; 2]; 4] { [[t[0], t[1]], [t[2], t[3]], [t[4], t[5]], [t[6], t[7]]] @@ -133,6 +147,14 @@ impl Warp { /// uniform-model contract, not a guarantee of other readers' handling of coincident slices. /// Nonfinite geometry becomes zero. pub fn try_from_descriptor(d: &Descriptor) -> Result> { + Self::try_from_descriptor_kind(d, d.class_id.is("quiltWarp")) + } + + // The containing SoLd key is authoritative even if an embedded class differs. + fn try_from_descriptor_kind(d: &Descriptor, quilt: bool) -> Result> { + if quilt { + validate_quilt_bounds(d)?; + } let style = d.get_enum("warpStyle").unwrap_or_else(|| "warpNone".to_string()); let side = |b: &Descriptor, k: &str| finite(b.get_number(k).unwrap_or(0.0)); let bounds = d.get_object("bounds").map_or([0.0; 4], |b| [side(b, "Left"), side(b, "Top "), side(b, "Rght"), side(b, "Btom")]); @@ -153,13 +175,8 @@ impl Warp { let cols = quilt_patches(&slice_x)?; let rows = quilt_patches(&slice_y)?; if !slice_x.is_empty() || !slice_y.is_empty() { - // Defaulting a missing or nonnumeric side to zero would invent an - // explicit rectangle. Numeric nonfinite sides still follow finite(). - if d.get("bounds").is_some() - && !d.get_object("bounds").is_some_and(|b| ["Left", "Top ", "Rght", "Btom"].iter().all(|key| b.get_number(key).is_some())) - { - return Err(PsdError::Unsupported("incomplete explicit quilt bounds".into())); - } + validate_quilt_bounds(d)?; + // The evaluator normalizes over bounds, not stored slice coordinates. // Infer an absent rectangle only when both explicit axes define it. if !valid_bounds(w.bounds) { @@ -366,9 +383,9 @@ impl SmartObject { let t = eight(&d, "nonAffineTransform").unwrap_or(t); let size = d.get_object("Sz ").and_then(|s| Some([finite(s.get_number("Wdth")?), finite(s.get_number("Hght")?)])); // A split warp is in `quiltWarp`, with `warp` holding none. - let mut warp = d.get_object("quiltWarp").map(Warp::try_from_descriptor).transpose()?.flatten(); + let mut warp = d.get_object("quiltWarp").map(|q| Warp::try_from_descriptor_kind(q, true)).transpose()?.flatten(); if warp.is_none() { - warp = d.get_object("warp").map(Warp::try_from_descriptor).transpose()?.flatten(); + warp = d.get_object("warp").map(|w| Warp::try_from_descriptor_kind(w, false)).transpose()?.flatten(); } Ok(SmartObject { uuid, quad: quad_from(t), size, warp }) } @@ -1184,6 +1201,92 @@ mod tests { assert!(Warp::try_from_descriptor(&overflow).is_err()); } #[test] + fn quilt_bounds_policy_covers_every_slice_axis_and_descriptor_context() { + let rect = |l, t, r, b| { + Value::Descriptor( + Descriptor::new("bounds") + .with("Left", Value::Double(l)) + .with("Top ", Value::Double(t)) + .with("Rght", Value::Double(r)) + .with("Btom", Value::Double(b)), + ) + }; + let cases = [ + (None, true), + (Some(rect(0.0, 0.0, 20.0, 10.0)), true), + (Some(Value::Integer(0)), false), + ( + Some(Value::Descriptor( + Descriptor::new("bounds").with("Left", Value::Double(0.0)).with("Rght", Value::Double(20.0)).with("Btom", Value::Double(10.0)), + )), + false, + ), + ( + Some(Value::Descriptor( + Descriptor::new("bounds") + .with("Left", Value::Double(0.0)) + .with("Top ", Value::Text(UnicodeString::new("bad"))) + .with("Rght", Value::Double(20.0)) + .with("Btom", Value::Double(10.0)), + )), + false, + ), + (Some(rect(0.0, 10.0, 20.0, 10.0)), false), + (Some(rect(0.0, -f64::MAX, 20.0, f64::MAX)), false), + (Some(rect(f64::NAN, f64::NEG_INFINITY, 20.0, 10.0)), true), + ]; + for axes in 0..4 { + for class in ["warp", "quiltWarp"] { + for (bounds, valid) in &cases { + let mut d = Warp { + style: "warpCustom".into(), + cols: 1, + rows: 1, + mesh: (0..4).flat_map(|y| (0..4).map(move |x| [x as f64 * 20.0 / 3.0, y as f64 * 10.0 / 3.0])).collect(), + ..Warp::default() + } + .to_descriptor(); + d.class_id = Id::new(class); + d.items.retain(|(key, _)| !key.is("bounds")); + if let Some(bounds) = bounds { + d.items.push((Id::new("bounds"), bounds.clone())); + } + let Value::Descriptor(env) = &mut d.items.iter_mut().find(|(key, _)| key.is("customEnvelopeWarp")).unwrap().1 else { + panic!("envelope") + }; + for (bit, key, end) in [(1, "quiltSliceX", 20.0), (2, "quiltSliceY", 10.0)] { + if axes & bit != 0 { + env.items.push((Id::new(key), Value::UnitFloats { unit: *b"#Pxl", values: vec![0.0, end] })); + } + } + let expected = |quilt| { + if bounds.is_none() { axes == 0 || axes == 3 } else { *valid || (!quilt && axes == 0) } + }; + assert_eq!( + Warp::try_from_descriptor(&d).is_ok(), + expected(class == "quiltWarp"), + "direct {class}, axes={axes}, bounds={bounds:?}" + ); + for field in ["warp", "quiltWarp"] { + let bytes = placed_layer_data("context", [0.0; 8], |parent| parent.with(field, Value::Descriptor(d.clone()))); + assert_eq!( + SmartObject::from_placed_layer_data(&bytes).is_ok(), + expected(field == "quiltWarp"), + "{field}/{class}, axes={axes}, bounds={bounds:?}" + ); + } + } + } + } + // No envelope and identity style must not bypass explicit quilt bounds. + for class in ["warp", "quiltWarp"] { + let d = Descriptor::new(class).with("bounds", rect(0.0, 10.0, 20.0, 10.0)); + assert_eq!(Warp::try_from_descriptor(&d).is_ok(), class == "warp"); + let bytes = placed_layer_data("identity", [0.0; 8], |parent| parent.with("quiltWarp", Value::Descriptor(d))); + assert!(SmartObject::from_placed_layer_data(&bytes).is_err()); + } + } + #[test] fn explicit_quilt_bounds_require_every_numeric_side() { let sides = [("Left", 0.0), ("Top ", 0.0), ("Rght", 20.0), ("Btom", 10.0)]; for omit_y in [false, true] { diff --git a/crates/psd/src/smart/write.rs b/crates/psd/src/smart/write.rs index f1edf82df..6976417b2 100644 --- a/crates/psd/src/smart/write.rs +++ b/crates/psd/src/smart/write.rs @@ -206,8 +206,9 @@ impl SmartObject { } set(&mut d, "warp", Value::Descriptor(warp.to_descriptor())); // The imported `quiltWarp` stays while it still says what the warp is. - let kept = - t.get_object("quiltWarp").is_some_and(|q| Warp::try_from_descriptor(q).is_ok_and(|parsed| parsed.as_ref() == self.warp.as_ref())); + let kept = t + .get_object("quiltWarp") + .is_some_and(|q| Warp::try_from_descriptor_kind(q, true).is_ok_and(|parsed| parsed.as_ref() == self.warp.as_ref())); if !kept { match quilt { Some(q) => set_before(&mut d, "quiltWarp", Value::Descriptor(q), "warp"), @@ -404,7 +405,8 @@ mod tests { assert!(Warp::try_from_descriptor(&unequal).is_err()); let valid_none = Warp::none(bounds).to_descriptor(); assert!(matches!(Warp::try_from_descriptor(&valid_none), Ok(None))); - for (quilt, keep) in [(unequal, false), (valid_none, true)] { + let invalid_none = Warp::none([0.0, 10.0, 20.0, 10.0]).to_descriptor(); + for (quilt, keep) in [(unequal, false), (valid_none, true), (invalid_none, false)] { let template = Descriptor::new("null").with("quiltWarp", Value::Descriptor(quilt.clone())); let bytes = placed(None).to_placed_layer_data(&PlacedLayerOptions { placed: "layer", From e1fc4b1376148197c2cfd2381eeb400e2731269a Mon Sep 17 00:00:00 2001 From: FredApps Date: Wed, 18 Nov 2026 10:39:08 +0100 Subject: [PATCH 53/56] psd: annotate quilt policy test closure parameter --- crates/psd/src/smart.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/psd/src/smart.rs b/crates/psd/src/smart.rs index 8cc140490..38f382292 100644 --- a/crates/psd/src/smart.rs +++ b/crates/psd/src/smart.rs @@ -1259,7 +1259,7 @@ mod tests { env.items.push((Id::new(key), Value::UnitFloats { unit: *b"#Pxl", values: vec![0.0, end] })); } } - let expected = |quilt| { + let expected = |quilt: bool| { if bounds.is_none() { axes == 0 || axes == 3 } else { *valid || (!quilt && axes == 0) } }; assert_eq!( From abde74fa7dcb6e35beffa6cb98e90ba5595d33ba Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 18 Nov 2026 06:33:33 -0500 Subject: [PATCH 54/56] fix(mcmat): validate manifests and read resources by index --- crates/mcmat/src/lib.rs | 90 +++++++++++++++++++++++++++++++++------ crates/zip/src/archive.rs | 34 +++++++++++++++ 2 files changed, 110 insertions(+), 14 deletions(-) diff --git a/crates/mcmat/src/lib.rs b/crates/mcmat/src/lib.rs index fe328cceb..ca3fa7641 100644 --- a/crates/mcmat/src/lib.rs +++ b/crates/mcmat/src/lib.rs @@ -3,7 +3,8 @@ //! The clean-room MCMAT v3 source archive. Applications interpret the SBS entry graph. use craft_zip::{Archive, Compression, Writer}; -use serde::Deserialize; +use serde::Deserializer; +use serde::de::{IgnoredAny, MapAccess, Visitor}; use std::collections::{BTreeMap, BTreeSet}; pub const VERSION: u32 = 3; @@ -62,20 +63,36 @@ impl Material { return Err(Error::Invalid("duplicate or overlapping archive entries".into())); } let json = archive.read(MANIFEST_ENTRY, limits.max_manifest_bytes)?.ok_or_else(|| Error::Invalid("missing material.json".into()))?; - #[derive(Deserialize)] - struct Version { - version: u32, + struct Marker; + impl<'de> Visitor<'de> for Marker { + type Value = (u32, bool); + fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("a version object") + } + fn visit_map>(self, mut map: A) -> Result { + let mut version = None; + let mut extra = false; + while let Some(key) = map.next_key::()? { + if key == "version" { + if version.is_some() { + return Err(serde::de::Error::duplicate_field("version")); + } + version = Some(map.next_value::()?); + } else { + map.next_value::()?; + extra = true; + } + } + Ok((version.ok_or_else(|| serde::de::Error::missing_field("version"))?, extra)) + } } - let marker: Version = serde_json::from_slice(&json).map_err(|err| Error::Invalid(format!("material.json: {err}")))?; - if marker.version != VERSION { - return Err(Error::Version(marker.version)); + let mut deserializer = serde_json::Deserializer::from_slice(&json); + let (version, extra) = deserializer.deserialize_map(Marker).map_err(|err| Error::Invalid(format!("material.json: {err}")))?; + deserializer.end().map_err(|err| Error::Invalid(format!("material.json: {err}")))?; + if version != VERSION { + return Err(Error::Version(version)); } - #[derive(Deserialize)] - #[serde(deny_unknown_fields)] - struct Marker { - version: u32, - } - if !serde_json::from_slice::(&json).is_ok_and(|m| m.version == VERSION) { + if extra { return Err(Error::Invalid("material.json must contain only the version".into())); } let source = archive.read(SOURCE_ENTRY, limits.max_entry_bytes)?.ok_or_else(|| Error::Invalid("missing source.sbs".into()))?; @@ -87,12 +104,15 @@ impl Material { continue; } if name.strip_suffix('/').is_some_and(|dir| dir == "resources" || valid_resource(dir)) { + if archive.entry_sizes(index)? != Some((0, 0)) { + return Err(Error::Invalid("directory entries must have no payload".into())); + } continue; } if !valid_resource(&name) || !seen.insert(name.to_ascii_lowercase()) { return Err(Error::Invalid(format!("invalid or ambiguous resource path `{name}`"))); } - let data = archive.read(&name, limits.max_entry_bytes)?.ok_or_else(|| Error::Invalid(format!("missing `{name}`")))?; + let data = archive.read_index(index, limits.max_entry_bytes)?.ok_or_else(|| Error::Invalid(format!("missing `{name}`")))?; resources.insert(name, data); } Ok(Self { source, resources }) @@ -151,6 +171,48 @@ mod tests { } } + #[test] + fn marker_requires_an_object_and_complete_input() { + for marker in [b"[3]".as_slice(), b"[2]", b"null", b"3", br#"{"version":3} {}"#, br#"{"version":3,"version":3}"#] { + let mut zip = Writer::new(); + zip.add(MANIFEST_ENTRY, marker, Compression::Stored).unwrap(); + zip.add(SOURCE_ENTRY, b"source", Compression::Stored).unwrap(); + assert!(matches!(Material::open(&zip.finish().unwrap(), Limits::default()), Err(Error::Invalid(_)))); + } + } + + #[test] + fn directory_members_must_be_empty() { + for payload in [b"".as_slice(), b"hidden"] { + let mut zip = Writer::new(); + zip.add(MANIFEST_ENTRY, MARKER, Compression::Stored).unwrap(); + zip.add(SOURCE_ENTRY, b"source", Compression::Stored).unwrap(); + zip.add("resources/", payload, Compression::Stored).unwrap(); + assert_eq!(Material::open(&zip.finish().unwrap(), Limits::default()).is_ok(), payload.is_empty()); + } + } + + #[test] + fn legacy_encoded_resource_names_read_by_index_under_one_budget() { + let mut zip = Writer::new(); + zip.add(MANIFEST_ENTRY, MARKER, Compression::Stored).unwrap(); + zip.add(SOURCE_ENTRY, b"s", Compression::Stored).unwrap(); + zip.add("resources/a.bin", b"data", Compression::Stored).unwrap(); + let mut bytes = zip.finish().unwrap(); + // Same-length CP437 name in both headers: no UTF-8 flag, 0x82 decodes to é. + let offsets: Vec<_> = + bytes.windows(b"resources/a.bin".len()).enumerate().filter_map(|(i, n)| (n == b"resources/a.bin").then_some(i + 10)).collect(); + assert_eq!(offsets.len(), 2); + for offset in offsets { + bytes[offset] = 0x82; + } + let total = MARKER.len() as u64 + 1 + 4; + let limits = Limits { max_total_bytes: total, ..Default::default() }; + let material = Material::open(&bytes, limits).unwrap(); + assert_eq!(material.resources["resources/é.bin"], b"data"); + assert!(Material::open(&bytes, Limits { max_total_bytes: total - 1, ..limits }).is_err()); + } + #[test] fn compresses_unencoded_source_assets() { let bytes = write(b"", [("resources/shape.svg", b"".as_slice()), ("resources/font.ttf", b"font".as_slice())]).unwrap(); diff --git a/crates/zip/src/archive.rs b/crates/zip/src/archive.rs index 49da63585..d00be89d0 100644 --- a/crates/zip/src/archive.rs +++ b/crates/zip/src/archive.rs @@ -108,6 +108,15 @@ impl<'a> Archive<'a> { Ok(Some(file.is_dir())) } + /// Declared decoded and compressed sizes at `index`, without name lookup. + pub fn entry_sizes(&mut self, index: usize) -> Result, Error> { + if index >= self.zip.len() { + return Ok(None); + } + let file = self.zip.by_index_raw(index).map_err(|e| Error::NotZip(e.to_string()))?; + Ok(Some((file.size(), file.compressed_size()))) + } + /// Do two entries share a name? `zip` then keeps one of them, and which one a writer meant /// is not known: a format that must not guess refuses the archive. pub fn has_duplicate_names(&self) -> bool { @@ -178,6 +187,16 @@ impl<'a> Archive<'a> { /// Only the bytes of a read that succeeds are charged to the total. pub fn read(&mut self, name: &str, max: u64) -> Result>, Error> { let Some(index) = self.zip.index_for_name(name) else { return Ok(None) }; + self.read_index(index, max) + } + + /// Read the entry at `index` under the same size, checksum and aggregate budget + /// rules as [`Self::read`], without repeating a decoded-name lookup. + pub fn read_index(&mut self, index: usize, max: u64) -> Result>, Error> { + if index >= self.zip.len() { + return Ok(None); + } + let name = self.entry_name(index)?.unwrap_or_default(); let entry = |msg: String| Error::Entry { name: name.to_string(), msg }; let f = self.zip.by_index(index).map_err(|e| entry(e.to_string()))?; let declared = f.size(); @@ -213,6 +232,21 @@ impl Archive<'static> { mod ownership_tests { use super::*; + #[test] + fn indexed_reads_charge_the_same_budget_and_enforce_entry_limits() { + let mut writer = crate::Writer::new(); + writer.add("a", b"abc", crate::Compression::Stored).unwrap(); + writer.add("b", b"def", crate::Compression::Deflated).unwrap(); + let bytes = writer.finish().unwrap(); + let mut archive = Archive::open(&bytes, Limits { max_entries: 2, max_total_bytes: 5 }).unwrap(); + assert!(archive.read_index(0, 2).is_err()); + assert_eq!(archive.read_index(0, 3).unwrap().unwrap(), b"abc"); + assert!(archive.read_index(1, 3).is_err()); + assert_eq!(archive.read_index(2, 3).unwrap(), None); + assert_eq!(archive.entry_sizes(0).unwrap(), Some((3, 3))); + assert_eq!(archive.entry_sizes(2).unwrap(), None); + } + #[test] fn owned_storage_lives_until_last_archive_clone_is_dropped() { let bytes = crate::Writer::new().finish().unwrap(); From 1cc156dcc3c4226f2aa25f3ff341c1cee69e9039 Mon Sep 17 00:00:00 2001 From: David Mann Date: Wed, 18 Nov 2026 12:43:50 +0100 Subject: [PATCH 55/56] ci: skip cargo fmt on the Windows lint leg (#2200) One rustfmt call with every source root of the workspace is now longer than a Windows command line may be (os error 206). rustfmt's result is the same on every system; the Linux and macOS legs keep checking it. The lint-command guard states the per-system stages. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/workspace.yml | 7 ++++++- scripts/test-workspace-tests.py | 11 ++++++++--- 2 files changed, 14 insertions(+), 4 deletions(-) diff --git a/.github/workflows/workspace.yml b/.github/workflows/workspace.yml index af7e04769..5a9e4989d 100644 --- a/.github/workflows/workspace.yml +++ b/.github/workflows/workspace.yml @@ -64,7 +64,12 @@ jobs: python3 scripts/test-workspace-concurrency.py python3 scripts/test-workspace-tests.py fi - cargo fmt --check + # One rustfmt call gets every source root of the workspace, which is longer than + # Windows allows for a command line (os error 206). rustfmt's result is the same on + # every system, so the Linux and macOS legs check it. + if [ "$RUNNER_OS" != Windows ]; then + cargo fmt --check + fi cargo clippy --workspace --all-targets --locked -- -D warnings cargo clippy --workspace --all-targets --all-features --locked -- -D warnings command: | diff --git a/scripts/test-workspace-tests.py b/scripts/test-workspace-tests.py index 9572cac31..ac65da9c1 100644 --- a/scripts/test-workspace-tests.py +++ b/scripts/test-workspace-tests.py @@ -25,7 +25,9 @@ if [ "$RUNNER_OS" = Linux ]; then python3 scripts/test-workspace-concurrency.py python3 scripts/test-workspace-tests.py fi -cargo fmt --check +if [ "$RUNNER_OS" != Windows ]; then + cargo fmt --check +fi cargo clippy --workspace --all-targets --locked -- -D warnings cargo clippy --workspace --all-targets --all-features --locked -- -D warnings """ @@ -96,11 +98,14 @@ TESTS = [ class WorkspaceTests(unittest.TestCase): def test_every_leg_lints_with_both_feature_sets(self): - for os_name in ("Linux", "macOS", "Windows"): + # Windows skips only rustfmt: one call with every source root of the workspace is longer + # than a Windows command line may be (os error 206), and Linux and macOS check the same + # formatting. + for os_name, expected in (("Linux", COMMON), ("macOS", COMMON), ("Windows", COMMON[1:])): with self.subTest(os=os_name): result = commands(os_name, name="lint-command") self.assertEqual(result.returncode, 0, result.stderr) - self.assertEqual(result.stdout.splitlines(), COMMON) + self.assertEqual(result.stdout.splitlines(), expected) def test_linux_and_macos_run_one_feature_set_with_doctests(self): for os_name in ("Linux", "macOS"): From 74b198524b3909ec376b6a3882f8d1d1b8acd468 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 18 Nov 2026 07:47:03 -0500 Subject: [PATCH 56/56] fix(zip): preserve named read error contracts --- crates/zip/src/archive.rs | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/crates/zip/src/archive.rs b/crates/zip/src/archive.rs index d00be89d0..b9b3b3d80 100644 --- a/crates/zip/src/archive.rs +++ b/crates/zip/src/archive.rs @@ -187,7 +187,7 @@ impl<'a> Archive<'a> { /// Only the bytes of a read that succeeds are charged to the total. pub fn read(&mut self, name: &str, max: u64) -> Result>, Error> { let Some(index) = self.zip.index_for_name(name) else { return Ok(None) }; - self.read_index(index, max) + self.read_index_named(index, name, max) } /// Read the entry at `index` under the same size, checksum and aggregate budget @@ -197,6 +197,10 @@ impl<'a> Archive<'a> { return Ok(None); } let name = self.entry_name(index)?.unwrap_or_default(); + self.read_index_named(index, &name, max) + } + + fn read_index_named(&mut self, index: usize, name: &str, max: u64) -> Result>, Error> { let entry = |msg: String| Error::Entry { name: name.to_string(), msg }; let f = self.zip.by_index(index).map_err(|e| entry(e.to_string()))?; let declared = f.size(); @@ -232,6 +236,17 @@ impl Archive<'static> { mod ownership_tests { use super::*; + #[test] + fn named_read_preserves_entry_error_for_a_corrupt_local_header() { + let mut writer = crate::Writer::new(); + writer.add("a", b"abc", crate::Compression::Stored).unwrap(); + let mut bytes = writer.finish().unwrap(); + bytes[0] = 0; // The central directory remains valid; the local signature does not. + let mut archive = Archive::open(&bytes, Limits { max_entries: 1, max_total_bytes: 3 }).unwrap(); + assert!(matches!(archive.read("a", 3), Err(Error::Entry { name, .. }) if name == "a")); + assert_eq!(archive.budget().remaining(), 3); + } + #[test] fn indexed_reads_charge_the_same_budget_and_enforce_entry_limits() { let mut writer = crate::Writer::new();