mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-26 04:27:49 +00:00
shell-w3: net change of 1 commits
- shell-w3: written from its sheet
This commit is contained in:
@@ -4,6 +4,8 @@
|
||||
|
||||
use std::collections::HashSet;
|
||||
|
||||
use crate::message::Template;
|
||||
|
||||
/// A row that passed, with its columns unescaped.
|
||||
pub(crate) struct Entry {
|
||||
pub context: String,
|
||||
@@ -52,6 +54,10 @@ pub(crate) fn parse_row(text: &str, forms: usize) -> Result<Entry, String> {
|
||||
match row.context.as_str() {
|
||||
"@id" => {}
|
||||
"@plural" => check_plural(&row.source, &row.translation, forms)?,
|
||||
"@msgplural" => {
|
||||
check_plural(&row.source, &row.translation, forms)?;
|
||||
row.source.split('|').try_for_each(check_matchable)?;
|
||||
}
|
||||
c if c.starts_with('@') && !RESERVED.contains(&c) => {
|
||||
return Err(format!("unknown reserved context {c:?}"));
|
||||
}
|
||||
@@ -62,11 +68,20 @@ pub(crate) fn parse_row(text: &str, forms: usize) -> Result<Entry, String> {
|
||||
if row.source.ends_with('…') != row.translation.ends_with('…') {
|
||||
return Err("trailing … differs from the source text".into());
|
||||
}
|
||||
if row.context == "@msg" {
|
||||
check_matchable(&row.source)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(row)
|
||||
}
|
||||
|
||||
/// A message is matched against its English text, so a template with no literal text or two
|
||||
/// placeholders in a row (where one ends and the next begins is unknowable) could never be used.
|
||||
fn check_matchable(english: &str) -> Result<(), String> {
|
||||
Template::parse(english, Vec::new(), false).map(|_| ()).ok_or_else(|| "unmatchable message template".to_string())
|
||||
}
|
||||
|
||||
fn check_plural(source: &str, translation: &str, forms: usize) -> Result<(), String> {
|
||||
let english: Vec<&str> = source.split('|').collect();
|
||||
let [one, other] = english.as_slice() else {
|
||||
|
||||
+173
-28
@@ -36,6 +36,7 @@ use negotiation::{bare, candidates, is_region, marked, plural_rules};
|
||||
|
||||
pub use bidi::{isolate, ltr, strip_isolates};
|
||||
pub use message::MessageMatch;
|
||||
use message::{KEPT_VALUE, MAX_MESSAGE_LEN, MESSAGE_DEPTH, Template, insert_template, sort_templates};
|
||||
|
||||
/// The CLDR number, plural and date data for every CLDR locale, from `data/generate.sh`.
|
||||
mod data {
|
||||
@@ -131,26 +132,76 @@ struct Locale {
|
||||
/// A locale's rows, app over shared, and what was wrong with the catalogs it came from.
|
||||
struct Parsed {
|
||||
rows: HashMap<String, HashMap<String, String>>,
|
||||
/// The `@msg` rows without placeholders: the English message, its `{{` and `}}` read as `{`
|
||||
/// and `}`, → its translation as written.
|
||||
exact: HashMap<String, String>,
|
||||
/// The `@msg` rows with placeholders and each English form of a `@msgplural` row, most
|
||||
/// specific first.
|
||||
templates: Vec<Template>,
|
||||
problems: Vec<String>,
|
||||
}
|
||||
|
||||
/// A message's matched catalog entry: the locale that holds it, the English template, its
|
||||
/// translation forms and the values captured from the message.
|
||||
struct Found<'a> {
|
||||
locale: &'a Locale,
|
||||
english: &'a str,
|
||||
forms: &'a [String],
|
||||
captures: Vec<(&'a str, &'a str)>,
|
||||
}
|
||||
|
||||
/// The index of `category` among a locale's plural `categories`. A category whole numbers up to
|
||||
/// 1000 never reach has no form of its own: Russian and Ukrainian decimals (`other`) take the `few`
|
||||
/// form (`1,5 файла`); any other (French `many` for a million) takes the last.
|
||||
fn plural_index(categories: &[PluralCategory], category: PluralCategory) -> usize {
|
||||
categories
|
||||
.iter()
|
||||
.position(|c| *c == category)
|
||||
.or_else(|| categories.iter().position(|c| *c == PluralCategory::Few))
|
||||
.unwrap_or(categories.len().saturating_sub(1))
|
||||
}
|
||||
|
||||
impl Locale {
|
||||
/// The rows; the catalogs are parsed on the first call and any problems logged then.
|
||||
fn parsed(&self) -> &Parsed {
|
||||
self.parsed.get_or_init(|| {
|
||||
let mut problems = Vec::new();
|
||||
let mut rows: HashMap<String, HashMap<String, String>> = HashMap::new();
|
||||
let mut exact = HashMap::new();
|
||||
let mut templates = Vec::new();
|
||||
for (name, text) in [("common", &self.shared), ("app", &self.app)] {
|
||||
let (entries, errors) = catalog::parse(text, self.forms);
|
||||
problems.extend(errors.into_iter().map(|e| format!("{}/{name}: {e}", self.code)));
|
||||
for e in entries {
|
||||
match e.context.as_str() {
|
||||
"@msg" => {
|
||||
if let Some(template) = Template::parse(&e.source, vec![e.translation.clone()], false) {
|
||||
match template.exact_key() {
|
||||
Some(key) => {
|
||||
exact.insert(key, e.translation.clone());
|
||||
}
|
||||
None => insert_template(&mut templates, template),
|
||||
}
|
||||
}
|
||||
}
|
||||
"@msgplural" => {
|
||||
let forms: Vec<String> = e.translation.split('|').map(str::to_string).collect();
|
||||
for english in e.source.split('|') {
|
||||
if let Some(template) = Template::parse(english, forms.clone(), true) {
|
||||
insert_template(&mut templates, template);
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
rows.entry(e.context).or_default().insert(e.source, e.translation);
|
||||
}
|
||||
}
|
||||
sort_templates(&mut templates);
|
||||
for p in &problems {
|
||||
log::warn!("translation catalog: {p}; row skipped");
|
||||
}
|
||||
Parsed { rows, problems }
|
||||
Parsed { rows, exact, templates, problems }
|
||||
})
|
||||
}
|
||||
|
||||
@@ -302,30 +353,116 @@ impl I18n {
|
||||
}
|
||||
|
||||
/// Translates a filled-in English message. An exact `@msg` row wins; otherwise the first matching
|
||||
/// template, by the order of the contract's template ranking, with the plural form from `{n}`.
|
||||
/// template: those that start with text before those that start with a placeholder, then the
|
||||
/// longest text before the first placeholder, then the most literal text. The plural form comes
|
||||
/// from `{n}`. Captured values are translated in turn to a depth of 5; a value between quotes
|
||||
/// at its own place stays, a value that starts with `{` is translated only by an exact row, and
|
||||
/// one that starts with `[` only by a template that starts with `[` and an index of digits.
|
||||
/// Messages over 2000 bytes are matched by an exact row only. Looks along the locale chain; a
|
||||
/// message with no match is returned as it is.
|
||||
pub fn message(&self, lang: Lang, s: &str) -> String {
|
||||
let _ = (lang, s);
|
||||
todo!("sh.K15")
|
||||
self.message_with(lang, s, &|_, _, _| None)
|
||||
}
|
||||
|
||||
/// As [`I18n::message`], with an app hook that sees each captured value (`key`, `value`) before
|
||||
/// the default rule.
|
||||
/// As [`I18n::message`], with an app hook that sees each captured value (`key`, `value`) that
|
||||
/// is not between quotes at its own place in the message, at every depth, before the default
|
||||
/// rule. `Some(text)` replaces the value's translation.
|
||||
pub fn message_with(&self, lang: Lang, s: &str, values: &dyn Fn(&MessageMatch<'_>, &str, &str) -> Option<String>) -> String {
|
||||
let _ = (lang, s, values);
|
||||
todo!("sh.K16")
|
||||
if lang == Lang::PSEUDO {
|
||||
return self.mark(s).to_string();
|
||||
}
|
||||
self.message_at(lang, s, false, MESSAGE_DEPTH, values)
|
||||
}
|
||||
|
||||
/// The exact `@msg` row for a filled-in English message, or `None` when the catalog has no such row.
|
||||
/// The exact `@msg` row for a filled-in English message, its `{{` and `}}` shown as `{` and `}`,
|
||||
/// or `None` when the catalog has no such row. Templates are not tried.
|
||||
pub fn message_exact(&self, lang: Lang, s: &str) -> Option<String> {
|
||||
let _ = (lang, s);
|
||||
todo!("sh.K16")
|
||||
let chain = self.locale(lang)?.chain.as_slice();
|
||||
let translation = chain.iter().find_map(|&i| self.locales.get(i)?.parsed().exact.get(s))?;
|
||||
Some(fill(translation, &[], false, true))
|
||||
}
|
||||
|
||||
/// Translates a message around a kept span (placeholder U+FFFC). The message is shown in English
|
||||
/// when the placeholder does not appear exactly once.
|
||||
/// Translates a message around a kept span (placeholder U+FFFC): `before` and `after` as
|
||||
/// [`I18n::message`] translates a message, `kept` (such as text a script threw) shown as it is,
|
||||
/// even when it reads like a message that has a translation. The message is shown in English
|
||||
/// when `before` or `after` already holds the placeholder, or the translation does not hold it
|
||||
/// exactly once.
|
||||
pub fn message_keeping(&self, lang: Lang, before: &str, kept: &str, after: &str) -> String {
|
||||
let _ = (lang, before, kept, after);
|
||||
todo!("sh.K18")
|
||||
let english = || format!("{before}{kept}{after}");
|
||||
if before.contains(KEPT_VALUE) || after.contains(KEPT_VALUE) {
|
||||
return english();
|
||||
}
|
||||
let shown = self.message(lang, &format!("{before}{KEPT_VALUE}{after}"));
|
||||
match shown.split_once(KEPT_VALUE) {
|
||||
Some((head, tail)) if !tail.contains(KEPT_VALUE) => format!("{head}{kept}{tail}"),
|
||||
_ => english(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The exact row or the first template `s` is an instance of, along `lang`'s chain. With
|
||||
/// `indexed`, only a template that starts with `[` and an index of digits.
|
||||
fn find_message<'a>(&'a self, lang: Lang, s: &'a str, indexed: bool) -> Option<Found<'a>> {
|
||||
let chain = self.locale(lang)?.chain.as_slice();
|
||||
chain.iter().find_map(|&i| {
|
||||
let locale = self.locales.get(i)?;
|
||||
let parsed = locale.parsed();
|
||||
if let Some(translation) = parsed.exact.get(s) {
|
||||
return Some(Found { locale, english: s, forms: std::slice::from_ref(translation), captures: Vec::new() });
|
||||
}
|
||||
if s.len() > MAX_MESSAGE_LEN {
|
||||
return None;
|
||||
}
|
||||
parsed.templates.iter().find_map(|t| {
|
||||
let captures = if indexed { t.indexed_captures(s)? } else { t.captures(s)? };
|
||||
Some(Found { locale, english: &t.english, forms: &t.forms, captures })
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/// `s` shown through the catalog entry it matches, its placeholder values translated in turn
|
||||
/// while `depth` lasts.
|
||||
fn message_at(
|
||||
&self,
|
||||
lang: Lang,
|
||||
s: &str,
|
||||
indexed: bool,
|
||||
depth: usize,
|
||||
values: &dyn Fn(&MessageMatch<'_>, &str, &str) -> Option<String>,
|
||||
) -> String {
|
||||
let Some(Found { locale, english, forms, captures }) = self.find_message(lang, s, indexed) else { return s.to_string() };
|
||||
let last = forms.len().saturating_sub(1);
|
||||
let count = captures.iter().find(|(k, _)| *k == "n").and_then(|(_, v)| v.parse::<u64>().ok());
|
||||
let index = match (count, &locale.plural) {
|
||||
(Some(n), Some((rules, categories))) => plural_index(categories, rules.category_for(PluralOperands::from(n))).min(last),
|
||||
_ => last,
|
||||
};
|
||||
let Some(template) = forms.get(index) else { return s.to_string() };
|
||||
// A value is quoted when quotes surround it at its own place in `s`. The same text quoted at
|
||||
// another place in `s` (a property named like the reason given for it) does not count.
|
||||
let quoted = |v: &str| {
|
||||
let at = (v.as_ptr() as usize).checked_sub(s.as_ptr() as usize);
|
||||
let Some((before, after)) = at.and_then(|at| Some((s.get(..at)?, s.get(at + v.len()..)?))) else { return false };
|
||||
[('"', '"'), ('“', '”'), ('\'', '\''), ('`', '`')].iter().any(|(a, b)| before.ends_with(*a) && after.starts_with(*b))
|
||||
};
|
||||
let matched = MessageMatch { english, captures: &captures };
|
||||
let nested = |v: &str| {
|
||||
if depth <= 1 || v.is_empty() {
|
||||
v.to_string()
|
||||
} else if v.starts_with('{') {
|
||||
self.message_exact(lang, v).unwrap_or_else(|| v.to_string())
|
||||
} else {
|
||||
self.message_at(lang, v, v.starts_with('['), depth - 1, values)
|
||||
}
|
||||
};
|
||||
let shown: Vec<(&str, String)> = captures
|
||||
.iter()
|
||||
.map(|&(k, v)| {
|
||||
let text = if quoted(v) { v.to_string() } else { values(&matched, k, v).unwrap_or_else(|| nested(v)) };
|
||||
(k, text)
|
||||
})
|
||||
.collect();
|
||||
let args: Vec<(&str, &str)> = shown.iter().map(|(k, v)| (*k, v.as_str())).collect();
|
||||
fill(template, &args, false, true)
|
||||
}
|
||||
|
||||
/// A count's wording in `lang`, `{n}` filled in as [`I18n::format`] writes numbers: grouped and
|
||||
@@ -367,15 +504,7 @@ impl I18n {
|
||||
let forms = locale.parsed().rows.get("@plural")?.get(&key)?;
|
||||
let (rules, categories) = locale.plural.as_ref()?;
|
||||
let category = operands.map_or(PluralCategory::Other, |o| rules.category_for(o));
|
||||
// A category whole numbers up to 1000 never reach has no form of its own. Russian
|
||||
// and Ukrainian decimals (`other`) take the `few` form (`1,5 файла`); any other
|
||||
// (French `many` for a million) takes the last.
|
||||
let index = categories
|
||||
.iter()
|
||||
.position(|c| *c == category)
|
||||
.or_else(|| categories.iter().position(|c| *c == PluralCategory::Few))
|
||||
.unwrap_or(categories.len().saturating_sub(1));
|
||||
forms.split('|').nth(index)
|
||||
forms.split('|').nth(plural_index(categories, category))
|
||||
})
|
||||
.unwrap_or(if english_one { one } else { other });
|
||||
let text = fmt(text, &[("n", <r(n))]);
|
||||
@@ -500,21 +629,35 @@ impl I18n {
|
||||
/// Other text gets no marks, and a value's own isolate is taken off. Unknown placeholders stay as written,
|
||||
/// and inserted values are never read as templates, so a file name containing `{n}` stays intact.
|
||||
pub fn fmt(template: &str, args: &[(&str, &str)]) -> String {
|
||||
fill(template, args, true)
|
||||
fill(template, args, true, false)
|
||||
}
|
||||
|
||||
/// [`fmt`] without isolates, for text that goes where the marks would get in the way: file
|
||||
/// names, logs, terminals, text compared or parsed later. Every isolate mark is taken off, in
|
||||
/// the template and in the values.
|
||||
pub fn fmt_plain(template: &str, args: &[(&str, &str)]) -> String {
|
||||
strip_isolates(&fill(template, args, false))
|
||||
strip_isolates(&fill(template, args, false, false))
|
||||
}
|
||||
|
||||
fn fill(template: &str, args: &[(&str, &str)], isolated: bool) -> String {
|
||||
/// The one filler behind [`fmt`], [`fmt_plain`] and message translation. With `escapes`, `{{` and
|
||||
/// `}}` are a literal `{` and `}`, as in a message template; without, braces are only placeholders.
|
||||
fn fill(template: &str, args: &[(&str, &str)], isolated: bool, escapes: bool) -> String {
|
||||
let mut pieces: Vec<(&str, bool)> = Vec::new();
|
||||
let mut rest = template;
|
||||
while let Some((before, after_open)) = rest.split_once('{') {
|
||||
while let Some(open) = rest.find(|c: char| c == '{' || (escapes && c == '}')) {
|
||||
let (before, tail) = rest.split_at_checked(open).unwrap_or((rest, ""));
|
||||
pieces.push((before, false));
|
||||
let after_open = tail.get(1..).unwrap_or("");
|
||||
if tail.starts_with('}') {
|
||||
pieces.push(("}", false));
|
||||
rest = after_open.strip_prefix('}').unwrap_or(after_open);
|
||||
continue;
|
||||
}
|
||||
if escapes && let Some(escaped) = after_open.strip_prefix('{') {
|
||||
pieces.push(("{", false));
|
||||
rest = escaped;
|
||||
continue;
|
||||
}
|
||||
let Some((name, after_close)) = after_open.split_once('}') else {
|
||||
pieces.push(("{", false));
|
||||
rest = after_open;
|
||||
@@ -545,5 +688,7 @@ fn fill(template: &str, args: &[(&str, &str)], isolated: bool) -> String {
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod message_tests;
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
@@ -1,5 +1,18 @@
|
||||
//! Matching a filled-in English message against `@msg` and `@msgplural` templates.
|
||||
|
||||
use std::cmp::Reverse;
|
||||
|
||||
/// How deep placeholder values that are messages themselves are translated. The status bar's line
|
||||
/// for an EPS file that can't be opened has five levels: the open error, the loader's error, the
|
||||
/// reader's error, the PostScript error and its meaning.
|
||||
pub(crate) const MESSAGE_DEPTH: usize = 5;
|
||||
|
||||
/// Messages longer than this are shown as they are (template matching backtracks).
|
||||
pub(crate) const MAX_MESSAGE_LEN: usize = 2000;
|
||||
|
||||
/// Stands in for the value `message_keeping` shows as it is while the text around it is translated.
|
||||
pub(crate) const KEPT_VALUE: char = '\u{FFFC}';
|
||||
|
||||
/// What a [`crate::I18n::message_with`] hook sees of the matched template.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct MessageMatch<'a> {
|
||||
@@ -8,3 +21,166 @@ pub struct MessageMatch<'a> {
|
||||
/// The captured values, as (key, value) pairs.
|
||||
pub captures: &'a [(&'a str, &'a str)],
|
||||
}
|
||||
|
||||
/// A piece of a message template: literal text or a `{name}` placeholder.
|
||||
#[derive(Debug)]
|
||||
pub(crate) enum Piece {
|
||||
Text(String),
|
||||
Hole(String),
|
||||
}
|
||||
|
||||
/// A message template (`Couldn't open {name}: {e}`) and its translation: one form for `@msg`, the
|
||||
/// plural forms for `@msgplural`.
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct Template {
|
||||
pieces: Vec<Piece>,
|
||||
/// Bytes of literal text: a template with more of it is the more specific match.
|
||||
literal: usize,
|
||||
/// The English text the template was parsed from.
|
||||
pub english: String,
|
||||
pub forms: Vec<String>,
|
||||
/// A `@msgplural` form: its `{n}` matches only a count.
|
||||
counted: bool,
|
||||
}
|
||||
|
||||
impl Template {
|
||||
/// `None` for a template that can't be matched reliably: no literal text, or two placeholders
|
||||
/// in a row. `{{` and `}}` are a literal `{` and `}`, as in a Rust format string, and so is a
|
||||
/// `{` with no `}` after it.
|
||||
pub fn parse(source: &str, forms: Vec<String>, counted: bool) -> Option<Template> {
|
||||
let mut pieces = Vec::new();
|
||||
let mut text = String::new();
|
||||
let mut rest = source;
|
||||
while let Some(a) = rest.find(['{', '}']) {
|
||||
text.push_str(rest.get(..a)?);
|
||||
let after = rest.get(a + 1..)?;
|
||||
let brace = if rest.get(a..)?.starts_with('{') { '{' } else { '}' };
|
||||
if let Some(escaped) = after.strip_prefix(brace) {
|
||||
text.push(brace);
|
||||
rest = escaped;
|
||||
continue;
|
||||
}
|
||||
if brace == '}' {
|
||||
text.push('}');
|
||||
rest = after;
|
||||
continue;
|
||||
}
|
||||
let Some(b) = after.find('}') else {
|
||||
text.push('{');
|
||||
rest = after;
|
||||
continue;
|
||||
};
|
||||
if !text.is_empty() {
|
||||
pieces.push(Piece::Text(std::mem::take(&mut text)));
|
||||
} else if matches!(pieces.last(), Some(Piece::Hole(_))) {
|
||||
return None;
|
||||
}
|
||||
pieces.push(Piece::Hole(after.get(..b)?.to_string()));
|
||||
rest = after.get(b + 1..)?;
|
||||
}
|
||||
text.push_str(rest);
|
||||
if !text.is_empty() {
|
||||
pieces.push(Piece::Text(text));
|
||||
}
|
||||
let literal = pieces.iter().map(|p| if let Piece::Text(t) = p { t.len() } else { 0 }).sum();
|
||||
(literal > 0).then_some(Template { pieces, literal, english: source.to_string(), forms, counted })
|
||||
}
|
||||
|
||||
/// The message text a template without placeholders stands for (`{{` read as `{`): such a row
|
||||
/// is an exact one.
|
||||
pub fn exact_key(&self) -> Option<String> {
|
||||
match self.pieces.as_slice() {
|
||||
[Piece::Text(text)] => Some(text.clone()),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The placeholder values if `s` is an instance of this template.
|
||||
pub fn captures<'a>(&'a self, s: &'a str) -> Option<Vec<(&'a str, &'a str)>> {
|
||||
let mut out = Vec::new();
|
||||
match_pieces(&self.pieces, s, self.counted, &mut out, None).then_some(out)
|
||||
}
|
||||
|
||||
/// [`Template::captures`] for a template that starts with a literal `[` and a placeholder
|
||||
/// whose value is an index of ASCII digits, such as ``[{j}] `{_1}`: {why}``. A JSON array such
|
||||
/// as ``["] `x`: b"]`` fits that template's text, but not its index.
|
||||
pub fn indexed_captures<'a>(&'a self, s: &'a str) -> Option<Vec<(&'a str, &'a str)>> {
|
||||
let [Piece::Text(open), Piece::Hole(index), ..] = self.pieces.as_slice() else { return None };
|
||||
if open != "[" {
|
||||
return None;
|
||||
}
|
||||
let captures = self.captures(s)?;
|
||||
captures.iter().any(|(k, v)| *k == index.as_str() && v.bytes().all(|b| b.is_ascii_digit())).then_some(captures)
|
||||
}
|
||||
}
|
||||
|
||||
/// Add `template` to `templates`, replacing an earlier one with the same English text (an app row
|
||||
/// over a shared one).
|
||||
pub(crate) fn insert_template(templates: &mut Vec<Template>, template: Template) {
|
||||
templates.retain(|t| !(t.english == template.english && t.counted == template.counted));
|
||||
templates.push(template);
|
||||
}
|
||||
|
||||
/// Order templates most specific first: those that start with text before those that start with a
|
||||
/// placeholder, so `plug-in manifest: {0}` wins over `{_1} is {_2} bytes` for a message it wraps;
|
||||
/// then the longest text before the first placeholder; then the most literal text, so
|
||||
/// `Couldn't open {name}: {e}` wins over `{path}: {e}`. The sort is stable: ties keep catalog order.
|
||||
pub(crate) fn sort_templates(templates: &mut [Template]) {
|
||||
templates.sort_by_key(|t| {
|
||||
let lead = if let Some(Piece::Text(text)) = t.pieces.first() { text.len() } else { 0 };
|
||||
(matches!(t.pieces.first(), Some(Piece::Hole(_))), Reverse(lead), Reverse(t.literal))
|
||||
});
|
||||
}
|
||||
|
||||
/// Match `s` against `pieces`, a placeholder taking the shortest non-empty text that lets the rest
|
||||
/// match (the last one takes what remains). A placeholder between two of the same quote (`'{key}'`,
|
||||
/// `"{key}"` or `` `{key}` ``) may also take no text, as for a property named by the empty string.
|
||||
/// With `counted`, `{n}` takes only a count. A placeholder that occurs twice takes the same text
|
||||
/// both times. `before` is the last character of the text piece before `pieces`.
|
||||
fn match_pieces<'p, 'a>(pieces: &'p [Piece], s: &'a str, counted: bool, out: &mut Vec<(&'p str, &'a str)>, before: Option<char>) -> bool {
|
||||
let Some((first, rest)) = pieces.split_first() else { return s.is_empty() };
|
||||
match first {
|
||||
Piece::Text(t) => s.strip_prefix(t.as_str()).is_some_and(|tail| match_pieces(rest, tail, counted, out, t.chars().last())),
|
||||
Piece::Hole(name) => {
|
||||
let earlier = out.iter().find(|(n, _)| *n == name.as_str()).map(|&(_, v)| v);
|
||||
let fits = |value: &str| (!(counted && name == "n") || value.parse::<u64>().is_ok()) && earlier.is_none_or(|e| e == value);
|
||||
let Some((next, after)) = rest.split_first() else {
|
||||
if s.is_empty() || !fits(s) {
|
||||
return false;
|
||||
}
|
||||
out.push((name.as_str(), s));
|
||||
return true;
|
||||
};
|
||||
let Piece::Text(next) = next else { return false };
|
||||
let quoted = before.is_some_and(|q| matches!(q, '\'' | '"' | '`') && next.starts_with(q));
|
||||
if quoted
|
||||
&& fits("")
|
||||
&& let Some(tail) = s.strip_prefix(next.as_str())
|
||||
{
|
||||
let mark = out.len();
|
||||
out.push((name.as_str(), ""));
|
||||
if match_pieces(after, tail, counted, out, next.chars().last()) {
|
||||
return true;
|
||||
}
|
||||
out.truncate(mark);
|
||||
}
|
||||
// Every other place the next literal occurs, nearest first.
|
||||
let mut from = s.chars().next().map_or(1, char::len_utf8);
|
||||
while let Some(at) = s.get(from..).and_then(|tail| tail.find(next.as_str())).map(|i| i + from) {
|
||||
let (Some(value), Some(tail)) = (s.get(..at), s.get(at + next.len()..)) else { return false };
|
||||
if !fits(value) {
|
||||
from = at + next.chars().next().map_or(1, char::len_utf8);
|
||||
continue;
|
||||
}
|
||||
let mark = out.len();
|
||||
out.push((name.as_str(), value));
|
||||
if match_pieces(after, tail, counted, out, next.chars().last()) {
|
||||
return true;
|
||||
}
|
||||
out.truncate(mark);
|
||||
from = at + next.chars().next().map_or(1, char::len_utf8);
|
||||
}
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
//! Message templates: which row a filled-in message matches, and how its values are translated.
|
||||
|
||||
use crate::{I18n, Lang, MessageMatch};
|
||||
|
||||
/// A German catalog of `(context, source, translation)` rows, and German.
|
||||
fn german(rows: &[(&str, &str, &str)]) -> (I18n, Lang) {
|
||||
let text = rows.iter().map(|(c, s, t)| format!("{c}\t{s}\t{t}")).collect::<Vec<_>>().join("\n");
|
||||
let (i18n, problems) = I18n::from_owned([("de".to_string(), String::new(), text)], &["de"]);
|
||||
assert!(problems.is_empty(), "{problems:?}");
|
||||
let lang = i18n.languages()[1];
|
||||
(i18n, lang)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_filled_message_matches_its_template_and_takes_its_plural_form() {
|
||||
let (i18n, de) = german(&[("@msg", "Open {name}", "Öffne {name}"), ("@msg", "Open a.eps", "Exakt")]);
|
||||
assert_eq!(i18n.message(de, "Open a.eps"), "Exakt");
|
||||
assert_eq!(i18n.message(de, "Open b.eps"), "Öffne b.eps");
|
||||
|
||||
// The template with leading text wins over one that starts with a hole, whatever the file order.
|
||||
let (i18n, de) = german(&[("@msg", "{path}: {e}", "{e} ← {path}"), ("@msg", "Open {name}: {e}", "Öffne {name}: {e}")]);
|
||||
assert_eq!(i18n.message(de, "Open a: b"), "Öffne a: b");
|
||||
|
||||
let (i18n, de) = german(&[("@msg", "a{x}", "kurz {x}"), ("@msg", "ab{x}", "lang {x}")]);
|
||||
assert_eq!(i18n.message(de, "abc"), "lang c");
|
||||
|
||||
let (i18n, de) = german(&[("@msg", "{x} of {y}", "zwei {x} {y}"), ("@msg", "{x} of {y} files", "drei {x} {y}")]);
|
||||
assert_eq!(i18n.message(de, "1 of 2 files"), "drei 1 2");
|
||||
|
||||
let (i18n, de) = german(&[("@msgplural", "{n} file|{n} files", "{n} Datei|{n} Dateien")]);
|
||||
assert_eq!(i18n.message(de, "1 file"), "1 Datei");
|
||||
assert_eq!(i18n.message(de, "3 files"), "3 Dateien");
|
||||
assert_eq!(i18n.message(de, "x files"), "x files", "{{n}} matches only a count");
|
||||
|
||||
// Rows the matcher cannot use are reported and the message shows in English.
|
||||
let (i18n, de) = german(&[("@msg", "{a}{b}", "{a}{b}"), ("@msgplural", "{n} cat|{n} cats", "{n} Katze")]);
|
||||
let problems = i18n.check_all();
|
||||
assert!(problems.iter().any(|p| p.contains("unmatchable message template")), "{problems:?}");
|
||||
assert!(problems.iter().any(|p| p.contains("plural forms")), "{problems:?}");
|
||||
assert_eq!(i18n.message(de, "xy"), "xy");
|
||||
assert_eq!(i18n.message(de, "2 cats"), "2 cats");
|
||||
|
||||
let (i18n, _) = german(&[("@msgplural", "{n} file|{n} files", "{n} Datei|{n} Dateien")]);
|
||||
assert_eq!(i18n.message(Lang::EN, "1 file"), "1 file");
|
||||
assert_eq!(i18n.message(Lang::PSEUDO, "1 file"), i18n.t(Lang::PSEUDO, "1 file"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn placeholder_values_translate_to_a_bounded_depth_and_quoted_ones_stay() {
|
||||
let chain: Vec<(&str, String, String)> = (1..=6).map(|i| ("@msg", format!("w{i} {{x}}"), format!("V{i} {{x}}"))).collect();
|
||||
let rows: Vec<(&str, &str, &str)> = chain.iter().map(|(c, s, t)| (*c, s.as_str(), t.as_str())).collect();
|
||||
let (i18n, de) = german(&rows);
|
||||
assert_eq!(i18n.message(de, "w1 w2 w3 w4 w5 w6 end"), "V1 V2 V3 V4 V5 w6 end");
|
||||
|
||||
let (i18n, de) = german(&[
|
||||
("@msg", "Reply: {r}", "Antwort: {r}"),
|
||||
("@msg", "Failed '{why}'", "Fehler '{why}'"),
|
||||
("@msg", "disk full", "Datenträger voll"),
|
||||
("@msg", "{{\"a\": 1}}", "{{\"a\": 1}} (de)"),
|
||||
("@msg", "[{i}] {why}", "[{i}] Grund: {why}"),
|
||||
]);
|
||||
assert_eq!(i18n.message(de, "Reply: disk full"), "Antwort: Datenträger voll");
|
||||
assert_eq!(i18n.message(de, "Failed 'disk full'"), "Fehler 'disk full'");
|
||||
assert_eq!(i18n.message(de, "Reply: {\"a\": 1}"), "Antwort: {\"a\": 1} (de)");
|
||||
assert_eq!(i18n.message(de, "Reply: {\"b\": 2}"), "Antwort: {\"b\": 2}");
|
||||
assert_eq!(i18n.message(de, "Reply: [0] bad"), "Antwort: [0] Grund: bad");
|
||||
assert_eq!(i18n.message(de, "Reply: [x] bad"), "Antwort: [x] bad");
|
||||
assert_eq!(i18n.message(de, "Reply: see {who}"), "Antwort: see {who}");
|
||||
|
||||
let upper = |m: &MessageMatch<'_>, key: &str, value: &str| (m.english == "Reply: {r}" && key == "r").then(|| value.to_uppercase());
|
||||
assert_eq!(i18n.message_with(de, "Reply: x", &upper), "Antwort: X");
|
||||
let always = |_: &MessageMatch<'_>, _: &str, _: &str| Some("HOOK".to_string());
|
||||
assert_eq!(i18n.message_with(de, "Failed 'disk full'", &always), "Fehler 'disk full'");
|
||||
|
||||
let long = format!("Reply: {}", "a".repeat(2001));
|
||||
assert_eq!(i18n.message(de, &long), long);
|
||||
|
||||
assert_eq!(i18n.message_keeping(de, "Reply: ", "x", ""), "Antwort: x");
|
||||
assert_eq!(i18n.message_keeping(de, "Reply: \u{FFFC}", "x", ""), "Reply: \u{FFFC}x");
|
||||
let (i18n, de) = german(&[("@msg", "A \u{FFFC}", "B")]);
|
||||
assert_eq!(i18n.message_keeping(de, "A ", "kept", ""), "A kept");
|
||||
}
|
||||
Reference in New Issue
Block a user