pub const LANGUAGES: &[(&str, &str)] = &[("en", "English"), ("ja", "日本語")];
pub fn resolve(tag: &str) -> &'static str {
lookup(tag).unwrap_or(LANGUAGES[0].0)
}
pub fn lookup(tag: &str) -> Option<&'static str> {
let base = tag.split('.').next().unwrap_or(tag);
let lang = base
.split(['-', '_', '@'])
.next()
.unwrap_or_default()
.trim()
.to_ascii_lowercase();
LANGUAGES.iter().map(|(t, _)| *t).find(|t| *t == lang)
}
pub fn pick(env: Option<&str>, os: Option<&str>) -> &'static str {
let tag = env
.filter(|s| !s.trim().is_empty())
.or(os)
.unwrap_or_default();
resolve(tag)
}
pub fn io_error(e: &std::io::Error, lang: &str) -> String {
let key = io_error_key(e);
let Some(segs) = crate::text::find(crate::text_table::CATALOGS, lang, key) else {
return e.to_string();
};
let detail = e.to_string();
let mut out = String::new();
let _ = crate::text::write_segs(&mut out, segs, &mut |_, w| w.write_str(&detail));
out
}
pub fn io_error_key(e: &std::io::Error) -> &'static str {
use std::io::ErrorKind as K;
match e.kind() {
K::NotFound => "io-not-found",
K::PermissionDenied => "io-permission-denied",
K::AlreadyExists => "io-already-exists",
K::InvalidData => "io-invalid-data",
K::UnexpectedEof => "io-unexpected-eof",
K::BrokenPipe => "io-broken-pipe",
K::OutOfMemory => "io-out-of-memory",
K::Unsupported => "io-unsupported",
_ => "io-other",
}
}
#[derive(Debug, Clone, PartialEq)]
pub enum Arg {
Str(String),
Num(f64),
}
impl std::fmt::Display for Arg {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Arg::Str(s) => f.write_str(s),
Arg::Num(n) => write!(f, "{n}"),
}
}
}
impl From<&str> for Arg {
fn from(s: &str) -> Self {
Arg::Str(s.to_string())
}
}
impl From<String> for Arg {
fn from(s: String) -> Self {
Arg::Str(s)
}
}
impl From<f64> for Arg {
fn from(n: f64) -> Self {
Arg::Num(n)
}
}
impl From<u64> for Arg {
fn from(n: u64) -> Self {
Arg::Num(n as f64)
}
}
impl From<u32> for Arg {
fn from(n: u32) -> Self {
Arg::Num(f64::from(n))
}
}
impl From<usize> for Arg {
fn from(n: usize) -> Self {
Arg::Num(n as f64)
}
}
impl From<i64> for Arg {
fn from(n: i64) -> Self {
Arg::Num(n as f64)
}
}
#[cfg(feature = "fluent")]
pub use fluent::I18n;
#[cfg(feature = "fluent")]
mod fluent {
use super::{Arg, LANGUAGES};
use crate::compiler::diagnostic::{DiagArg, Diagnostic};
use crate::text::{Catalog, Localized, Seg, TextArg};
use crate::SynthSpec;
use fluent_bundle::concurrent::FluentBundle;
use fluent_bundle::{FluentArgs, FluentResource, FluentValue};
use unic_langid::LanguageIdentifier;
type Bundle = FluentBundle<FluentResource>;
fn plain(segs: &[Seg]) -> String {
let mut out = String::new();
let _ = crate::text::write_segs(&mut out, segs, &mut |_, _| Ok(()));
out
}
fn bundle(tag: &str, resources: &[(&str, &[&str])]) -> Bundle {
let id: LanguageIdentifier = tag.parse().expect("言語タグが不正");
let mut b = FluentBundle::new_concurrent(vec![id]);
b.set_use_isolating(false);
for src in resources
.iter()
.filter(|(t, _)| *t == tag)
.flat_map(|(_, s)| s.iter())
{
let res = FluentResource::try_new((*src).to_string()).expect("ftl の構文が不正");
b.add_resource(res).expect("ftl のキーが重複している");
}
b
}
fn fluent_args(args: &[(&str, Arg)]) -> FluentArgs<'static> {
let mut fa = FluentArgs::new();
for (name, v) in args {
match v {
Arg::Str(s) => fa.set(name.to_string(), FluentValue::from(s.clone())),
Arg::Num(n) => fa.set(name.to_string(), FluentValue::from(*n)),
}
}
fa
}
pub struct I18n {
tag: &'static str,
current: Bundle,
fallback: Bundle,
}
impl std::fmt::Debug for I18n {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("I18n").field("lang", &self.tag).finish()
}
}
impl I18n {
pub fn new(tag: &str, resources: &[(&str, &[&str])]) -> Self {
let tag = super::resolve(tag);
I18n {
tag,
current: bundle(tag, resources),
fallback: bundle(LANGUAGES[0].0, resources),
}
}
pub fn lang(&self) -> &'static str {
self.tag
}
fn format(b: &Bundle, key: &str, args: &[(&str, Arg)]) -> Option<(String, usize)> {
let pattern = b.get_message(key)?.value()?;
let fa = fluent_args(args);
let mut errors = Vec::new();
let s = b
.format_pattern(pattern, Some(&fa), &mut errors)
.into_owned();
Some((s, errors.len()))
}
pub fn tr(&self, key: &str) -> String {
self.tr_args(key, &[])
}
pub fn tr_args(&self, key: &str, args: &[(&str, Arg)]) -> String {
self.try_tr_args(key, args)
.map(|(s, _)| s)
.unwrap_or_else(|| key.to_string())
}
pub fn try_tr_args(&self, key: &str, args: &[(&str, Arg)]) -> Option<(String, usize)> {
Self::format(&self.current, key, args)
.or_else(|| Self::format(&self.fallback, key, args))
}
pub fn has(&self, key: &str) -> bool {
self.current.has_message(key)
}
pub fn override_text(&self, key: &str) -> Option<String> {
Self::format(&self.current, key, &[]).map(|(s, _)| s)
}
fn term(&self, key: &str, text: &str, texts: &[Catalog]) -> String {
if let Some(s) = self.override_text(key) {
return s;
}
if let Some(segs) = crate::text::find(texts, self.tag, key) {
return plain(segs);
}
if let Some(segs) = crate::compiler::diagnostic::lookup(self.tag, key) {
return plain(segs);
}
text.to_string()
}
pub fn diagnostic(&self, d: &Diagnostic) -> String {
if !d.key.is_empty() {
let key = format!("diag-{}", d.key);
if self.current.has_message(&key) {
let args: Vec<(&str, Arg)> = d
.args
.iter()
.map(|(n, v)| {
let a = match v {
DiagArg::Str(s) => Arg::Str(s.clone()),
DiagArg::Int(n) => Arg::Num(*n as f64),
DiagArg::Term { key, text, texts } => {
Arg::Str(self.term(key, text, texts))
}
};
(*n, a)
})
.collect();
if let Some((s, _)) = Self::format(&self.current, &key, &args) {
return s;
}
}
}
d.message_in_with(self.tag, &mut |k| self.override_text(k))
}
pub fn error<E: Localized + ?Sized>(&self, e: &E) -> String {
if self.current.has_message(e.text_key()) {
let mut args: Vec<(&str, Arg)> = Vec::new();
e.text_args(&mut |name, v| {
args.push((
name,
match v {
TextArg::Str(s) => Arg::Str(s.to_string()),
TextArg::Int(n) => Arg::Num(n as f64),
},
))
});
if let Some((s, _)) = Self::format(&self.current, e.text_key(), &args) {
return s;
}
}
crate::text::InLang(e, self.tag).to_string()
}
pub fn synth_text(&self, spec: &SynthSpec, key: &str) -> String {
self.override_text(key)
.unwrap_or_else(|| spec.text(key, self.tag).to_string())
}
pub fn io_error(&self, e: &std::io::Error) -> String {
let key = super::io_error_key(e);
match Self::format(&self.current, key, &[("detail", e.to_string().into())]) {
Some((s, _)) => s,
None => super::io_error(e, self.tag),
}
}
}
}