pikopiko-runtime 0.1.0

no_std, heap-free runtime for pikopiko: synth trait, event-binary sequencer, effects and built-in synths (AY-3-8912, buzzer, sfx).
Documentation
//! 訳せる文(エラーの文など)の口と、文の表。`no_std`・ヒープなし。
//!
//! 文は各クレートの `locales/<種類>-<言語>.ftl` にあり、ビルドのときに静的な表([`Catalog`])に
//! なって埋め込まれる(`pikopiko-textgen`)。エラーの型は [`Localized`] でキー(`err-…`)と値と表を
//! 示し、`Display` は既定の言語([`DEFAULT_LANG`])の文を出す。ほかの言語は [`write_localized`] や
//! [`InLang`] で出す。

use core::fmt;

/// 表にその言語の文がないときに使う言語(翻訳の基準)。
pub const BASE_LANG: &str = "en";

/// 言語を指定しないとき(`Display`・ログ・`?` で伝わるエラーなど)の言語。Rust のライブラリの
/// 慣例に合わせて英語にし、翻訳の基準([`BASE_LANG`])と同じにする。画面に出す文は、表示の
/// 言語を渡して [`InLang`] や [`write_localized`] で作る。
pub const DEFAULT_LANG: &str = BASE_LANG;

/// 文の値。
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TextArg<'a> {
    /// 訳さない文字列(ファイル名、外のライブラリのエラーの文など)。
    Str(&'a str),
    /// 数。
    Int(i64),
}

impl fmt::Display for TextArg<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            TextArg::Str(s) => f.write_str(s),
            TextArg::Int(n) => write!(f, "{n}"),
        }
    }
}

/// 文の部品。
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Seg {
    /// そのまま出す文字列。
    Lit(&'static str),
    /// 値の場所(名前)。
    Var(&'static str),
}

/// 1 つの言語の文の表。`entries` はキーで並べてある。
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Catalog {
    /// 言語(`en`、`ja`)。
    pub lang: &'static str,
    /// (キー, 文)。
    pub entries: &'static [(&'static str, &'static [Seg])],
}

impl Catalog {
    /// キーの文。
    pub fn get(&self, key: &str) -> Option<&'static [Seg]> {
        self.entries
            .binary_search_by(|(k, _)| (*k).cmp(key))
            .ok()
            .map(|i| self.entries[i].1)
    }
}

/// 表の並びから、`lang` の文を引く。なければ基準の言語([`BASE_LANG`])の文。
pub fn find(catalogs: &[Catalog], lang: &str, key: &str) -> Option<&'static [Seg]> {
    let get = |l: &str| {
        catalogs
            .iter()
            .find(|c| c.lang == l)
            .and_then(|c| c.get(key))
    };
    get(lang).or_else(|| get(BASE_LANG))
}

/// 文の部品を順に書く。値の場所では `var(名前, 書き込み先)` を呼ぶ。
pub fn write_segs(
    out: &mut dyn fmt::Write,
    segs: &[Seg],
    var: &mut dyn FnMut(&str, &mut dyn fmt::Write) -> fmt::Result,
) -> fmt::Result {
    for s in segs {
        match s {
            Seg::Lit(t) => out.write_str(t)?,
            Seg::Var(n) => var(n, out)?,
        }
    }
    Ok(())
}

/// キーと値で訳せる文。
pub trait Localized {
    /// 訳のキー(`err-…`)。
    fn text_key(&self) -> &'static str;

    /// 値を名前つきで順に渡す。値がなければ何もしない(既定)。
    fn text_args(&self, f: &mut dyn FnMut(&'static str, TextArg<'_>)) {
        let _ = f;
    }

    /// この型の文の表(そのクレートの `locales/*.ftl` から作ったもの)。表を持たない型は空(既定)で、
    /// そのときは表示する側が自分の訳を引く。
    fn catalogs(&self) -> &'static [Catalog] {
        &[]
    }
}

/// `e` の文を `lang` で書く(なければ基準の言語、それもなければキー)。
pub fn write_localized<E: Localized + ?Sized>(
    out: &mut dyn fmt::Write,
    e: &E,
    lang: &str,
) -> fmt::Result {
    let Some(segs) = find(e.catalogs(), lang, e.text_key()) else {
        return out.write_str(e.text_key());
    };
    write_segs(out, segs, &mut |name, w| {
        let mut r = Ok(());
        e.text_args(&mut |n, v| {
            if n == name && r.is_ok() {
                r = write!(w, "{v}");
            }
        });
        r
    })
}

/// 言語を選んで `Display` で出すための包み(`InLang(&e, "en").to_string()` など)。
pub struct InLang<'a, E: ?Sized>(pub &'a E, pub &'a str);

impl<E: Localized + ?Sized> fmt::Display for InLang<'_, E> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write_localized(f, self.0, self.1)
    }
}

/// このクレートの文の表(`locales/*.ftl`)。
pub(crate) mod table {
    use super::{Catalog, Seg};
    include!(concat!(env!("OUT_DIR"), "/text.rs"));
}

#[cfg(test)]
mod tests {
    use super::*;

    struct E(i64);
    static CATS: &[Catalog] = &[
        Catalog {
            lang: "en",
            entries: &[("k", &[Seg::Lit("n="), Seg::Var("n"), Seg::Lit("!")])],
        },
        Catalog {
            lang: "ja",
            entries: &[],
        },
    ];
    impl Localized for E {
        fn text_key(&self) -> &'static str {
            "k"
        }
        fn text_args(&self, f: &mut dyn FnMut(&'static str, TextArg<'_>)) {
            f("n", TextArg::Int(self.0));
        }
        fn catalogs(&self) -> &'static [Catalog] {
            CATS
        }
    }

    struct Buf([u8; 32], usize);
    impl fmt::Write for Buf {
        fn write_str(&mut self, s: &str) -> fmt::Result {
            let b = s.as_bytes();
            let end = self.1 + b.len();
            if end > self.0.len() {
                return Err(fmt::Error);
            }
            self.0[self.1..end].copy_from_slice(b);
            self.1 = end;
            Ok(())
        }
    }

    #[test]
    fn falls_back_to_the_base_language() {
        let mut b = Buf([0; 32], 0);
        write_localized(&mut b, &E(-3), "ja").unwrap();
        assert_eq!(core::str::from_utf8(&b.0[..b.1]).unwrap(), "n=-3!");
    }
}