Skip to main content

egui_pop_i18n/
extract.rs

1//! The extractor: which keys an application uses, with their English;
2//! the English catalogue written from them; and, per locale, the keys
3//! missing or unused.
4//!
5//! Keys come from two places:
6//!
7//! - **sources** ([`scan`], [`scan_tree`]): calls written in Rust
8//!   with a literal key, `tr!("key")`, `t(ctx, "key", …)`,
9//!   `text(ctx, "key", "English", …)`, `StrKey::new("key", "English")`,
10//!   `lookup(ctx, "key", "English")` (see [`Pattern::DEFAULTS`]; an
11//!   application adds its own), under any path (`app::Message::new`);
12//!   a constructor call it cannot read is reported ([`Scan::unread`]);
13//! - **declarations** ([`declarations`]): what the plugins of a built
14//!   application declare (commands, categories, panels, submenus,
15//!   settings and their choices, plugins), under the keys
16//!   `egui_pop_core::strings` derives from their ids.
17//!
18//! [`english`] writes the English catalogue from them, sorted, so the
19//! same keys always give the same bytes; [`update`] merges them into an
20//! existing one, keeping the English written there for keys the code
21//! gives none; [`out_of_date`] checks a catalogue against them, listing
22//! the calls not read; [`report`] compares every locale with them.
23//!
24//! ```
25//! use egui_pop_i18n::extract::{self, Pattern};
26//!
27//! let src = r#"
28//!     ui.label(tr!("welcome"));
29//!     const SAVE: StrKey = StrKey::new("app-save", "Save { $name }");
30//! "#;
31//! let found = extract::scan_source(src, "src/lib.rs", Pattern::DEFAULTS);
32//! let messages = extract::messages(&found).unwrap();
33//! let ftl = extract::english(&messages, "");
34//! assert!(ftl.contains("app-save = Save { $name }\n"));
35//! assert!(ftl.contains("welcome = welcome\n"), "{ftl}");
36//! ```
37
38use std::collections::{BTreeMap, BTreeSet};
39use std::fmt::Write as _;
40use std::io;
41use std::path::Path;
42
43use egui_pop_api::AppHandle;
44use egui_pop_api::app::MENU_MAIN;
45use egui_pop_core::strings::{self, kind};
46use egui_pop_model::ids::MenuId;
47use egui_pop_model::menus::Item;
48use fluent_syntax::ast::{Entry, Identifier, Message, Pattern as FtlPattern, Resource};
49use serde::{Deserialize, Serialize};
50
51/// A key's English, as found.
52#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
53#[serde(tag = "kind", content = "text", rename_all = "snake_case")]
54pub enum English {
55    /// Text to show as is (a declaration's title): braces are escaped
56    /// when written to Fluent.
57    Plain(String),
58    /// A Fluent pattern (`Save { $name }`), written as is.
59    Pattern(String),
60    /// The code gives none (`tr!("key")`): the catalogue's English is
61    /// kept, or the key is written as a placeholder.
62    None,
63}
64
65/// A key found, with its English and where.
66#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
67pub struct Found {
68    pub key: String,
69    pub english: English,
70    /// `file:line`, or what declares it (`command app.quit`).
71    pub origin: String,
72}
73
74/// A call whose arguments hold a key, and maybe its English.
75#[derive(Clone, Copy, Debug, PartialEq, Eq)]
76pub struct Pattern {
77    /// What is called, as written before `(` (`tr!`, `t`,
78    /// `StrKey::new`). A name without a path also matches with one
79    /// (`t` matches `egui_pop_i18n::t`).
80    pub callee: &'static str,
81    /// Which argument is the key (from 0).
82    pub key: usize,
83    /// Which argument is the English, if any.
84    pub english: Option<usize>,
85}
86
87impl Pattern {
88    /// `tr!("key", …)`, `t(ctx, "key", …)`, `text(ctx, "key",
89    /// "English", …)`, `StrKey::new("key", "English")`, `lookup(ctx,
90    /// "key", "English")` and `lookup_args(ctx, "key", "English", …)`.
91    pub const DEFAULTS: &'static [Pattern] = &[
92        Pattern {
93            callee: "tr!",
94            key: 0,
95            english: None,
96        },
97        Pattern {
98            callee: "t",
99            key: 1,
100            english: None,
101        },
102        Pattern {
103            callee: "text",
104            key: 1,
105            english: Some(2),
106        },
107        Pattern {
108            callee: "StrKey::new",
109            key: 0,
110            english: Some(1),
111        },
112        Pattern {
113            callee: "lookup",
114            key: 1,
115            english: Some(2),
116        },
117        Pattern {
118            callee: "lookup_args",
119            key: 1,
120            english: Some(2),
121        },
122    ];
123}
124
125/// A key as Fluent allows it: an identifier, optionally `.attribute`.
126pub fn valid_key(key: &str) -> bool {
127    let ident = |s: &str| {
128        let mut c = s.chars();
129        c.next().is_some_and(|f| f.is_ascii_alphabetic())
130            && c.all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_')
131    };
132    match key.split_once('.') {
133        Some((id, attr)) => ident(id) && ident(attr),
134        None => ident(key),
135    }
136}
137
138/// Source with comments and the contents of string literals other than
139/// the ones we read blanked, so calls are found by their text.
140fn tokens(source: &str) -> Vec<Tok> {
141    let b = source.as_bytes();
142    let mut out = Vec::new();
143    let mut i = 0;
144    let mut line = 1;
145    while i < b.len() {
146        let c = b[i];
147        if c == b'\n' {
148            line += 1;
149            i += 1;
150        } else if b[i..].starts_with(b"//") {
151            while i < b.len() && b[i] != b'\n' {
152                i += 1;
153            }
154        } else if b[i..].starts_with(b"/*") {
155            i += 2;
156            while i < b.len() && !b[i..].starts_with(b"*/") {
157                if b[i] == b'\n' {
158                    line += 1;
159                }
160                i += 1;
161            }
162            i += 2;
163        } else if c == b'"' || (c == b'r' && matches!(b.get(i + 1), Some(b'"' | b'#'))) {
164            let start_line = line;
165            let (text, end) = string_literal(source, i);
166            line += source[i..end].matches('\n').count();
167            out.push(Tok::Str(text, start_line));
168            i = end;
169        } else if c == b'\'' {
170            // A char literal or a lifetime: skip `'x'` and `'\n'`.
171            if b.get(i + 2) == Some(&b'\'') {
172                i += 3;
173            } else if b.get(i + 1) == Some(&b'\\') {
174                i += 2;
175                while i < b.len() && b[i] != b'\'' {
176                    i += 1;
177                }
178                i += 1;
179            } else {
180                i += 1;
181            }
182        } else if c.is_ascii_alphabetic() || c == b'_' {
183            let start = i;
184            while i < b.len() && (b[i].is_ascii_alphanumeric() || b[i] == b'_') {
185                i += 1;
186            }
187            out.push(Tok::Ident(source[start..i].to_string(), line));
188        } else if c.is_ascii_whitespace() {
189            i += 1;
190        } else {
191            out.push(Tok::Punct(c as char));
192            i += 1;
193        }
194    }
195    out
196}
197
198#[derive(Clone, Debug, PartialEq)]
199enum Tok {
200    Ident(String, usize),
201    Str(String, usize),
202    Punct(char),
203}
204
205/// A string literal at `i` (plain or raw), unescaped, and where it ends.
206fn string_literal(source: &str, i: usize) -> (String, usize) {
207    let b = source.as_bytes();
208    if b[i] == b'r' {
209        let mut j = i + 1;
210        let mut hashes = 0;
211        while b.get(j) == Some(&b'#') {
212            hashes += 1;
213            j += 1;
214        }
215        let start = j + 1;
216        let close = format!("\"{}", "#".repeat(hashes));
217        let end = source[start..]
218            .find(&close)
219            .map_or(source.len(), |p| start + p);
220        return (
221            source[start..end].to_string(),
222            (end + close.len()).min(source.len()),
223        );
224    }
225    let mut out = String::new();
226    let mut j = i + 1;
227    let chars: Vec<(usize, char)> = source[j..].char_indices().collect();
228    let mut k = 0;
229    while k < chars.len() {
230        let (off, c) = chars[k];
231        match c {
232            '"' => return (out, j + off + 1),
233            '\\' => {
234                k += 1;
235                let Some(&(_, e)) = chars.get(k) else { break };
236                match e {
237                    'n' => out.push('\n'),
238                    't' => out.push('\t'),
239                    '\\' => out.push('\\'),
240                    '"' => out.push('"'),
241                    '\'' => out.push('\''),
242                    '0' => out.push('\0'),
243                    '\n' => {
244                        // A line continuation: the next line's indent goes.
245                        while chars.get(k + 1).is_some_and(|(_, c)| c.is_whitespace()) {
246                            k += 1;
247                        }
248                    }
249                    'u' => {
250                        let hex: String = chars[k + 1..]
251                            .iter()
252                            .map(|(_, c)| *c)
253                            .skip(1)
254                            .take_while(|c| *c != '}')
255                            .collect();
256                        if let Some(c) = u32::from_str_radix(&hex, 16).ok().and_then(char::from_u32)
257                        {
258                            out.push(c);
259                        }
260                        k += hex.len() + 2;
261                    }
262                    other => out.push(other),
263                }
264            }
265            c => out.push(c),
266        }
267        k += 1;
268    }
269    j = source.len();
270    (out, j)
271}
272
273/// A call the scanner took for a message constructor but could not
274/// read: the message it declares is missing from what was found, or
275/// found without its English.
276#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
277pub struct Unread {
278    /// The callee as written, path included (`app::Message::new`).
279    pub callee: String,
280    /// `file:line` of the call.
281    pub origin: String,
282    /// Why it was not read (`the key is not a string literal`).
283    pub reason: String,
284}
285
286impl std::fmt::Display for Unread {
287    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
288        write!(
289            f,
290            "{}: `{}(…)` not read: {}",
291            self.origin, self.callee, self.reason
292        )
293    }
294}
295
296/// What a scan gives: the keys found, and the constructor calls that
297/// could not be read.
298#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
299pub struct Scan {
300    pub found: Vec<Found>,
301    pub unread: Vec<Unread>,
302}
303
304impl Scan {
305    /// Adds another scan's results after this one's.
306    pub fn extend(&mut self, other: Scan) {
307        self.found.extend(other.found);
308        self.unread.extend(other.unread);
309    }
310}
311
312/// Whether `callee` (as written) is the call `pattern` names: the same
313/// path, or a longer one ending in it (`a::b::Message::new` and
314/// `crate::Message::new` are `Message::new`; `egui_pop_i18n::t` is `t`).
315fn names(callee: &str, pattern: &str) -> bool {
316    callee == pattern
317        || callee
318            .strip_suffix(pattern)
319            .is_some_and(|head| head.ends_with("::"))
320}
321
322/// A constructor: a pattern whose callee ends in `::new`
323/// (`StrKey::new`, an application's `Message::new`). It declares a
324/// message, so its key and English must be literals the scanner reads.
325fn constructor(pattern: &Pattern) -> bool {
326    pattern.callee.ends_with("::new")
327}
328
329/// The keys a Rust source uses through `patterns`, with their English,
330/// and the constructor calls it could not read.
331///
332/// A callee is matched by its path's last segments, however long the
333/// path and however it is laid out (`helios::Message::new(`,
334/// `::app::strings::Message::new(`, a path or arguments split across
335/// lines, comments between). A call whose key is not a literal, or not
336/// a valid Fluent key, is skipped; when the pattern is a constructor
337/// (its callee ends in `::new`, as `StrKey::new`), the call is also
338/// reported in [`Scan::unread`] with its file and line, and logged as a
339/// warning; so is a constructor whose English is not a literal (its key
340/// is still found, without English).
341pub fn scan(source: &str, file: &str, patterns: &[Pattern]) -> Scan {
342    let toks = tokens(source);
343    let mut out = Scan::default();
344    for (i, t) in toks.iter().enumerate() {
345        let Tok::Ident(name, line) = t else { continue };
346        // The callee as written: a path `a::b`, then `!` for a macro.
347        let mut callee = name.clone();
348        let mut j = i + 1;
349        while matches!(toks.get(j), Some(Tok::Punct(':')))
350            && matches!(toks.get(j + 1), Some(Tok::Punct(':')))
351        {
352            match toks.get(j + 2) {
353                Some(Tok::Ident(n, _)) => {
354                    callee.push_str("::");
355                    callee.push_str(n);
356                    j += 3;
357                }
358                _ => break,
359            }
360        }
361        if matches!(toks.get(j), Some(Tok::Punct('!'))) {
362            callee.push('!');
363            j += 1;
364        }
365        if !matches!(toks.get(j), Some(Tok::Punct('('))) {
366            continue;
367        }
368        // Not a method or a definition: `x.t(`, `fn t(`.
369        if i > 0
370            && (matches!(toks.get(i - 1), Some(Tok::Punct('.')))
371                || matches!(toks.get(i - 1), Some(Tok::Ident(k, _)) if k == "fn"))
372        {
373            continue;
374        }
375        // Inside a path (`a::b`), the path was read from its first
376        // segment; a leading `::` (`::app::Message::new`) starts one.
377        if i > 2
378            && matches!(toks.get(i - 1), Some(Tok::Punct(':')))
379            && matches!(toks.get(i - 2), Some(Tok::Punct(':')))
380            && matches!(toks.get(i - 3), Some(Tok::Ident(..)))
381        {
382            continue;
383        }
384        let Some(p) = patterns.iter().find(|p| names(&callee, p.callee)) else {
385            continue;
386        };
387        let args = arguments(&toks, j);
388        let literal = |n: usize| match args.get(n) {
389            Some(a) if a.len() == 1 => match &a[0] {
390                Tok::Str(s, _) => Some(s.clone()),
391                _ => None,
392            },
393            _ => None,
394        };
395        let origin = format!("{file}:{line}");
396        let mut unread = |reason: String| {
397            if constructor(p) {
398                let u = Unread {
399                    callee: callee.clone(),
400                    origin: origin.clone(),
401                    reason,
402                };
403                log::warn!("i18n extraction: {u}");
404                out.unread.push(u);
405            }
406        };
407        let key = match literal(p.key) {
408            Some(k) if valid_key(&k) => k,
409            Some(k) => {
410                unread(format!("`{k}` is not a Fluent key"));
411                continue;
412            }
413            None => {
414                unread("the key is not a string literal".into());
415                continue;
416            }
417        };
418        let english = match p.english.map(|n| (n, literal(n))) {
419            Some((_, Some(e))) => English::Pattern(e),
420            Some((n, None)) => {
421                unread(format!(
422                    "its English (argument {}) is not a string literal: `{key}` is kept without it",
423                    n + 1
424                ));
425                English::None
426            }
427            None => English::None,
428        };
429        out.found.push(Found {
430            key,
431            english,
432            origin,
433        });
434    }
435    out
436}
437
438/// The keys a Rust source uses through `patterns`, with their English:
439/// [`scan`]'s keys, its unread calls only logged.
440pub fn scan_source(source: &str, file: &str, patterns: &[Pattern]) -> Vec<Found> {
441    scan(source, file, patterns).found
442}
443
444/// The arguments of the call whose `(` is at `open`, each as its tokens.
445fn arguments(toks: &[Tok], open: usize) -> Vec<Vec<Tok>> {
446    let mut out = vec![Vec::new()];
447    let mut depth = 0;
448    for t in &toks[open..] {
449        match t {
450            Tok::Punct('(' | '[' | '{') => {
451                depth += 1;
452                if depth == 1 {
453                    continue;
454                }
455            }
456            Tok::Punct(')' | ']' | '}') => {
457                depth -= 1;
458                if depth == 0 {
459                    break;
460                }
461            }
462            Tok::Punct(',') if depth == 1 => {
463                out.push(Vec::new());
464                continue;
465            }
466            _ => {}
467        }
468        if let Some(last) = out.last_mut() {
469            last.push(t.clone());
470        }
471    }
472    out
473}
474
475/// [`scan`] over every `.rs` file under `dir` (`target` and hidden
476/// directories skipped), files in a stable order; origins are relative
477/// to `dir`.
478pub fn scan_tree(dir: &Path, patterns: &[Pattern]) -> io::Result<Scan> {
479    let mut files = Vec::new();
480    walk(dir, &mut files)?;
481    files.sort();
482    let mut out = Scan::default();
483    for f in files {
484        let source = std::fs::read_to_string(&f)?;
485        let name = f.strip_prefix(dir).unwrap_or(&f).display().to_string();
486        out.extend(scan(&source, &name, patterns));
487    }
488    Ok(out)
489}
490
491/// [`scan_tree`]'s keys, its unread calls only logged.
492pub fn scan_dir(dir: &Path, patterns: &[Pattern]) -> io::Result<Vec<Found>> {
493    Ok(scan_tree(dir, patterns)?.found)
494}
495
496fn walk(dir: &Path, out: &mut Vec<std::path::PathBuf>) -> io::Result<()> {
497    for e in std::fs::read_dir(dir)? {
498        let p = e?.path();
499        let name = p.file_name().and_then(|n| n.to_str()).unwrap_or_default();
500        if p.is_dir() {
501            if name != "target" && !name.starts_with('.') {
502                walk(&p, out)?;
503            }
504        } else if p.extension().is_some_and(|e| e == "rs") {
505            out.push(p);
506        }
507    }
508    Ok(())
509}
510
511/// What a built application declares, under the keys
512/// `egui_pop_core::strings` derives: commands (title, description,
513/// category; a panel's `focus` and `toggle` commands only their
514/// category, their texts being shared), panels, submenus (from the main menu and `menus`),
515/// settings (label, description, each choice), plugins (title) and the
516/// context stack's frames (title).
517pub fn declarations(app: &AppHandle, menus: &[MenuId]) -> Vec<Found> {
518    let mut out = Vec::new();
519    // Command titles, which may say `{ $application }`.
520    let mut titles = Vec::new();
521    let mut push = |key: String, text: &str, origin: String| {
522        if !text.trim().is_empty() {
523            out.push(Found {
524                key,
525                english: English::Plain(text.to_string()),
526                origin,
527            });
528        }
529    };
530    let ctx = app.egui();
531    for (spec, _) in app.commands() {
532        let id = spec.id.as_str();
533        let origin = format!("command {id}");
534        // A panel's commands read texts shared by every panel (egui-pop's
535        // catalogue has them): nothing of their own to translate.
536        if strings::panel_command(&ctx, id).is_none() {
537            // A title may say `{ $application }` (filled where it is
538            // drawn): kept as a placeable, the rest as plain text.
539            if !spec.title.trim().is_empty() {
540                titles.push(Found {
541                    key: strings::declared_key(kind::COMMAND, id, Some("title")),
542                    english: plain_with(&spec.title, COMMAND_TITLE_VARIABLES),
543                    origin: origin.clone(),
544                });
545            }
546            push(
547                strings::declared_key(kind::COMMAND, id, Some("description")),
548                &spec.description,
549                origin.clone(),
550            );
551        }
552        push(
553            strings::category_key(&spec.category),
554            &spec.category,
555            origin,
556        );
557    }
558    for p in app.panels() {
559        push(
560            strings::declared_key(kind::PANEL, p.id.as_str(), Some("title")),
561            &p.title,
562            format!("panel {}", p.id),
563        );
564    }
565    let mut seen = BTreeSet::new();
566    let mut todo: Vec<MenuId> = vec![MENU_MAIN];
567    todo.extend(menus.iter().cloned());
568    while let Some(menu) = todo.pop() {
569        if !seen.insert(menu.clone()) {
570            continue;
571        }
572        for item in app.menu(&menu) {
573            if let Item::Submenu { menu: sub, label } = &item.item {
574                push(
575                    strings::declared_key(kind::MENU, sub.as_str(), Some("label")),
576                    label,
577                    format!("menu {sub}"),
578                );
579                todo.push(sub.clone());
580            }
581        }
582    }
583    for s in app.settings() {
584        let id = s.id.as_str();
585        let origin = format!("setting {id}");
586        push(
587            strings::declared_key(kind::SETTING, id, Some("label")),
588            &s.descriptor.label,
589            origin.clone(),
590        );
591        push(
592            strings::declared_key(kind::SETTING, id, Some("description")),
593            &s.descriptor.description,
594            origin.clone(),
595        );
596        for c in &s.descriptor.choices {
597            push(strings::setting_choice_key(id, c), c, origin.clone());
598        }
599    }
600    for p in app.plugins().into_iter().filter(|p| p.connected) {
601        push(
602            strings::declared_key(kind::PLUGIN, p.id.as_str(), Some("title")),
603            &p.title,
604            format!("plugin {}", p.id),
605        );
606    }
607    for (_, t) in egui_pop_api::clipboard::types(app) {
608        push(
609            egui_pop_api::clipboard::type_title_key(&t.format),
610            &t.title,
611            format!("clipboard type {}", t.format),
612        );
613    }
614    let frames = egui_pop_api::contexts::with_owner(app, |c| c.registry()).unwrap_or_default();
615    for f in frames.iter() {
616        push(
617            strings::declared_key(kind::FRAME, f.id.as_str(), Some("title")),
618            &f.title,
619            format!("frame {}", f.id),
620        );
621    }
622    out.extend(titles);
623    out
624}
625
626/// Keys with their English, deduplicated.
627pub type Messages = BTreeMap<String, English>;
628
629/// What was found, by key. Refused when one key is given two different
630/// English texts (two ids that differ only by punctuation, one key used
631/// with two texts); categories, keyed by their English, keep the first.
632pub fn messages(found: &[Found]) -> Result<Messages, String> {
633    let mut out: Messages = BTreeMap::new();
634    let mut origin: BTreeMap<&str, &str> = BTreeMap::new();
635    let mut errors = Vec::new();
636    for f in found {
637        match out.get(&f.key) {
638            None => {
639                out.insert(f.key.clone(), f.english.clone());
640                origin.insert(&f.key, &f.origin);
641            }
642            Some(English::None) => {
643                out.insert(f.key.clone(), f.english.clone());
644            }
645            Some(e) if *e == f.english || f.english == English::None => {}
646            Some(_) if f.key.starts_with("category-") => {}
647            Some(e) => errors.push(format!(
648                "`{}` has two English texts: {e:?} ({}) and {:?} ({})",
649                f.key,
650                origin.get(f.key.as_str()).unwrap_or(&"?"),
651                f.english,
652                f.origin
653            )),
654        }
655    }
656    if errors.is_empty() {
657        Ok(out)
658    } else {
659        Err(errors.join("\n"))
660    }
661}
662
663/// The variables a command's title may say (`{ $application }`, the
664/// application's name), filled where the title is drawn.
665pub const COMMAND_TITLE_VARIABLES: &[&str] = &["application"];
666
667/// Plain text in which the placeables of `variables` (`{ $name }` or
668/// `{$name}`) stay placeables: [`English::Plain`] when it has none, else
669/// an [`English::Pattern`] with every other brace escaped.
670///
671/// ```
672/// use egui_pop_i18n::extract::{English, plain_with};
673///
674/// assert_eq!(
675///     plain_with("About { $application } {x}", &["application"]),
676///     English::Pattern("About { $application } {\"{\"}x{\"}\"}".into())
677/// );
678/// assert_eq!(plain_with("Use { $other }", &["application"]), English::Plain("Use { $other }".into()));
679/// ```
680pub fn plain_with(text: &str, variables: &[&str]) -> English {
681    let mut pattern = escape(text);
682    let mut found = false;
683    for v in variables {
684        for (spaced, written) in [(true, format!("{{ ${v} }}")), (false, format!("{{${v}}}"))] {
685            let escaped = if spaced {
686                format!("{{\"{{\"}} ${v} {{\"}}\"}}")
687            } else {
688                format!("{{\"{{\"}}${v}{{\"}}\"}}")
689            };
690            if text.contains(&written) {
691                found = true;
692                pattern = pattern.replace(&escaped, &format!("{{ ${v} }}"));
693            }
694        }
695    }
696    if found {
697        English::Pattern(pattern)
698    } else {
699        English::Plain(text.to_string())
700    }
701}
702
703/// Text as a Fluent pattern that formats back to itself: braces are
704/// string literals, continuation lines indented, and a continuation line
705/// that would read as syntax quoted.
706pub fn escape(text: &str) -> String {
707    let text = text.trim();
708    let mut out = String::new();
709    for (n, line) in text.split('\n').enumerate() {
710        if n > 0 {
711            out.push('\n');
712        }
713        let mut chars = line.trim_start().chars().peekable();
714        if n > 0 && matches!(chars.peek(), Some('[' | '*' | '.')) {
715            let c = chars.next().expect("peeked");
716            let _ = write!(out, "{{\"{c}\"}}");
717        }
718        for c in chars {
719            match c {
720                '{' => out.push_str("{\"{\"}"),
721                '}' => out.push_str("{\"}\"}"),
722                c => out.push(c),
723            }
724        }
725    }
726    out
727}
728
729/// A Fluent pattern written as a value: continuation lines indented.
730fn indent(pattern: &str) -> String {
731    pattern.trim().replace('\n', "\n    ")
732}
733
734/// The pattern source of each key of a Fluent file, as written.
735fn existing(source: &str) -> BTreeMap<String, String> {
736    let resource = match fluent_syntax::parser::parse(source) {
737        Ok(r) | Err((r, _)) => r,
738    };
739    let mut out = BTreeMap::new();
740    for entry in &resource.body {
741        if let Entry::Message(m) = entry {
742            if let Some(v) = &m.value {
743                out.insert(m.id.name.to_string(), serialize(v));
744            }
745            for a in &m.attributes {
746                out.insert(format!("{}.{}", m.id.name, a.id.name), serialize(&a.value));
747            }
748        }
749    }
750    out
751}
752
753/// A pattern's source as Fluent's serializer writes it.
754pub(crate) fn serialize(pattern: &FtlPattern<&str>) -> String {
755    let resource = Resource {
756        body: vec![Entry::Message(Message {
757            id: Identifier { name: "m" },
758            value: Some(pattern.clone()),
759            attributes: Vec::new(),
760            comment: None,
761        })],
762    };
763    let s = fluent_syntax::serializer::serialize(&resource);
764    let s = s.strip_prefix("m =").unwrap_or(&s);
765    // A value written on its own lines comes back indented: unindent it.
766    s.trim_end()
767        .lines()
768        .map(|l| l.strip_prefix("    ").unwrap_or(l))
769        .collect::<Vec<_>>()
770        .join("\n")
771        .trim()
772        .to_string()
773}
774
775/// Writes keys with their pattern sources as a Fluent file, messages
776/// sorted by id, attributes under their message.
777fn write(header: &str, patterns: &BTreeMap<String, String>) -> String {
778    let mut messages: BTreeMap<&str, (Option<&str>, BTreeMap<&str, &str>)> = BTreeMap::new();
779    for (key, pattern) in patterns {
780        let (id, attr) = crate::catalog::split_key(key);
781        let entry = messages.entry(id).or_default();
782        match attr {
783            Some(a) => {
784                entry.1.insert(a, pattern);
785            }
786            None => entry.0 = Some(pattern),
787        }
788    }
789    let mut out = String::from(header);
790    for (id, (value, attrs)) in messages {
791        if !out.is_empty() {
792            out.push('\n');
793        }
794        out.push_str(id);
795        out.push_str(" =");
796        if let Some(v) = value {
797            out.push(' ');
798            out.push_str(&indent(v));
799        }
800        out.push('\n');
801        for (a, v) in attrs {
802            let _ = writeln!(out, "    .{a} = {}", indent(v).replace('\n', "\n    "));
803        }
804    }
805    out
806}
807
808/// A key's English as a Fluent pattern; `None` when the code gives none.
809fn pattern_of(english: &English) -> Option<String> {
810    match english {
811        English::Plain(t) => Some(escape(t)),
812        English::Pattern(p) => Some(p.trim().to_string()),
813        English::None => None,
814    }
815}
816
817/// The English catalogue of `messages`: sorted, the same keys giving
818/// the same bytes; a key without English reads as itself. `header` (a
819/// Fluent comment, `# …` lines) comes first.
820pub fn english(messages: &Messages, header: &str) -> String {
821    let patterns = messages
822        .iter()
823        .map(|(k, e)| (k.clone(), pattern_of(e).unwrap_or_else(|| k.clone())))
824        .collect();
825    write(header, &patterns)
826}
827
828/// An English catalogue brought up to date.
829#[derive(Clone, Debug, Default, PartialEq, Eq)]
830pub struct Updated {
831    /// The new source.
832    pub source: String,
833    /// Keys that were not in it.
834    pub added: Vec<String>,
835    /// Keys whose English the code changed.
836    pub changed: Vec<String>,
837    /// Keys in it that the code no longer uses (dropped when pruning).
838    pub unused: Vec<String>,
839}
840
841/// `messages` merged into the English catalogue `source`: the code's
842/// English wins; for a key the code gives none, the catalogue's is kept
843/// (a new one reads as its key). Unused keys are kept unless `prune`.
844/// The result is sorted like [`english`].
845pub fn update(source: &str, messages: &Messages, header: &str, prune: bool) -> Updated {
846    let old = existing(source);
847    let mut out = Updated::default();
848    let mut patterns = BTreeMap::new();
849    for (key, english) in messages {
850        let new = pattern_of(english);
851        let pattern = match (old.get(key), new) {
852            (None, new) => {
853                out.added.push(key.clone());
854                new.unwrap_or_else(|| key.clone())
855            }
856            (Some(was), Some(new)) => {
857                if canonical(was) != canonical(&new) {
858                    out.changed.push(key.clone());
859                }
860                new
861            }
862            (Some(was), None) => was.clone(),
863        };
864        patterns.insert(key.clone(), pattern);
865    }
866    for (key, was) in &old {
867        if !messages.contains_key(key) {
868            out.unused.push(key.clone());
869            if !prune {
870                patterns.insert(key.clone(), was.clone());
871            }
872        }
873    }
874    out.source = write(header, &patterns);
875    out
876}
877
878/// The catalogue check of an English catalogue: `None` when `current`
879/// (the file at `path`) is `fresh` (what [`english`] or [`update`]
880/// writes now); else the failure message, saying `path` is out of date
881/// and listing `unread` (see [`Scan::unread`]), the calls whose
882/// messages are missing from it.
883pub fn out_of_date(path: &str, current: &str, fresh: &str, unread: &[Unread]) -> Option<String> {
884    if current == fresh {
885        return None;
886    }
887    let mut out = format!("{path} is out of date");
888    if !unread.is_empty() {
889        out.push_str("; the extractor could not read these calls, their messages are missing:");
890        for u in unread {
891            let _ = write!(out, "\n  {u}");
892        }
893    }
894    Some(out)
895}
896
897/// A pattern as Fluent's serializer writes it, to compare two.
898fn canonical(pattern: &str) -> String {
899    existing(&format!("m = {}\n", indent(pattern)))
900        .remove("m")
901        .unwrap_or_else(|| pattern.to_string())
902}
903
904/// One locale against what the code uses.
905#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize)]
906pub struct LocaleKeys {
907    pub locale: String,
908    /// Used by the code, not in this locale's catalogue.
909    pub missing: Vec<String>,
910    /// In this locale's catalogue, not used by the code.
911    pub unused: Vec<String>,
912}
913
914/// Every locale of `catalogs` against the keys the code uses.
915pub fn report(catalogs: &crate::check::Catalogs, messages: &Messages) -> Vec<LocaleKeys> {
916    let mut keys: BTreeMap<&str, BTreeSet<String>> = BTreeMap::new();
917    for f in &catalogs.files {
918        keys.entry(&f.locale)
919            .or_default()
920            .extend(existing(&f.source).into_keys());
921    }
922    keys.into_iter()
923        .map(|(locale, theirs)| LocaleKeys {
924            locale: locale.to_string(),
925            missing: messages
926                .keys()
927                .filter(|k| !theirs.contains(*k))
928                .cloned()
929                .collect(),
930            unused: theirs
931                .iter()
932                .filter(|k| !messages.contains_key(*k))
933                .cloned()
934                .collect(),
935        })
936        .collect()
937}
938
939#[cfg(test)]
940mod tests {
941    use super::*;
942
943    #[test]
944    fn calls_are_found_with_their_english() {
945        let src = r##"
946            // tr!("in-a-comment")
947            fn t(x: &str) {}
948            let a = tr!("plain");
949            let b = egui_pop_i18n::t(&ctx, "with-path", &args![n = 1]);
950            let c = obj.t(&ctx, "a-method");
951            const K: StrKey = StrKey::new(
952                "multi-line",
953                "Line { $n }",
954            );
955            let d = strings::lookup(ui.ctx(), "lookup-key", r#"Raw "quoted""#);
956            let e = tr!(dynamic_key);
957            let f = tr!("not a key");
958            let g = text(ctx, "attr-key.title", "Esc\"aped\n", &[]);
959        "##;
960        let found = scan_source(src, "x.rs", Pattern::DEFAULTS);
961        let keys: Vec<(&str, &English)> =
962            found.iter().map(|f| (f.key.as_str(), &f.english)).collect();
963        assert_eq!(
964            keys,
965            [
966                ("plain", &English::None),
967                ("with-path", &English::None),
968                ("multi-line", &English::Pattern("Line { $n }".into())),
969                ("lookup-key", &English::Pattern("Raw \"quoted\"".into())),
970                ("attr-key.title", &English::Pattern("Esc\"aped\n".into())),
971            ]
972        );
973        assert_eq!(found[0].origin, "x.rs:4");
974        assert_eq!(found[2].origin, "x.rs:7");
975    }
976
977    /// An application's constructor, next to the defaults.
978    const MESSAGE: &[Pattern] = &[
979        Pattern {
980            callee: "Message::new",
981            key: 0,
982            english: Some(1),
983        },
984        Pattern {
985            callee: "t",
986            key: 1,
987            english: None,
988        },
989    ];
990
991    #[test]
992    fn a_path_qualified_constructor_is_extracted() {
993        let src = r#"
994            const A: Message = Message::new("plain", "Plain");
995            const B: Message = app_core::Message::new("one-segment", "One");
996            const C: Message = crate::strings::Message::new("crate-path", "Crate");
997            const D: Message = ::app_core::Message::new("leading-colons", "Leading");
998            const E: StrKey = egui_pop::core::strings::StrKey::new("str-key", "Key");
999            const F: Other = app::NotMessage::new("not-ours", "No");
1000        "#;
1001        let mut patterns = MESSAGE.to_vec();
1002        patterns.extend_from_slice(Pattern::DEFAULTS);
1003        let s = scan(src, "x.rs", &patterns);
1004        let keys: Vec<&str> = s.found.iter().map(|f| f.key.as_str()).collect();
1005        assert_eq!(
1006            keys,
1007            [
1008                "plain",
1009                "one-segment",
1010                "crate-path",
1011                "leading-colons",
1012                "str-key"
1013            ]
1014        );
1015        assert_eq!(s.found[2].english, English::Pattern("Crate".into()));
1016        assert_eq!(s.found[3].origin, "x.rs:5");
1017        assert!(s.unread.is_empty(), "{:?}", s.unread);
1018    }
1019
1020    #[test]
1021    fn a_multi_line_qualified_constructor_is_extracted() {
1022        let src = "
1023            pub const READY: Message = app_core
1024                ::strings::
1025                Message // the status bar's
1026                ::new(
1027                    \"status-ready\",
1028                    \"Ready\",
1029                );
1030        ";
1031        let s = scan(src, "src/status.rs", MESSAGE);
1032        assert_eq!(
1033            s.found,
1034            [Found {
1035                key: "status-ready".into(),
1036                english: English::Pattern("Ready".into()),
1037                origin: "src/status.rs:2".into(),
1038            }]
1039        );
1040        assert!(s.unread.is_empty(), "{:?}", s.unread);
1041    }
1042
1043    #[test]
1044    fn an_unreadable_constructor_is_reported_with_its_file_and_line() {
1045        let src = r#"
1046            const OK: Message = Message::new("fine", "Fine");
1047            let dynamic = app::Message::new(id, "Text");
1048            let bad = Message::new("not a key", "Text");
1049            let computed = app::Message::new(
1050                "computed",
1051                concat!("Comp", "uted"),
1052            );
1053            // Not a constructor: a dynamic key stays silent.
1054            let looked_up = t(ctx, key);
1055        "#;
1056        let s = scan(src, "src/ui.rs", MESSAGE);
1057        let keys: Vec<(&str, &English)> = s
1058            .found
1059            .iter()
1060            .map(|f| (f.key.as_str(), &f.english))
1061            .collect();
1062        assert_eq!(
1063            keys,
1064            [
1065                ("fine", &English::Pattern("Fine".into())),
1066                ("computed", &English::None)
1067            ]
1068        );
1069        let places: Vec<(&str, &str)> = s
1070            .unread
1071            .iter()
1072            .map(|u| (u.origin.as_str(), u.callee.as_str()))
1073            .collect();
1074        assert_eq!(
1075            places,
1076            [
1077                ("src/ui.rs:3", "app::Message::new"),
1078                ("src/ui.rs:4", "Message::new"),
1079                ("src/ui.rs:5", "app::Message::new"),
1080            ]
1081        );
1082        assert_eq!(
1083            s.unread[0].to_string(),
1084            "src/ui.rs:3: `app::Message::new(…)` not read: the key is not a string literal"
1085        );
1086        // The catalogue check lists them when the catalogue is stale.
1087        let m = messages(&s.found).unwrap();
1088        let fresh = english(&m, "");
1089        assert_eq!(out_of_date("en/app.ftl", &fresh, &fresh, &s.unread), None);
1090        let failure = out_of_date("en/app.ftl", "", &fresh, &s.unread).unwrap();
1091        assert!(
1092            failure.starts_with("en/app.ftl is out of date"),
1093            "{failure}"
1094        );
1095        for u in &s.unread {
1096            assert!(failure.contains(&u.to_string()), "{failure}");
1097        }
1098    }
1099
1100    #[test]
1101    fn a_command_title_keeps_its_application_placeable() {
1102        let found = vec![Found {
1103            key: "command-about.title".into(),
1104            english: plain_with("About { $application }", COMMAND_TITLE_VARIABLES),
1105            origin: "command about".into(),
1106        }];
1107        let ftl = english(&messages(&found).unwrap(), "");
1108        assert_eq!(
1109            ftl.trim(),
1110            "command-about =\n    .title = About { $application }"
1111        );
1112        let i = crate::I18n::new("en");
1113        i.add("en", &ftl).unwrap();
1114        assert_eq!(
1115            i.t("command-about.title", &[("application", "Helios".into())]),
1116            "About Helios"
1117        );
1118        // Written without spaces, and beside a brace that stays text.
1119        assert_eq!(
1120            plain_with("{$application} {x}", COMMAND_TITLE_VARIABLES),
1121            English::Pattern("{ $application } {\"{\"}x{\"}\"}".into())
1122        );
1123    }
1124
1125    #[test]
1126    fn the_english_catalogue_is_sorted_and_round_trips() {
1127        let found = vec![
1128            Found {
1129                key: "command-b.title".into(),
1130                english: English::Plain("Use {braces}".into()),
1131                origin: "command b".into(),
1132            },
1133            Found {
1134                key: "a".into(),
1135                english: English::Pattern("Hi { $name }".into()),
1136                origin: "x.rs:1".into(),
1137            },
1138            Found {
1139                key: "command-b.description".into(),
1140                english: English::Plain("Two\nlines".into()),
1141                origin: "command b".into(),
1142            },
1143        ];
1144        let m = messages(&found).unwrap();
1145        let ftl = english(&m, "# Generated.\n");
1146        assert_eq!(
1147            ftl,
1148            "# Generated.\n\na = Hi { $name }\n\ncommand-b =\n    .description = Two\n        lines\n    .title = Use {\"{\"}braces{\"}\"}\n"
1149        );
1150        let i = crate::I18n::new("en");
1151        i.add("en", &ftl).unwrap();
1152        assert_eq!(i.t("command-b.title", &[]), "Use {braces}");
1153        assert_eq!(i.t("command-b.description", &[]), "Two\nlines");
1154        let mut twice = found.clone();
1155        twice.push(Found {
1156            key: "a".into(),
1157            english: English::Pattern("Other".into()),
1158            origin: "y.rs:2".into(),
1159        });
1160        assert!(messages(&twice).unwrap_err().contains("x.rs:1"));
1161    }
1162
1163    #[test]
1164    fn update_keeps_written_english_and_reports_changes() {
1165        let old = "# h\n\nkept = Written by hand\nold = Gone\nchanged = Before\n";
1166        let mut m = Messages::new();
1167        m.insert("kept".into(), English::None);
1168        m.insert("changed".into(), English::Pattern("After".into()));
1169        m.insert("new".into(), English::None);
1170        let u = update(old, &m, "# h\n", false);
1171        assert_eq!(u.added, ["new"]);
1172        assert_eq!(u.changed, ["changed"]);
1173        assert_eq!(u.unused, ["old"]);
1174        assert!(u.source.contains("kept = Written by hand\n"));
1175        assert!(u.source.contains("new = new\n"));
1176        assert!(u.source.contains("old = Gone\n"));
1177        let pruned = update(old, &m, "# h\n", true);
1178        assert!(!pruned.source.contains("old ="));
1179        // Up to date: nothing changes.
1180        let again = update(&u.source, &m, "# h\n", false);
1181        assert_eq!(again.source, u.source);
1182        assert!(again.added.is_empty() && again.changed.is_empty());
1183    }
1184
1185    #[test]
1186    fn the_context_stack_frames_are_declarations() {
1187        use egui_pop_api::contexts::{self, ContextsPlugin, FrameSpec};
1188        use egui_pop_api::{Ctx, Plugin, PluginError};
1189        use egui_pop_model::ids::{FrameId, GroupId, PluginId};
1190        struct Frames;
1191        impl Plugin for Frames {
1192            fn id(&self) -> PluginId {
1193                PluginId::from_static("demo")
1194            }
1195            fn requires(&self) -> Vec<PluginId> {
1196                vec![contexts::PLUGIN]
1197            }
1198            fn connect(&mut self, ctx: &mut Ctx<'_>) -> Result<(), PluginError> {
1199                ctx.frame(FrameSpec::place(
1200                    FrameId::from_static("demo.album"),
1201                    "Album",
1202                ))?
1203                .frame(FrameSpec::mode(
1204                    FrameId::from_static("demo.culling"),
1205                    GroupId::from_static("orientation"),
1206                    "Culling",
1207                ))?;
1208                Ok(())
1209            }
1210        }
1211        let app = egui_pop_api::App::builder()
1212            .plugin(ContextsPlugin::default())
1213            .plugin(Frames)
1214            .build(&egui::Context::default())
1215            .unwrap();
1216        let found = declarations(app.handle(), &[]);
1217        let frames: Vec<(&str, &English, &str)> = found
1218            .iter()
1219            .filter(|f| f.key.starts_with("frame-"))
1220            .map(|f| (f.key.as_str(), &f.english, f.origin.as_str()))
1221            .collect();
1222        assert_eq!(
1223            frames,
1224            [
1225                (
1226                    "frame-demo-album.title",
1227                    &English::Plain("Album".into()),
1228                    "frame demo.album"
1229                ),
1230                (
1231                    "frame-demo-culling.title",
1232                    &English::Plain("Culling".into()),
1233                    "frame demo.culling"
1234                ),
1235            ]
1236        );
1237    }
1238
1239    #[test]
1240    fn multi_line_patterns_survive_a_rewrite() {
1241        let old = "plural =\n    { $n ->\n        [one] one\n       *[other] many\n    }\n";
1242        let mut m = Messages::new();
1243        m.insert("plural".into(), English::None);
1244        let u = update(old, &m, "", false);
1245        let i = crate::I18n::new("en");
1246        i.add("en", &u.source).unwrap();
1247        assert_eq!(i.t("plural", &crate::args![n = 1]), "one");
1248        assert_eq!(i.t("plural", &crate::args![n = 5]), "many");
1249    }
1250}