Skip to main content

bilingua_model/
icu.rs

1//! A small ICU MessageFormat parser that keeps the raw text of every piece, so an unchanged message is written
2//! back exactly. Plural, selectordinal and select arguments are split into branches; `{name}` and typed
3//! arguments (`{n, number}`) are simple arguments; quotes (`'{'`, `''`) stay as raw text.
4//!
5//! One parser for every crate that reads ICU messages (json dialects, arb; unit model step 6). It was two
6//! near-copies (`bilingua-json/src/icu.rs`, `bilingua-arb/src/icu.rs`) that parsed alike; the only difference was
7//! the arb copy's `locos` flag on [`translatable`] and [`has_words`], kept here as a flag (`false` is the json
8//! behaviour). [`levels`] walks a parsed message the way both crates cut it into units, with the plural slot of
9//! each branch and, when asked, the branches a target language needs that the source lacks.
10
11const MAX_DEPTH: usize = 40;
12
13/// One piece of a message.
14#[derive(Debug, Clone, PartialEq, Eq)]
15pub enum Part {
16    /// Raw message text (quote marks included).
17    Text(String),
18    /// A simple or typed argument, raw: `{name}`, `{n, number, ::compact}`.
19    Simple(String),
20    /// `#` inside a plural or selectordinal branch.
21    Pound,
22    /// A plural, selectordinal or select argument.
23    Complex(Complex),
24}
25
26/// The kind of a complex argument.
27#[derive(Debug, Clone, Copy, PartialEq, Eq)]
28pub enum Kind {
29    /// `plural`.
30    Plural,
31    /// `selectordinal`.
32    SelectOrdinal,
33    /// `select`.
34    Select,
35}
36
37impl Kind {
38    /// The ICU keyword (`plural`, `selectordinal`, `select`).
39    pub fn word(self) -> &'static str {
40        match self {
41            Kind::Plural => "plural",
42            Kind::SelectOrdinal => "selectordinal",
43            Kind::Select => "select",
44        }
45    }
46
47    /// The plural kind of the model ([`crate::PluralKind`]).
48    pub fn plural_kind(self) -> crate::PluralKind {
49        match self {
50            Kind::Plural => crate::PluralKind::Cardinal,
51            Kind::SelectOrdinal => crate::PluralKind::Ordinal,
52            Kind::Select => crate::PluralKind::Select,
53        }
54    }
55}
56
57/// A plural, selectordinal or select argument with its branches.
58#[derive(Debug, Clone, PartialEq, Eq)]
59pub struct Complex {
60    /// Raw text from `{` through the whitespace before the first selector (and an `offset:n`).
61    pub head: String,
62    /// Plural, selectordinal or select.
63    pub kind: Kind,
64    /// The branches in source order.
65    pub branches: Vec<Branch>,
66}
67
68impl Complex {
69    /// The argument name inside `{name, plural, ...`.
70    pub fn arg(&self) -> String {
71        arg_name(&self.head)
72    }
73
74    /// The first `other` branch.
75    pub fn other(&self) -> Option<&Branch> {
76        self.branches.iter().find(|b| b.selector == "other")
77    }
78}
79
80/// One branch of a complex argument.
81#[derive(Debug, Clone, PartialEq, Eq)]
82pub struct Branch {
83    /// `one`, `=0`, `female`.
84    pub selector: String,
85    /// Whitespace between the selector and `{`.
86    pub mid: String,
87    /// The branch's message.
88    pub msg: Vec<Part>,
89    /// Whitespace after the closing brace.
90    pub trail: String,
91}
92
93/// The message is not valid ICU MessageFormat (or nests too deeply).
94#[derive(Debug)]
95pub struct IcuError;
96
97type R<T> = Result<T, IcuError>;
98
99/// Python `\s` for str patterns: Unicode white space plus the four information separators.
100fn is_ws(c: char) -> bool {
101    crate::py_isspace_char(c)
102}
103
104fn ch(s: &str, i: usize) -> Option<char> {
105    s.get(i..).and_then(|r| r.chars().next())
106}
107
108fn skip_ws(s: &str, mut i: usize) -> usize {
109    while let Some(c) = ch(s, i) {
110        if !is_ws(c) {
111            break;
112        }
113        i += c.len_utf8();
114    }
115    i
116}
117
118/// Parses a whole message. Errors on unbalanced braces, bad arguments or nesting over 40 levels.
119pub fn parse(s: &str) -> R<Vec<Part>> {
120    // Nothing that could be markup: one text part.
121    if !s.bytes().any(|b| matches!(b, b'{' | b'}' | b'\'')) {
122        return Ok(if s.is_empty() { vec![] } else { vec![Part::Text(s.to_string())] });
123    }
124    let (parts, i) = message(s, 0, 0, false, false)?;
125    if i != s.len() {
126        return Err(IcuError);
127    }
128    Ok(parts)
129}
130
131fn message(s: &str, mut i: usize, depth: usize, in_plural: bool, nested: bool) -> R<(Vec<Part>, usize)> {
132    if depth > MAX_DEPTH {
133        return Err(IcuError);
134    }
135    let b = s.as_bytes();
136    let n = b.len();
137    let mut parts = Vec::new();
138    let mut run = i;
139    while i < n {
140        match b[i] {
141            b'{' => {
142                flush(s, &mut parts, run, i);
143                let (p, next) = argument(s, i, depth)?;
144                parts.push(p);
145                i = next;
146                run = i;
147            }
148            b'}' => {
149                if !nested {
150                    return Err(IcuError);
151                }
152                break;
153            }
154            b'#' if in_plural => {
155                flush(s, &mut parts, run, i);
156                parts.push(Part::Pound);
157                i += 1;
158                run = i;
159            }
160            b'\'' => {
161                let nxt = b.get(i + 1).copied();
162                if nxt == Some(b'\'') {
163                    i += 2;
164                } else if matches!(nxt, Some(b'{' | b'}' | b'|')) || (nxt == Some(b'#') && in_plural) {
165                    let mut j = i + 1;
166                    while j < n {
167                        if b[j] == b'\'' {
168                            if b.get(j + 1) == Some(&b'\'') {
169                                j += 2;
170                                continue;
171                            }
172                            break;
173                        }
174                        j += 1;
175                    }
176                    i = j + 1;
177                } else {
178                    i += 1;
179                }
180            }
181            _ => i += 1,
182        }
183    }
184    let end = i.min(n);
185    flush(s, &mut parts, run, end);
186    Ok((parts, i))
187}
188
189fn flush(s: &str, parts: &mut Vec<Part>, from: usize, to: usize) {
190    if to > from {
191        parts.push(Part::Text(s[from..to].to_string()));
192    }
193}
194
195fn argument(s: &str, start: usize, depth: usize) -> R<(Part, usize)> {
196    let mut j = skip_ws(s, start + 1);
197    // name: one or more characters that are not white space or , { } # ' |
198    let name_start = j;
199    while let Some(c) = ch(s, j) {
200        if is_ws(c) || matches!(c, ',' | '{' | '}' | '#' | '\'' | '|') {
201            break;
202        }
203        j += c.len_utf8();
204    }
205    if j == name_start {
206        return Err(IcuError);
207    }
208    j = skip_ws(s, j);
209    let b = s.as_bytes();
210    match b.get(j) {
211        Some(b'}') => return Ok((Part::Simple(s[start..=j].to_string()), j + 1)),
212        Some(b',') => {}
213        _ => return Err(IcuError),
214    }
215    j = skip_ws(s, j + 1);
216    let ty_start = j;
217    while b.get(j).is_some_and(u8::is_ascii_alphabetic) {
218        j += 1;
219    }
220    if j == ty_start {
221        return Err(IcuError);
222    }
223    let kind_word = &s[ty_start..j];
224    j = skip_ws(s, j);
225    match b.get(j) {
226        Some(b'}') => return Ok((Part::Simple(s[start..=j].to_string()), j + 1)),
227        Some(b',') => {}
228        _ => return Err(IcuError),
229    }
230    let kind = match kind_word {
231        "plural" => Kind::Plural,
232        "selectordinal" => Kind::SelectOrdinal,
233        "select" => Kind::Select,
234        _ => {
235            // number, date, time, ...: opaque, brace balanced, quotes skipped
236            let mut level = 1usize;
237            let mut k = j + 1;
238            while k < b.len() && level > 0 {
239                match b[k] {
240                    b'{' => level += 1,
241                    b'}' => level -= 1,
242                    b'\'' => match s[k + 1..].find('\'') {
243                        Some(p) => k = k + 1 + p,
244                        None => k = b.len(),
245                    },
246                    _ => {}
247                }
248                k += 1;
249            }
250            if level > 0 {
251                return Err(IcuError);
252            }
253            return Ok((Part::Simple(s[start..k].to_string()), k));
254        }
255    };
256    j = skip_ws(s, j + 1);
257    if kind != Kind::Select {
258        j = offset(s, j).unwrap_or(j);
259    }
260    let head = s[start..j].to_string();
261    let mut branches = Vec::new();
262    loop {
263        if j >= b.len() {
264            return Err(IcuError);
265        }
266        if b[j] == b'}' {
267            break;
268        }
269        let sel_end = selector_end(s, j).ok_or(IcuError)?;
270        let selector = s[j..sel_end].to_string();
271        let k = skip_ws(s, sel_end);
272        if b.get(k) != Some(&b'{') {
273            return Err(IcuError);
274        }
275        let (msg, k2) = message(s, k + 1, depth + 1, kind != Kind::Select, true)?;
276        if b.get(k2) != Some(&b'}') {
277            return Err(IcuError);
278        }
279        let t = skip_ws(s, k2 + 1);
280        branches.push(Branch { selector, mid: s[sel_end..k].to_string(), msg, trail: s[k2 + 1..t].to_string() });
281        j = t;
282    }
283    if branches.is_empty() {
284        return Err(IcuError);
285    }
286    Ok((Part::Complex(Complex { head, kind, branches }), j + 1))
287}
288
289/// `offset\s*:\s*\d+\s*` at `j`: the index after it.
290fn offset(s: &str, j: usize) -> Option<usize> {
291    let rest = s.get(j..)?.strip_prefix("offset")?;
292    let mut k = skip_ws(s, s.len() - rest.len());
293    if s.as_bytes().get(k) != Some(&b':') {
294        return None;
295    }
296    k = skip_ws(s, k + 1);
297    let d0 = k;
298    while s.as_bytes().get(k).is_some_and(u8::is_ascii_digit) {
299        k += 1;
300    }
301    if k == d0 {
302        return None;
303    }
304    Some(skip_ws(s, k))
305}
306
307/// End of a selector at `j`: `=-?\d+(\.\d+)?` first, else any run without white space or braces.
308fn selector_end(s: &str, j: usize) -> Option<usize> {
309    let b = s.as_bytes();
310    if b.get(j) == Some(&b'=') {
311        let mut k = j + 1;
312        if b.get(k) == Some(&b'-') {
313            k += 1;
314        }
315        let d0 = k;
316        while b.get(k).is_some_and(u8::is_ascii_digit) {
317            k += 1;
318        }
319        if k > d0 {
320            if b.get(k) == Some(&b'.') && b.get(k + 1).is_some_and(u8::is_ascii_digit) {
321                k += 1;
322                while b.get(k).is_some_and(u8::is_ascii_digit) {
323                    k += 1;
324                }
325            }
326            return Some(k);
327        }
328    }
329    let mut k = j;
330    while let Some(c) = ch(s, k) {
331        if is_ws(c) || c == '{' || c == '}' {
332            break;
333        }
334        k += c.len_utf8();
335    }
336    (k > j).then_some(k)
337}
338
339/// True when the level has a letter or digit in its text or simple arguments (tokens do not count). With `locos`
340/// a literal `⟦x<digits>⟧` in the text is a token too and does not count (LocOS `_translatable`), so a message
341/// that is only such a token has no unit. (The json crate passes `false`, the arb crate its profile flag.)
342pub fn translatable(parts: &[Part], locos: bool) -> bool {
343    parts.iter().any(|p| match p {
344        Part::Text(t) | Part::Simple(t) => has_words(t, locos),
345        _ => false,
346    })
347}
348
349/// A letter or digit in `t`, after removing LocOS argument tokens when `locos`.
350pub fn has_words(t: &str, locos: bool) -> bool {
351    const OPEN: &str = "\u{27E6}x";
352    const CLOSE: char = '\u{27E7}';
353    if !locos || !t.contains(OPEN) {
354        return crate::py_has_alnum(t);
355    }
356    let mut rest = t;
357    let mut kept = String::new();
358    while let Some(at) = rest.find(OPEN) {
359        let after = &rest[at + OPEN.len()..];
360        let d = after.chars().take_while(|c| crate::py_isdecimal_char(*c)).map(char::len_utf8).sum::<usize>();
361        if d > 0 && after[d..].starts_with(CLOSE) {
362            kept.push_str(&rest[..at]);
363            rest = &after[d + CLOSE.len_utf8()..];
364        } else {
365            let skip = at + '\u{27E6}'.len_utf8();
366            kept.push_str(&rest[..skip]);
367            rest = &rest[skip..];
368        }
369    }
370    kept.push_str(rest);
371    crate::py_has_alnum(&kept)
372}
373
374/// The argument name inside `{name, plural, ...`.
375pub fn arg_name(head: &str) -> String {
376    let inner = head.trim_start_matches('{').trim_start();
377    inner.split([',', '}']).next().unwrap_or("").trim().to_string()
378}
379
380// ---------------------------------------------------------------------------------------------------------
381// Levels and plural slots (unit model step 6)
382
383/// Where one branch sits among the plural and select arguments of its message. Group numbers count the complex
384/// arguments of one message in pre-order, from 0 (added branches included), so a crate makes a document-wide group
385/// name from them and the message's first unit id.
386#[derive(Debug, Clone, PartialEq, Eq)]
387pub struct BranchSlot {
388    /// The complex argument the branch belongs to.
389    pub group: usize,
390    /// The complex argument around that one, for a plural inside a select (or any nesting).
391    pub parent: Option<usize>,
392    /// Plural, selectordinal or select.
393    pub kind: Kind,
394    /// The argument name (`count`).
395    pub arg: String,
396    /// The selector (`one`, `=0`, `female`).
397    pub category: String,
398    /// A target category the source does not have, or a level inside such a branch.
399    pub added: bool,
400}
401
402/// One level of a message: the message itself or a branch, with the path the crates write to `extra["icu"]`
403/// (`count: plural one`, `n: plural one / g: select x`; empty for the message's own text).
404#[derive(Debug, Clone)]
405pub struct Level<'a> {
406    /// The level's pieces.
407    pub parts: &'a [Part],
408    /// The path of the level in the message.
409    pub path: String,
410    /// The branch's slot; `None` for the message's own text.
411    pub slot: Option<BranchSlot>,
412}
413
414/// The target categories `cats` that the plural or selectordinal `cx` lacks, in the order of `cats`: the
415/// branches a merge for that target fills from `other`. Empty for a select and for an argument without `other`
416/// (the merge fills nothing then).
417pub fn missing<'c>(cx: &Complex, cats: &[&'c str]) -> Vec<&'c str> {
418    if cx.kind == Kind::Select || cx.other().is_none() {
419        return vec![];
420    }
421    cats.iter().copied().filter(|c| !cx.branches.iter().any(|b| b.selector == *c)).collect()
422}
423
424/// Every level of a parsed message in pre-order, the order the crates make units in: the level itself, then for
425/// each complex argument its branches in source order, then (when `cats` gives the target categories of a kind)
426/// one copy of the `other` branch for each category the argument lacks ([`missing`]), marked `added`.
427pub fn levels<'a>(parts: &'a [Part], cats: &dyn Fn(Kind) -> Option<Vec<&'static str>>) -> Vec<Level<'a>> {
428    let mut out = Vec::new();
429    let mut groups = 0usize;
430    walk(parts, String::new(), None, false, cats, &mut groups, &mut out);
431    out
432}
433
434fn walk<'a>(
435    parts: &'a [Part],
436    path: String,
437    slot: Option<BranchSlot>,
438    added: bool,
439    cats: &dyn Fn(Kind) -> Option<Vec<&'static str>>,
440    groups: &mut usize,
441    out: &mut Vec<Level<'a>>,
442) {
443    let parent = slot.as_ref().map(|s| s.group);
444    out.push(Level { parts, path: path.clone(), slot });
445    for p in parts {
446        let Part::Complex(cx) = p else { continue };
447        let group = *groups;
448        *groups += 1;
449        let arg = cx.arg();
450        let here = if path.is_empty() { String::new() } else { format!("{path} / ") };
451        let branch = |selector: &str, added: bool| BranchSlot { group, parent, kind: cx.kind, arg: arg.clone(), category: selector.to_string(), added };
452        for b in &cx.branches {
453            walk(&b.msg, format!("{here}{arg}: {} {}", cx.kind.word(), b.selector), Some(branch(&b.selector, added)), added, cats, groups, out);
454        }
455        if cx.kind == Kind::Select {
456            continue;
457        }
458        let (Some(want), Some(other)) = (cats(cx.kind), cx.other()) else { continue };
459        for c in missing(cx, &want) {
460            walk(&other.msg, format!("{here}{arg}: {} {c}", cx.kind.word()), Some(branch(c, true)), true, cats, groups, out);
461        }
462    }
463}
464
465/// The hidden key ([`crate::Unit::hidden`]) of a unit added for a target category the source lacks: its ICU path
466/// (`count: plural few`). A merge checks it against its own plan, so a document extracted for one language and
467/// merged for another (`few` against `two`) never writes one category's text as another's.
468pub const ADDED_HIDDEN: &str = "icu_added";
469
470/// True when `unit` is what a plan expects at its place: an added unit with the same ICU path where the plan has
471/// an added level (`added_path`), no added mark where it has a source level.
472pub fn added_matches(unit: &crate::Unit, added_path: Option<&str>) -> bool {
473    unit.hidden(ADDED_HIDDEN) == added_path
474}
475
476// ---------------------------------------------------------------------------------------------------------
477// Added forms of key-style plurals (unit model step 7)
478
479/// The [`ADDED_HIDDEN`] value of a unit added for a key-style plural form (Android `<item quantity>`, stringsdict
480/// keys, i18next `_few` keys, Rails YAML keys, Fluent variants): the category and every category of the target it
481/// was added for, `few of one few many other`. A merge uses the unit only when its own target categories are the
482/// same list ([`key_added`]), so a document extracted for Polish and merged for Slovenian never writes Polish
483/// `few` as Slovenian `few`.
484pub fn key_added_mark(category: &str, cats: &[&str]) -> String {
485    format!("{category} of {}", cats.join(" "))
486}
487
488/// How a merge whose target has the categories `cats` treats one unit ([`key_added`]).
489#[derive(Debug, Clone, Copy, PartialEq, Eq)]
490pub enum KeyAdded<'u> {
491    /// Not an added key-style form.
492    No,
493    /// Added for this category of the same target categories: the merge may write it.
494    Fits(&'u str),
495    /// Added for another target's categories (or the merge has no target): the merge must not write it.
496    Foreign,
497}
498
499/// Reads a unit's [`key_added_mark`] against the merge's target categories (`None`: the merge has no target).
500pub fn key_added<'u>(unit: &'u crate::Unit, cats: Option<&[&str]>) -> KeyAdded<'u> {
501    let Some((cat, list)) = unit.hidden(ADDED_HIDDEN).and_then(|m| m.split_once(" of ")) else { return KeyAdded::No };
502    match cats {
503        Some(cats) if list.split(' ').eq(cats.iter().copied()) && cats.contains(&cat) => KeyAdded::Fits(cat),
504        _ => KeyAdded::Foreign,
505    }
506}
507
508/// True when a unit has a target in some segment (a translator wrote it).
509pub fn has_any_target(unit: &crate::Unit) -> bool {
510    unit.segments.iter().any(|s| s.has_target())
511}
512
513/// The error a merge gives for a translated unit that was added for another target's plural categories: writing
514/// it would put one language's form under another's category.
515pub fn foreign_added_error(unit: &crate::Unit) -> crate::Error {
516    crate::Error::TargetChanged { unit: unit.id.clone() }
517}
518
519/// The first unit of `units` added for a plural category ([`ADDED_HIDDEN`]) whose mark is not one the merge's own
520/// plan adds (`fits`: the ICU paths of its added levels). A json or arb merge whose plans do not line up calls it:
521/// such a unit means the document was extracted for another target's categories ([`foreign_added_error`]); with
522/// none, the mismatch is a plain skeleton one.
523pub fn first_foreign_added<'u>(units: &'u [crate::Unit], fits: &std::collections::HashSet<&str>) -> Option<&'u crate::Unit> {
524    units.iter().find(|u| u.hidden(ADDED_HIDDEN).is_some_and(|m| !fits.contains(m)))
525}
526
527/// A copy of `other` (a fresh extract's unit) as the added form `category` of a target with the categories `cats`:
528/// id `id` (its segment too), the [`key_added_mark`], and `slot` (marked added).
529pub fn key_added_copy(other: &crate::Unit, id: impl Into<String>, category: &str, cats: &[&str], slot: Option<crate::PluralSlot>) -> crate::Unit {
530    let mut u = other.clone();
531    let id = id.into();
532    let old = std::mem::take(&mut u.id);
533    for s in u.segments.iter_mut().filter(|s| s.id == old) {
534        s.id = id.clone();
535    }
536    u.id = id;
537    u.set_hidden(ADDED_HIDDEN, key_added_mark(category, cats));
538    u.set_plural(slot.map(|s| s.with_added(true)));
539    u
540}
541
542/// Puts every unit added for a key-style plural form (an added plural slot: Android items, stringsdict keys,
543/// i18next and Rails keys, Fluent variants, xcstrings forms) right after the last unit of its own group that is not
544/// added (cat-os#89), so a translator meets the forms of one message together; a unit whose slot names the group as
545/// its parent (a select inside a variant) counts as one of the group's units. The added units keep their order
546/// (extracts make them in CLDR category order), every other unit keeps its place and every id stays as it is.
547/// `parts` (the skeleton's) is pointed at the new places. An added unit whose group has no other unit stays where
548/// it is. A merge must therefore find added units by their mark or id, never by position: documents from 0.10.0
549/// have them at the end. ICU messages ([`levels`]) already come in this order and must not go through here: the
550/// units inside an added branch belong to groups of their own.
551pub fn place_added(units: &mut Vec<crate::Unit>, parts: &mut [crate::SkelPart]) {
552    use std::collections::HashMap;
553    let is_added = |u: &crate::Unit| u.plural().is_some_and(|p| p.is_added());
554    if !units.iter().any(is_added) {
555        return;
556    }
557    // the last unit of each group that is not added (a child group's units count for the parent)
558    let mut last: HashMap<&str, usize> = HashMap::new();
559    for (i, u) in units.iter().enumerate() {
560        let Some(p) = u.plural().filter(|_| !is_added(u)) else { continue };
561        last.insert(p.group(), i);
562        if let Some(parent) = p.parent() {
563            last.insert(parent, i);
564        }
565    }
566    let mut after: HashMap<usize, Vec<usize>> = HashMap::new();
567    let mut moved = vec![false; units.len()];
568    for (i, u) in units.iter().enumerate() {
569        if !is_added(u) {
570            continue;
571        }
572        if let Some(&at) = u.plural().and_then(|p| last.get(p.group())) {
573            after.entry(at).or_default().push(i);
574            moved[i] = true;
575        }
576    }
577    let mut order: Vec<usize> = Vec::with_capacity(units.len());
578    for (i, &m) in moved.iter().enumerate() {
579        if !m {
580            order.push(i);
581        }
582        if let Some(list) = after.get(&i) {
583            order.extend(list.iter().copied());
584        }
585    }
586    if order.iter().enumerate().all(|(k, &i)| k == i) {
587        return;
588    }
589    apply_order(units, parts, &order);
590}
591
592/// Keeps the units `order` names, in that order, and points the skeleton's unit parts at their new places (a part
593/// of a unit left out keeps its number).
594fn apply_order(units: &mut Vec<crate::Unit>, parts: &mut [crate::SkelPart], order: &[usize]) {
595    let mut new_at = vec![usize::MAX; units.len()];
596    for (k, &i) in order.iter().enumerate() {
597        new_at[i] = k;
598    }
599    for p in parts.iter_mut() {
600        if let crate::SkelPart::Unit(i) = p {
601            if let Some(&n) = new_at.get(*i).filter(|n| **n != usize::MAX) {
602                *i = n;
603            }
604        }
605    }
606    let mut old: Vec<Option<crate::Unit>> = std::mem::take(units).into_iter().map(Some).collect();
607    units.extend(order.iter().map(|&i| old[i].take().expect("each unit once")));
608}
609
610/// For tests of format crates: `doc` with its added plural forms ([`place_added`]) moved to the end, the layout
611/// 0.10.0 extracted (`keep`), or left out (`!keep`, a document from before the forms were added), the skeleton
612/// pointed at the new places.
613#[doc(hidden)]
614pub fn reorder_added(doc: &crate::Document, keep: bool) -> crate::Document {
615    let mut d = doc.clone();
616    let added = |u: &crate::Unit| u.plural().is_some_and(|p| p.is_added());
617    let mut order: Vec<usize> = (0..d.units.len()).filter(|&i| !added(&d.units[i])).collect();
618    if keep {
619        order.extend((0..d.units.len()).filter(|&i| added(&d.units[i])));
620    }
621    let mut none: Vec<crate::SkelPart> = Vec::new();
622    let parts = match &mut d.skeleton {
623        crate::Skeleton::Text { parts, .. } => parts,
624        _ => &mut none,
625    };
626    apply_order(&mut d.units, parts, &order);
627    d
628}
629
630/// Plural slots for suffix-style plural keys (ARB `itemCountOne`, `itemCountOther`): the units whose key (`key`
631/// gives it, `None` for a unit that is not a whole top-level message) is a stem and a category word, grouped by
632/// stem, where a stem has `Other` and one more word (the groups the merge's suffix fill reads). Group `{stem}`,
633/// category the word in lower case; a unit that has a slot keeps it.
634pub fn suffix_plural_slots(units: &mut [crate::Unit], key: &dyn Fn(&crate::Unit) -> Option<String>) {
635    const WORDS: [&str; 6] = ["Zero", "One", "Two", "Few", "Many", "Other"];
636    let mut groups: std::collections::HashMap<String, Vec<(usize, &'static str)>> = std::collections::HashMap::new();
637    for (i, u) in units.iter().enumerate() {
638        let Some(k) = key(u) else { continue };
639        if !k.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_') {
640            continue;
641        }
642        if let Some((stem, w)) = WORDS.iter().find_map(|w| k.strip_suffix(w).filter(|s| !s.is_empty()).map(|s| (s.to_string(), *w))) {
643            groups.entry(stem).or_default().push((i, w));
644        }
645    }
646    for (stem, forms) in groups {
647        let mut words: Vec<&str> = forms.iter().map(|f| f.1).collect();
648        words.sort_unstable();
649        words.dedup();
650        if words.len() < 2 || !words.contains(&"Other") {
651            continue;
652        }
653        for (i, w) in forms {
654            if units[i].plural.is_none() {
655                units[i].set_plural(key_slot(stem.as_str(), false, &w.to_ascii_lowercase(), false));
656            }
657        }
658    }
659}
660
661/// The plural slot of a key-style form: group, cardinal or ordinal, category, the `added` mark.
662pub fn key_slot(group: impl Into<Box<str>>, ordinal: bool, category: &str, added: bool) -> crate::PluralSlot {
663    let kind = if ordinal { crate::PluralKind::Ordinal } else { crate::PluralKind::Cardinal };
664    crate::PluralSlot::new(group, kind).with_category(category).with_added(added)
665}
666
667/// A complex argument rebuilt from its rendered branches. Plural and selectordinal follow the target's
668/// categories `cats`: unused ones go, missing ones take the text of `added` for that category (an added unit's
669/// rendering) or else copy the `other` text, `=N` branches stay.
670pub fn render_branches(cx: &Complex, rendered: Vec<String>, added: &[(&str, String)], cats: Option<&[&str]>) -> String {
671    struct B {
672        selector: String,
673        mid: String,
674        text: String,
675        trail: String,
676    }
677    let mut list: Vec<B> = cx
678        .branches
679        .iter()
680        .zip(rendered)
681        .map(|(b, text)| B { selector: b.selector.clone(), mid: b.mid.clone(), text, trail: b.trail.clone() })
682        .collect();
683    let cats = if cx.kind == Kind::Select { None } else { cats };
684    if let Some(cats) = cats {
685        if let Some(o) = list.iter().find(|b| b.selector == "other") {
686            let (other_mid, other_text) = (o.mid.clone(), o.text.clone());
687            let mut kept: Vec<B> = list.into_iter().filter(|b| b.selector.starts_with('=') || cats.contains(&b.selector.as_str())).collect();
688            let missing: Vec<&str> = cats.iter().copied().filter(|c| !kept.iter().any(|b| b.selector == *c)).collect();
689            if !missing.is_empty() {
690                let idx = kept.iter().position(|b| b.selector == "other").unwrap_or(kept.len());
691                let sep = if idx > 0 && !kept[idx - 1].trail.is_empty() { kept[idx - 1].trail.clone() } else { " ".to_string() };
692                let new = missing.iter().map(|c| {
693                    let text = added.iter().find(|(a, _)| a == c).map_or_else(|| other_text.clone(), |(_, t)| t.clone());
694                    B { selector: (*c).to_string(), mid: other_mid.clone(), text, trail: sep.clone() }
695                });
696                let tail = kept.split_off(idx);
697                kept.extend(new);
698                kept.extend(tail);
699            }
700            list = kept;
701        }
702    }
703    let mut out = cx.head.clone();
704    for b in &list {
705        out.push_str(&b.selector);
706        out.push_str(&b.mid);
707        out.push('{');
708        out.push_str(&b.text);
709        out.push('}');
710        out.push_str(&b.trail);
711    }
712    out.push('}');
713    out
714}
715
716/// The model's plural slot of a branch: group names are `{message}#{group}` (`message` is the first unit id of
717/// the message, `u3#0`).
718pub fn plural_slot(message: &str, s: &BranchSlot) -> crate::PluralSlot {
719    let mut p = crate::PluralSlot::new(format!("{message}#{}", s.group), s.kind.plural_kind()).with_category(s.category.as_str()).with_added(s.added);
720    if !s.arg.is_empty() {
721        p = p.with_arg(s.arg.as_str());
722    }
723    if let Some(g) = s.parent {
724        p = p.with_parent(format!("{message}#{g}"));
725    }
726    p
727}
728
729#[cfg(test)]
730mod tests {
731    use super::*;
732
733    fn render(parts: &[Part]) -> String {
734        let mut out = String::new();
735        for p in parts {
736            match p {
737                Part::Text(t) | Part::Simple(t) => out.push_str(t),
738                Part::Pound => out.push('#'),
739                Part::Complex(cx) => {
740                    out.push_str(&cx.head);
741                    for b in &cx.branches {
742                        out.push_str(&format!("{}{}{{{}}}{}", b.selector, b.mid, render(&b.msg), b.trail));
743                    }
744                    out.push('}');
745                }
746            }
747        }
748        out
749    }
750
751    fn none(_: Kind) -> Option<Vec<&'static str>> {
752        None
753    }
754
755    #[test]
756    fn every_byte_is_kept() {
757        for s in [
758            "plain",
759            "Hello {name}!",
760            "{n, plural, =0{none} one{# x} other{# xs}}",
761            "{ count , plural , offset:1 one { # item } other { # items } }",
762            "{g, select, a{A} other{B}} tail",
763            "It''s '{quoted}' text",
764            "{d, date, ::yMMMd} and {n, number, '{'}",
765            "{a, plural, one{{b, select, x{X} other{Y}}} other{Z}}",
766            "{g, select, female{{n, plural, one{# her} other{# hers}}} other{{n, plural, one{# their} other{# theirs}}}}",
767            "'#' {n, plural, one{'#' # '{x}'} other{''#''}}",
768        ] {
769            let parts = parse(s).unwrap_or_else(|_| panic!("{s}"));
770            assert_eq!(render(&parts), s);
771        }
772    }
773
774    #[test]
775    fn nested_select_inside_plural() {
776        let parts = parse("{n, plural, one{{g, select, f{she has #} other{they have #}}} other{# items}}").unwrap();
777        let Part::Complex(cx) = &parts[0] else { panic!() };
778        assert_eq!((cx.kind, cx.arg(), cx.branches.len()), (Kind::Plural, "n".to_string(), 2));
779        let Part::Complex(inner) = &cx.branches[0].msg[0] else { panic!() };
780        assert_eq!(inner.kind, Kind::Select);
781        // `#` is text in a select's branches, even inside a plural (as both crates parsed it)
782        assert_eq!(inner.branches[0].msg, [Part::Text("she has #".into())]);
783        let lv = levels(&parts, &none);
784        let paths: Vec<&str> = lv.iter().map(|l| l.path.as_str()).collect();
785        assert_eq!(paths, ["", "n: plural one", "n: plural one / g: select f", "n: plural one / g: select other", "n: plural other"]);
786        let s = lv[2].slot.as_ref().unwrap();
787        assert_eq!((s.group, s.parent, s.kind, s.arg.as_str(), s.category.as_str(), s.added), (1, Some(0), Kind::Select, "g", "f", false));
788        assert_eq!(lv[4].slot.as_ref().unwrap().group, 0);
789        assert!(lv[0].slot.is_none());
790    }
791
792    #[test]
793    fn pound_exact_offsets_and_quotes() {
794        // `#` is a token in a plural branch, text outside one and in a select branch
795        assert_eq!(parse("# {g, select, a{#} other{#}}").unwrap().len(), 2);
796        let parts = parse("{n, plural, one{#} other{##}}").unwrap();
797        let Part::Complex(cx) = &parts[0] else { panic!() };
798        assert_eq!(cx.branches[1].msg, [Part::Pound, Part::Pound]);
799        // exact selectors, negative and decimal ones too
800        let parts = parse("{n, plural, =0{none} =-1{minus} =1.5{half} other{#}}").unwrap();
801        let Part::Complex(cx) = &parts[0] else { panic!() };
802        let sel: Vec<&str> = cx.branches.iter().map(|b| b.selector.as_str()).collect();
803        assert_eq!(sel, ["=0", "=-1", "=1.5", "other"]);
804        // an offset belongs to the head, a select has none
805        let parts = parse("{ n , plural , offset : 2 one{x} other{y}}").unwrap();
806        let Part::Complex(cx) = &parts[0] else { panic!() };
807        assert_eq!(cx.head, "{ n , plural , offset : 2 ");
808        assert_eq!(cx.arg(), "n");
809        assert!(parse("{g, select, offset:1 other{x}}").is_err());
810        // quotes: '' is an apostrophe, '{...}' is literal, a lone ' is text
811        assert_eq!(parse("It''s '{x}' ok").unwrap(), [Part::Text("It''s '{x}' ok".into())]);
812        assert_eq!(parse("don't {x}").unwrap(), [Part::Text("don't ".into()), Part::Simple("{x}".into())]);
813        let parts = parse("{n, plural, other{'#' is #}}").unwrap();
814        let Part::Complex(cx) = &parts[0] else { panic!() };
815        assert_eq!(cx.branches[0].msg, [Part::Text("'#' is ".into()), Part::Pound]);
816        // typed arguments are simple, their styles opaque
817        assert!(matches!(parse("{n, number, ::compact-short}").unwrap()[0], Part::Simple(_)));
818        assert!(matches!(parse("{n, plural}").unwrap()[0], Part::Simple(_)));
819    }
820
821    #[test]
822    fn rejects_what_localization_os_rejects() {
823        let deep = format!("{}x{}", "{a, select, other{".repeat(60), "}".repeat(60));
824        for bad in ["{", "}", "{n, plural, one{x}", "{n, plural}x{", "{n, plural, }", "{n, plural, one x}", "{, plural, other{x}}", "'{open", "{n, number, {x}", deep.as_str()] {
825            assert!(parse(bad).is_err(), "{bad}");
826        }
827    }
828
829    #[test]
830    fn the_locos_flag_counts_literal_tokens_as_no_words() {
831        assert!(has_words("\u{27E6}x1\u{27E7}", false));
832        assert!(!has_words("\u{27E6}x1\u{27E7}", true));
833        assert!(has_words("\u{27E6}x1\u{27E7} files", true));
834        assert!(has_words("\u{27E6}xa\u{27E7}", true));
835        assert!(!translatable(&[Part::Pound, Part::Text(" ".into())], false));
836    }
837
838    #[test]
839    fn missing_categories_become_added_copies_of_other() {
840        let parts = parse("{n, plural, =0{none} one{# file} other{# files}} {g, select, a{A} other{B}}").unwrap();
841        let pl = |k: Kind| (k == Kind::Plural).then(|| vec!["one", "few", "many", "other"]);
842        let lv = levels(&parts, &pl);
843        let got: Vec<(&str, bool)> = lv.iter().map(|l| (l.path.as_str(), l.slot.as_ref().is_some_and(|s| s.added))).collect();
844        assert_eq!(
845            got,
846            [
847                ("", false),
848                ("n: plural =0", false),
849                ("n: plural one", false),
850                ("n: plural other", false),
851                ("n: plural few", true),
852                ("n: plural many", true),
853                ("g: select a", false),
854                ("g: select other", false),
855            ]
856        );
857        // an added copy holds the `other` branch's parts
858        assert_eq!(lv[4].parts, lv[3].parts);
859        // without `other` nothing is added; a select never is
860        let parts = parse("{n, plural, one{x}}").unwrap();
861        assert_eq!(levels(&parts, &pl).len(), 2);
862    }
863
864    #[test]
865    fn render_fills_missing_categories_from_other_or_the_added_text() {
866        let parts = parse("{n, plural, one{# file} other{# files}}").unwrap();
867        let Part::Complex(cx) = &parts[0] else { panic!() };
868        let r = || vec!["# plik".to_string(), "# plików".to_string()];
869        let cats = ["one", "few", "many", "other"];
870        assert_eq!(render_branches(cx, r(), &[], Some(&cats)), "{n, plural, one{# plik} few{# plików} many{# plików} other{# plików}}");
871        assert_eq!(render_branches(cx, r(), &[("few", "# pliki".into())], Some(&cats)), "{n, plural, one{# plik} few{# pliki} many{# plików} other{# plików}}");
872        assert_eq!(render_branches(cx, r(), &[("few", "x".into())], None), "{n, plural, one{# plik} other{# plików}}");
873    }
874
875    #[test]
876    fn key_style_added_forms_fit_only_the_same_categories() {
877        let other = crate::Unit::new("u3", vec![crate::Inline::text("# files")]);
878        let slot = key_slot("files", false, "other", false);
879        let u = key_added_copy(&other, "u3.few", "few", &["one", "few", "many", "other"], Some(slot.clone().with_category("few")));
880        assert_eq!((u.id.as_str(), u.segments[0].id.as_str()), ("u3.few", "u3.few"));
881        assert_eq!(u.hidden(ADDED_HIDDEN), Some("few of one few many other"));
882        assert!(u.plural().is_some_and(|p| p.is_added() && p.category() == Some("few") && p.group() == "files"));
883        assert_eq!(key_added(&u, Some(&["one", "few", "many", "other"])), KeyAdded::Fits("few"));
884        // Slovenian has `few` too, among other categories: not the same forms
885        assert_eq!(key_added(&u, Some(&["one", "two", "few", "other"])), KeyAdded::Foreign);
886        assert_eq!(key_added(&u, None), KeyAdded::Foreign);
887        assert_eq!(key_added(&other, Some(&["one", "other"])), KeyAdded::No);
888        // an ICU added path is not a key-style mark
889        let mut icu = other.clone();
890        icu.set_hidden(ADDED_HIDDEN, "count: plural few");
891        assert_eq!(key_added(&icu, Some(&["one", "few", "many", "other"])), KeyAdded::No);
892        assert!(!has_any_target(&u));
893    }
894
895    #[test]
896    fn added_forms_move_after_their_group_and_the_skeleton_follows() {
897        let unit = |id: &str, group: Option<&str>, added: bool| {
898            let mut u = crate::Unit::new(id, vec![crate::Inline::text(id)]);
899            if let Some(g) = group {
900                u.set_plural(key_slot(g, false, "other", added));
901            }
902            u
903        };
904        // the 0.10.0 layout: added units at the end
905        let mut units = vec![unit("a", Some("g1"), false), unit("b", Some("g1"), false), unit("c", None, false), unit("d", Some("g2"), false), unit("b.few", Some("g1"), true), unit("b.many", Some("g1"), true), unit("d.few", Some("g2"), true), unit("x.few", Some("gone"), true)];
906        let mut parts: Vec<crate::SkelPart> = (0..4).map(crate::SkelPart::Unit).collect();
907        place_added(&mut units, &mut parts);
908        let ids: Vec<&str> = units.iter().map(|u| u.id.as_str()).collect();
909        assert_eq!(ids, ["a", "b", "b.few", "b.many", "c", "d", "d.few", "x.few"]);
910        let at: Vec<usize> = parts.iter().map(|p| if let crate::SkelPart::Unit(i) = p { *i } else { usize::MAX }).collect();
911        assert_eq!(at, [0, 1, 4, 5]);
912        // and back: the test helper puts them at the end again, or leaves them out
913        let doc = crate::Document::new("x", units, crate::Skeleton::text(parts, "utf-8", crate::ParserInfo::new("x", "0", 1)));
914        let back = reorder_added(&doc, true);
915        assert_eq!(back.units.iter().map(|u| u.id.as_str()).collect::<Vec<_>>(), ["a", "b", "c", "d", "b.few", "b.many", "d.few", "x.few"]);
916        let none = reorder_added(&doc, false);
917        assert_eq!(none.units.len(), 4);
918        let crate::Skeleton::Text { parts, .. } = &none.skeleton else { panic!() };
919        assert!(parts.iter().enumerate().all(|(k, p)| matches!(p, crate::SkelPart::Unit(i) if *i == k)));
920    }
921
922    #[test]
923    fn suffix_keys_group_by_stem() {
924        let mut units: Vec<crate::Unit> = ["itemCountOne", "itemCountOther", "phone", "lonelyOther", "aOne", "aMany"].iter().map(|k| {
925            let mut u = crate::Unit::new(*k, vec![]);
926            u.context.key = Some((*k).to_string());
927            u
928        }).collect();
929        suffix_plural_slots(&mut units, &|u| u.context.key.clone());
930        let got: Vec<Option<(&str, &str)>> = units.iter().map(|u| u.plural().map(|p| (p.group(), p.category().unwrap()))).collect();
931        assert_eq!(got, [Some(("itemCount", "one")), Some(("itemCount", "other")), None, None, None, None]);
932    }
933
934    #[test]
935    fn slots_name_groups_by_message() {
936        let s = BranchSlot { group: 1, parent: Some(0), kind: Kind::Select, arg: "g".into(), category: "f".into(), added: false };
937        let p = plural_slot("u3", &s);
938        assert_eq!((p.group(), p.parent(), p.category(), p.arg(), p.kind(), p.is_added()), ("u3#1", Some("u3#0"), Some("f"), Some("g"), crate::PluralKind::Select, false));
939    }
940}