1const MAX_DEPTH: usize = 40;
12
13#[derive(Debug, Clone, PartialEq, Eq)]
15pub enum Part {
16 Text(String),
18 Simple(String),
20 Pound,
22 Complex(Complex),
24}
25
26#[derive(Debug, Clone, Copy, PartialEq, Eq)]
28pub enum Kind {
29 Plural,
31 SelectOrdinal,
33 Select,
35}
36
37impl Kind {
38 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 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#[derive(Debug, Clone, PartialEq, Eq)]
59pub struct Complex {
60 pub head: String,
62 pub kind: Kind,
64 pub branches: Vec<Branch>,
66}
67
68impl Complex {
69 pub fn arg(&self) -> String {
71 arg_name(&self.head)
72 }
73
74 pub fn other(&self) -> Option<&Branch> {
76 self.branches.iter().find(|b| b.selector == "other")
77 }
78}
79
80#[derive(Debug, Clone, PartialEq, Eq)]
82pub struct Branch {
83 pub selector: String,
85 pub mid: String,
87 pub msg: Vec<Part>,
89 pub trail: String,
91}
92
93#[derive(Debug)]
95pub struct IcuError;
96
97type R<T> = Result<T, IcuError>;
98
99fn 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
118pub fn parse(s: &str) -> R<Vec<Part>> {
120 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 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 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
289fn 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
307fn 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
339pub 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
349pub 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
374pub 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#[derive(Debug, Clone, PartialEq, Eq)]
387pub struct BranchSlot {
388 pub group: usize,
390 pub parent: Option<usize>,
392 pub kind: Kind,
394 pub arg: String,
396 pub category: String,
398 pub added: bool,
400}
401
402#[derive(Debug, Clone)]
405pub struct Level<'a> {
406 pub parts: &'a [Part],
408 pub path: String,
410 pub slot: Option<BranchSlot>,
412}
413
414pub 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
424pub 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
465pub const ADDED_HIDDEN: &str = "icu_added";
469
470pub fn added_matches(unit: &crate::Unit, added_path: Option<&str>) -> bool {
473 unit.hidden(ADDED_HIDDEN) == added_path
474}
475
476pub fn key_added_mark(category: &str, cats: &[&str]) -> String {
485 format!("{category} of {}", cats.join(" "))
486}
487
488#[derive(Debug, Clone, Copy, PartialEq, Eq)]
490pub enum KeyAdded<'u> {
491 No,
493 Fits(&'u str),
495 Foreign,
497}
498
499pub 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
508pub fn has_any_target(unit: &crate::Unit) -> bool {
510 unit.segments.iter().any(|s| s.has_target())
511}
512
513pub fn foreign_added_error(unit: &crate::Unit) -> crate::Error {
516 crate::Error::TargetChanged { unit: unit.id.clone() }
517}
518
519pub 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
527pub 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
542pub 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 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
592fn 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#[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
630pub 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
661pub 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
667pub 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
716pub 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 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 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 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 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 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 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 assert_eq!(lv[4].parts, lv[3].parts);
859 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 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 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 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 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}