Skip to main content

i18n_next/
check.rs

1//! `I18n::check()` (DESIGN 8b.8, M3): what a translator forgot, found without running the app.
2//!
3//! - a page that has a file in some locales but not in others;
4//! - a key of the default locale missing in another locale, page by page (root and pages);
5//! - `{placeholders}` of one key that differ from the default locale's;
6//! - a plural message whose form count does not fit the locale's CLDR categories, or whose
7//!   shape makes `tc` fall back to the index rule;
8//! - links that left a linked message as written (with `linked_messages(true)`).
9//!
10//! Disabled locales are skipped. Texts `linked.rs` stored for a view are not the locale's own
11//! keys and are never counted.
12
13use crate::catalog::{Chunk, Entry, Msg, hole_ranges};
14use crate::linked::Broken;
15use crate::plural::Plural;
16use std::collections::{BTreeMap, BTreeSet};
17use std::fmt;
18use std::sync::Arc;
19
20/// Why a link left its message as written.
21#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
22#[non_exhaustive]
23pub enum LinkError {
24    /// The key names no message (missing, a subtree or a boolean).
25    Missing,
26    /// The link leads back to a message being resolved.
27    Cycle,
28    /// The target is itself left as written.
29    Broken,
30    /// Not `upper`, `lower` or `capitalize`.
31    UnknownModifier,
32    /// Nothing at `build`, when lazy and remote files are not read yet: the key may be in
33    /// one of the view's lazy files. An eager message is resolved at `build` only.
34    Lazy,
35}
36
37impl fmt::Display for LinkError {
38    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
39        f.write_str(match self {
40            LinkError::Missing => "names no message",
41            LinkError::Cycle => "is a cycle",
42            LinkError::Broken => "links a message left as written",
43            LinkError::UnknownModifier => "has an unknown modifier",
44            LinkError::Lazy => "names no message read at build (its view has lazy files)",
45        })
46    }
47}
48
49/// One finding of [`I18n::check`](crate::I18n::check). `page` is `"index"` for the root.
50#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
51#[non_exhaustive]
52pub enum CheckItem {
53    /// `locale` has no file for `page`, other locales do.
54    MissingPage { locale: String, page: String },
55    /// `key` of the default locale is missing in `locale`.
56    MissingKey {
57        locale: String,
58        page: String,
59        key: String,
60    },
61    /// The placeholders of `key` in `locale` are not those of the default locale.
62    Placeholders {
63        locale: String,
64        page: String,
65        key: String,
66        /// In the default locale, sorted.
67        expected: Vec<String>,
68        /// In `locale`, sorted.
69        found: Vec<String>,
70    },
71    /// A plural message with a form count the locale does not read by category.
72    PluralForms {
73        locale: String,
74        page: String,
75        key: String,
76        forms: usize,
77        /// Counts that fit: a zero form plus one per category small counts reach; a `=0 `
78        /// message also one per category of the locale.
79        expected: Vec<usize>,
80        /// The categories small counts reach (`one`, `few`, `many`).
81        categories: Vec<String>,
82    },
83    /// The form count fits, but the zero form has a `{` or a form shared by several counts
84    /// lacks `{count}`: `tc` reads it by index.
85    PluralShape {
86        locale: String,
87        page: String,
88        key: String,
89        categories: Vec<String>,
90    },
91    /// A link left the linked message `key` as written.
92    BrokenLink {
93        locale: String,
94        page: String,
95        key: String,
96        /// As written (`@.upper:brand`).
97        link: String,
98        reason: LinkError,
99    },
100}
101
102impl fmt::Display for CheckItem {
103    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
104        match self {
105            CheckItem::MissingPage { locale, page } => {
106                write!(
107                    f,
108                    "{locale}: no file for page \"{page}\" (other locales have one)"
109                )
110            }
111            CheckItem::MissingKey { locale, page, key } => {
112                write!(
113                    f,
114                    "{locale}/{page}: \"{key}\" is missing (the default locale has it)"
115                )
116            }
117            CheckItem::Placeholders {
118                locale,
119                page,
120                key,
121                expected,
122                found,
123            } => write!(
124                f,
125                "{locale}/{page}: \"{key}\" has {{{}}}, the default locale {{{}}}",
126                found.join(", "),
127                expected.join(", ")
128            ),
129            CheckItem::PluralForms {
130                locale,
131                page,
132                key,
133                forms,
134                expected,
135                categories,
136            } => {
137                let expected: Vec<String> = expected.iter().map(usize::to_string).collect();
138                write!(
139                    f,
140                    "{locale}/{page}: \"{key}\" has {forms} plural forms, expected {} (zero | {})",
141                    expected.join(" or "),
142                    categories.join(" | ")
143                )
144            }
145            CheckItem::PluralShape {
146                locale,
147                page,
148                key,
149                categories,
150            } => write!(
151                f,
152                "{locale}/{page}: \"{key}\" is read by index, not by category (zero | {}): \
153                 the zero form has a `{{` or a form of several counts lacks {{count}}",
154                categories.join(" | ")
155            ),
156            CheckItem::BrokenLink {
157                locale,
158                page,
159                key,
160                link,
161                reason,
162            } => write!(
163                f,
164                "{locale}/{page}: \"{key}\" left as written: {link} {reason}"
165            ),
166        }
167    }
168}
169
170/// What [`I18n::check`](crate::I18n::check) found, sorted. Display lists it line by line.
171///
172/// ```
173/// use i18n_next::{CheckItem, I18n};
174///
175/// let i18n = I18n::builder()
176///     .locale("en")
177///     .messages("en", None, r#"{"hi": "Hi {name}", "bye": "Bye"}"#)
178///     .messages("de", None, r#"{"hi": "Hallo {nam}"}"#)
179///     .build()?;
180/// let report = i18n.check();
181/// assert!(!report.is_clean());
182/// assert!(report.items.contains(&CheckItem::MissingKey {
183///     locale: "de".into(),
184///     page: "index".into(),
185///     key: "bye".into(),
186/// }));
187/// println!("{report}");
188/// # Ok::<(), i18n_next::Error>(())
189/// ```
190#[derive(Debug, Clone, Default, PartialEq, Eq)]
191#[non_exhaustive]
192pub struct CheckReport {
193    /// Every finding, sorted (by kind, then locale, page, key).
194    pub items: Vec<CheckItem>,
195}
196
197impl CheckReport {
198    /// No findings.
199    #[must_use]
200    pub fn is_clean(&self) -> bool {
201        self.items.is_empty()
202    }
203}
204
205impl fmt::Display for CheckReport {
206    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
207        if self.items.is_empty() {
208            return f.write_str("catalog check: clean");
209        }
210        write!(f, "catalog check: {} problem(s)", self.items.len())?;
211        for item in &self.items {
212            write!(f, "\n  - {item}")?;
213        }
214        Ok(())
215    }
216}
217
218/// What `build` leaves for `check` (`i18n.rs` `Meta`).
219#[derive(Debug, Default)]
220pub(crate) struct Facts {
221    /// The default locale: keys and placeholders are compared with it.
222    pub(crate) reference: Option<Arc<str>>,
223    /// Links left as written at the last `build` / `reload` (`linked_messages(true)`).
224    pub(crate) broken: std::sync::Mutex<Vec<Broken>>,
225}
226
227/// Locks `m`, poisoned or not (the data is replaced whole).
228pub(crate) fn lock<T>(m: &std::sync::Mutex<T>) -> std::sync::MutexGuard<'_, T> {
229    m.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
230}
231
232fn page_name(page: Option<&Arc<str>>) -> String {
233    page.map_or_else(|| "index".to_owned(), |p| String::from(&**p))
234}
235
236/// The placeholder names of a message; without `count` when `plural` (`tc` fills it, and a
237/// form may show the count in one language and not in another).
238fn holes(e: &Entry, plural: bool) -> Option<BTreeSet<&str>> {
239    let raw = match e {
240        Entry::Msg(_) => e.text()?,
241        _ => return None,
242    };
243    Some(
244        hole_ranges(raw)
245            .filter_map(|(s, e)| raw.get(s..e))
246            .filter(|name| !(plural && *name == "count"))
247            .collect(),
248    )
249}
250
251fn sorted(set: &BTreeSet<&str>) -> Vec<String> {
252    set.iter().map(|s| (*s).to_owned()).collect()
253}
254
255/// The report over `chunks` (`(locale, page, chunk)`, disabled locales left out).
256pub(crate) fn run<'a>(
257    chunks: impl Iterator<Item = (&'a Arc<str>, Option<&'a Arc<str>>, &'a Chunk)>,
258    facts: &Facts,
259    plural: impl Fn(&str) -> Option<&'static Plural>,
260) -> CheckReport {
261    let chunks: BTreeMap<(&Arc<str>, Option<&Arc<str>>), &Chunk> = chunks
262        .filter(|(_, _, c)| !c.only_linked())
263        .map(|(l, p, c)| ((l, p), c))
264        .collect();
265    let locales: BTreeSet<&Arc<str>> = chunks.keys().map(|(l, _)| *l).collect();
266    let pages: BTreeSet<Option<&Arc<str>>> = chunks.keys().map(|(_, p)| *p).collect();
267    let mut items = Vec::new();
268
269    for page in &pages {
270        for locale in &locales {
271            if !chunks.contains_key(&(*locale, *page)) {
272                items.push(CheckItem::MissingPage {
273                    locale: String::from(&***locale),
274                    page: page_name(*page),
275                });
276            }
277        }
278    }
279
280    if let Some(reference) = facts.reference.as_ref() {
281        for ((_, page), base) in chunks.iter().filter(|((l, _), _)| *l == reference) {
282            for locale in locales.iter().filter(|l| **l != reference) {
283                let Some(other) = chunks.get(&(*locale, *page)) else {
284                    continue;
285                };
286                for (key, e) in base.leaves() {
287                    let mine = match other.get(key) {
288                        Some(m) if other.has(key) => m,
289                        _ => {
290                            items.push(CheckItem::MissingKey {
291                                locale: String::from(&***locale),
292                                page: page_name(*page),
293                                key: key.to_owned(),
294                            });
295                            continue;
296                        }
297                    };
298                    let plural = [e, mine]
299                        .iter()
300                        .any(|x| matches!(x, Entry::Msg(Msg::Plural(_))));
301                    if let (Some(want), Some(got)) = (holes(e, plural), holes(mine, plural))
302                        && want != got
303                    {
304                        items.push(CheckItem::Placeholders {
305                            locale: String::from(&***locale),
306                            page: page_name(*page),
307                            key: key.to_owned(),
308                            expected: sorted(&want),
309                            found: sorted(&got),
310                        });
311                    }
312                }
313            }
314        }
315    }
316
317    for ((locale, page), chunk) in &chunks {
318        let rules = plural(locale);
319        for (key, e) in chunk.leaves() {
320            let Entry::Msg(Msg::Plural(p)) = e else {
321                continue;
322            };
323            let (forms, marked, shape) = p.layout();
324            let Some((expected, shape_only)) = shape.check(marked, rules) else {
325                continue;
326            };
327            let categories = rules
328                .map(|r| r.named_names().into_iter().map(str::to_owned).collect())
329                .unwrap_or_default();
330            let (locale, page, key) = (String::from(&***locale), page_name(*page), key.to_owned());
331            items.push(if shape_only {
332                CheckItem::PluralShape {
333                    locale,
334                    page,
335                    key,
336                    categories,
337                }
338            } else {
339                CheckItem::PluralForms {
340                    locale,
341                    page,
342                    key,
343                    forms,
344                    expected,
345                    categories,
346                }
347            });
348        }
349    }
350
351    for b in lock(&facts.broken).iter() {
352        if locales.contains(&b.locale) {
353            items.push(CheckItem::BrokenLink {
354                locale: String::from(&*b.locale),
355                page: page_name(b.page.as_ref()),
356                key: String::from(&*b.key),
357                link: String::from(&*b.link),
358                reason: b.reason,
359            });
360        }
361    }
362
363    items.sort();
364    items.dedup();
365    CheckReport { items }
366}