Skip to main content

pikopiko_runtime/
text.rs

1//! 訳せる文(エラーの文など)の口と、文の表。`no_std`・ヒープなし。
2//!
3//! 文は各クレートの `locales/<種類>-<言語>.ftl` にあり、ビルドのときに静的な表([`Catalog`])に
4//! なって埋め込まれる(`pikopiko-textgen`)。エラーの型は [`Localized`] でキー(`err-…`)と値と表を
5//! 示し、`Display` は既定の言語([`DEFAULT_LANG`])の文を出す。ほかの言語は [`write_localized`] や
6//! [`InLang`] で出す。
7
8use core::fmt;
9
10/// 表にその言語の文がないときに使う言語(翻訳の基準)。
11pub const BASE_LANG: &str = "en";
12
13/// 言語を指定しないとき(`Display`・ログ・`?` で伝わるエラーなど)の言語。Rust のライブラリの
14/// 慣例に合わせて英語にし、翻訳の基準([`BASE_LANG`])と同じにする。画面に出す文は、表示の
15/// 言語を渡して [`InLang`] や [`write_localized`] で作る。
16pub const DEFAULT_LANG: &str = BASE_LANG;
17
18/// 文の値。
19#[derive(Debug, Clone, Copy, PartialEq, Eq)]
20pub enum TextArg<'a> {
21    /// 訳さない文字列(ファイル名、外のライブラリのエラーの文など)。
22    Str(&'a str),
23    /// 数。
24    Int(i64),
25}
26
27impl fmt::Display for TextArg<'_> {
28    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
29        match self {
30            TextArg::Str(s) => f.write_str(s),
31            TextArg::Int(n) => write!(f, "{n}"),
32        }
33    }
34}
35
36/// 文の部品。
37#[derive(Debug, Clone, Copy, PartialEq, Eq)]
38pub enum Seg {
39    /// そのまま出す文字列。
40    Lit(&'static str),
41    /// 値の場所(名前)。
42    Var(&'static str),
43}
44
45/// 1 つの言語の文の表。`entries` はキーで並べてある。
46#[derive(Debug, Clone, Copy, PartialEq, Eq)]
47pub struct Catalog {
48    /// 言語(`en`、`ja`)。
49    pub lang: &'static str,
50    /// (キー, 文)。
51    pub entries: &'static [(&'static str, &'static [Seg])],
52}
53
54impl Catalog {
55    /// キーの文。
56    pub fn get(&self, key: &str) -> Option<&'static [Seg]> {
57        self.entries
58            .binary_search_by(|(k, _)| (*k).cmp(key))
59            .ok()
60            .map(|i| self.entries[i].1)
61    }
62}
63
64/// 表の並びから、`lang` の文を引く。なければ基準の言語([`BASE_LANG`])の文。
65pub fn find(catalogs: &[Catalog], lang: &str, key: &str) -> Option<&'static [Seg]> {
66    let get = |l: &str| {
67        catalogs
68            .iter()
69            .find(|c| c.lang == l)
70            .and_then(|c| c.get(key))
71    };
72    get(lang).or_else(|| get(BASE_LANG))
73}
74
75/// 文の部品を順に書く。値の場所では `var(名前, 書き込み先)` を呼ぶ。
76pub fn write_segs(
77    out: &mut dyn fmt::Write,
78    segs: &[Seg],
79    var: &mut dyn FnMut(&str, &mut dyn fmt::Write) -> fmt::Result,
80) -> fmt::Result {
81    for s in segs {
82        match s {
83            Seg::Lit(t) => out.write_str(t)?,
84            Seg::Var(n) => var(n, out)?,
85        }
86    }
87    Ok(())
88}
89
90/// キーと値で訳せる文。
91pub trait Localized {
92    /// 訳のキー(`err-…`)。
93    fn text_key(&self) -> &'static str;
94
95    /// 値を名前つきで順に渡す。値がなければ何もしない(既定)。
96    fn text_args(&self, f: &mut dyn FnMut(&'static str, TextArg<'_>)) {
97        let _ = f;
98    }
99
100    /// この型の文の表(そのクレートの `locales/*.ftl` から作ったもの)。表を持たない型は空(既定)で、
101    /// そのときは表示する側が自分の訳を引く。
102    fn catalogs(&self) -> &'static [Catalog] {
103        &[]
104    }
105}
106
107/// `e` の文を `lang` で書く(なければ基準の言語、それもなければキー)。
108pub fn write_localized<E: Localized + ?Sized>(
109    out: &mut dyn fmt::Write,
110    e: &E,
111    lang: &str,
112) -> fmt::Result {
113    let Some(segs) = find(e.catalogs(), lang, e.text_key()) else {
114        return out.write_str(e.text_key());
115    };
116    write_segs(out, segs, &mut |name, w| {
117        let mut r = Ok(());
118        e.text_args(&mut |n, v| {
119            if n == name && r.is_ok() {
120                r = write!(w, "{v}");
121            }
122        });
123        r
124    })
125}
126
127/// 言語を選んで `Display` で出すための包み(`InLang(&e, "en").to_string()` など)。
128pub struct InLang<'a, E: ?Sized>(pub &'a E, pub &'a str);
129
130impl<E: Localized + ?Sized> fmt::Display for InLang<'_, E> {
131    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
132        write_localized(f, self.0, self.1)
133    }
134}
135
136/// このクレートの文の表(`locales/*.ftl`)。
137pub(crate) mod table {
138    use super::{Catalog, Seg};
139    include!(concat!(env!("OUT_DIR"), "/text.rs"));
140}
141
142#[cfg(test)]
143mod tests {
144    use super::*;
145
146    struct E(i64);
147    static CATS: &[Catalog] = &[
148        Catalog {
149            lang: "en",
150            entries: &[("k", &[Seg::Lit("n="), Seg::Var("n"), Seg::Lit("!")])],
151        },
152        Catalog {
153            lang: "ja",
154            entries: &[],
155        },
156    ];
157    impl Localized for E {
158        fn text_key(&self) -> &'static str {
159            "k"
160        }
161        fn text_args(&self, f: &mut dyn FnMut(&'static str, TextArg<'_>)) {
162            f("n", TextArg::Int(self.0));
163        }
164        fn catalogs(&self) -> &'static [Catalog] {
165            CATS
166        }
167    }
168
169    struct Buf([u8; 32], usize);
170    impl fmt::Write for Buf {
171        fn write_str(&mut self, s: &str) -> fmt::Result {
172            let b = s.as_bytes();
173            let end = self.1 + b.len();
174            if end > self.0.len() {
175                return Err(fmt::Error);
176            }
177            self.0[self.1..end].copy_from_slice(b);
178            self.1 = end;
179            Ok(())
180        }
181    }
182
183    #[test]
184    fn falls_back_to_the_base_language() {
185        let mut b = Buf([0; 32], 0);
186        write_localized(&mut b, &E(-3), "ja").unwrap();
187        assert_eq!(core::str::from_utf8(&b.0[..b.1]).unwrap(), "n=-3!");
188    }
189}