Skip to main content

yomi_core/
texts.rs

1//! Text tables that replace bodies (localization; `spec/host/05-texts.md`).
2//!
3//! A text table maps, per language, keys (`module.label#id`; for identity display names, `identity:module.name`) to
4//! translations. A translation is a body in the same form as the original, and can use body escapes (section 1.10 of
5//! `spec/language/01-lexical.md`) and `${n}`, which refers to the `n`-th `${expr}` of the original. Translations are
6//! parsed when put into the table (so that the positions of `${n}` can be looked up right away).
7//!
8//! Errors are held only as codes and arguments (no message text).
9
10use std::collections::BTreeMap;
11
12use crate::diag::Severity;
13use crate::program::{Program, StopKind, TextArg, TextPart};
14use crate::value::{Identity, Value};
15
16/// The kind of text table error.
17#[non_exhaustive]
18#[derive(Debug, Clone, PartialEq, Eq)]
19pub enum TextErrorKind {
20    /// An escape that cannot be used (in a translation). Argument `found` (`\` and the next character).
21    InvalidEscape {
22        /// The spelling found.
23        found: String,
24    },
25    /// A `${…}` that is not in the form `${n}` (`n` is an integer of 1 or more), or an unclosed `${` (in a translation).
26    /// Argument `found`.
27    InvalidPlaceholder {
28        /// The spelling found.
29        found: String,
30    },
31    /// A line of the table file has no TAB separating the key and the translation.
32    MissingTab,
33    /// The key of a line of the table file is empty.
34    EmptyKey,
35    /// The same key appears twice in the table file.
36    DuplicateKey,
37    /// An unknown directive in the table file (an `@…` other than `@lang`). Argument `name`.
38    UnknownDirective {
39        /// The name of the directive (without `@`).
40        name: String,
41    },
42}
43
44impl TextErrorKind {
45    /// The stable English name.
46    pub fn code(&self) -> &'static str {
47        match self {
48            TextErrorKind::InvalidEscape { .. } => "invalid_escape",
49            TextErrorKind::InvalidPlaceholder { .. } => "invalid_placeholder",
50            TextErrorKind::MissingTab => "missing_tab",
51            TextErrorKind::EmptyKey => "empty_key",
52            TextErrorKind::DuplicateKey => "duplicate_key",
53            TextErrorKind::UnknownDirective { .. } => "unknown_directive",
54        }
55    }
56}
57
58/// An error in a translation that could not be put into the table, or in a line of the table file.
59#[non_exhaustive]
60#[derive(Debug, Clone, PartialEq, Eq)]
61pub struct TextError {
62    /// Kind.
63    pub kind: TextErrorKind,
64    /// The key of the translation with the error (when known).
65    pub key: Option<String>,
66    /// The line of the table file (1-based; only when reading a file).
67    pub line: Option<u32>,
68}
69
70impl std::fmt::Display for TextError {
71    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
72        write!(f, "{}", self.kind.code())?;
73        if let Some(k) = &self.key {
74            write!(f, " (key {k})")?;
75        }
76        if let Some(n) = self.line {
77            write!(f, " (line {n})")?;
78        }
79        Ok(())
80    }
81}
82
83impl std::error::Error for TextError {}
84
85/// The kind of result of checking a text table against the scripts ([`TextTable::check`]).
86#[non_exhaustive]
87#[derive(Debug, Clone, PartialEq, Eq)]
88pub enum TextIssueKind {
89    /// A missing translation. A key that is in the scripts but not in the table (warning).
90    Missing,
91    /// An extra translation. A key that is in the table but not in the scripts (warning).
92    Unused,
93    /// A number error. The `n` of `${n}` in a translation exceeds the number of `${expr}` in the original (error).
94    BadNumber {
95        /// The `n` of `${n}` in the translation (the largest among those that exceed).
96        number: u32,
97        /// The number of `${expr}` in the original.
98        count: u32,
99    },
100}
101
102impl TextIssueKind {
103    /// The stable English name.
104    pub fn code(&self) -> &'static str {
105        match self {
106            TextIssueKind::Missing => "missing",
107            TextIssueKind::Unused => "unused",
108            TextIssueKind::BadNumber { .. } => "bad_number",
109        }
110    }
111
112    /// Severity (missing and extra translations are warnings, number errors are errors).
113    pub fn severity(&self) -> Severity {
114        match self {
115            TextIssueKind::BadNumber { .. } => Severity::Error,
116            _ => Severity::Warning,
117        }
118    }
119}
120
121/// One result of checking a text table against the scripts.
122#[non_exhaustive]
123#[derive(Debug, Clone, PartialEq, Eq)]
124pub struct TextIssue {
125    /// Severity.
126    pub severity: Severity,
127    /// The key (`module.label#id`).
128    pub key: String,
129    /// Kind.
130    pub kind: TextIssueKind,
131}
132
133impl TextIssue {
134    /// Makes an issue for an item. The severity is decided by the kind.
135    fn new(key: &str, kind: TextIssueKind) -> Self {
136        Self {
137            severity: kind.severity(),
138            key: key.to_string(),
139            kind,
140        }
141    }
142}
143
144/// A parsed part of a translation.
145#[derive(Debug, Clone, PartialEq, Eq)]
146enum Part {
147    /// Characters (after unescaping).
148    Lit(String),
149    /// The value of the `n`-th (1-based) `${expr}` of the original.
150    Arg(u32),
151}
152
153/// One item of the translation table.
154#[derive(Debug, Clone, PartialEq, Eq)]
155struct Entry {
156    key: String,
157    /// The translation as written.
158    raw: String,
159    parts: Vec<Part>,
160    /// The largest `n` of `${n}` (0 if none).
161    max_arg: u32,
162}
163
164/// A per-language table that replaces bodies.
165///
166/// Keys are `module.label#id` (the same form as passed stop points). Values are bodies in the same form as the original.
167/// Pass it to the VM with [`Vm::set_texts`](crate::Vm::set_texts).
168#[derive(Debug, Clone, PartialEq, Eq)]
169pub struct TextTable {
170    language: String,
171    /// In insertion order.
172    entries: Vec<Entry>,
173    /// Key → index into `entries`.
174    index: BTreeMap<String, usize>,
175}
176
177impl TextTable {
178    /// Makes an empty table. `language` is the name of the language (such as `en`; the core gives it no meaning).
179    pub fn new(language: impl Into<String>) -> Self {
180        Self {
181            language: language.into(),
182            entries: Vec::new(),
183            index: BTreeMap::new(),
184        }
185    }
186
187    /// The name of the language.
188    pub fn language(&self) -> &str {
189        &self.language
190    }
191
192    /// Puts a translation. If the same key exists, replaces it.
193    ///
194    /// A translation is a body in the same form as the original. Body escapes (`\「` `\」` `\$` `\\` `\=` `\#`) can be used.
195    /// `${n}` (`n` is an integer of 1 or more) becomes the value of the `n`-th `${expr}` of the original. Any other `\`
196    /// combinations and `${…}` are errors (the table is unchanged). Whether `n` exceeds the count in the original is not
197    /// checked here, because the scripts are unknown ([`Vm::set_texts`](crate::Vm::set_texts) and [`TextTable::check`] check
198    /// it).
199    pub fn insert(
200        &mut self,
201        key: impl Into<String>,
202        value: impl Into<String>,
203    ) -> Result<(), TextError> {
204        let key = key.into();
205        let raw = value.into();
206        let parts = parse_value(&raw).map_err(|kind| TextError {
207            kind,
208            key: Some(key.clone()),
209            line: None,
210        })?;
211        let max_arg = parts
212            .iter()
213            .map(|p| match p {
214                Part::Arg(n) => *n,
215                Part::Lit(_) => 0,
216            })
217            .max()
218            .unwrap_or(0);
219        let entry = Entry {
220            key: key.clone(),
221            raw,
222            parts,
223            max_arg,
224        };
225        match self.index.get(&key) {
226            Some(&i) => self.entries[i] = entry,
227            None => {
228                self.index.insert(key, self.entries.len());
229                self.entries.push(entry);
230            }
231        }
232        Ok(())
233    }
234
235    /// The translation of a key (as written).
236    pub fn get(&self, key: &str) -> Option<&str> {
237        self.index.get(key).map(|&i| self.entries[i].raw.as_str())
238    }
239
240    /// The number of translations.
241    pub fn len(&self) -> usize {
242        self.entries.len()
243    }
244
245    /// Whether it is empty.
246    pub fn is_empty(&self) -> bool {
247        self.entries.is_empty()
248    }
249
250    /// Returns `(key, translation)` in insertion order.
251    pub fn iter(&self) -> impl Iterator<Item = (&str, &str)> {
252        self.entries
253            .iter()
254            .map(|e| (e.key.as_str(), e.raw.as_str()))
255    }
256
257    /// Checks against the scripts. Results are in script order (missing translations, number errors), followed by table order
258    /// (extra translations).
259    ///
260    /// - Missing translation (warning): a key of a body with a stable ID in the scripts that is not in the table.
261    /// - Extra translation (warning): a key in the table that is not in the scripts.
262    /// - Number error (error): the `n` of `${n}` exceeds the number of `${expr}` in the original.
263    pub fn check(&self, program: &Program) -> Vec<TextIssue> {
264        let mut out = Vec::new();
265        let script = program.text_entries();
266        for (key, parts) in &script {
267            match self.index.get(key) {
268                None => out.push(TextIssue::new(key, TextIssueKind::Missing)),
269                Some(&i) => {
270                    let count = interp_count(parts);
271                    let e = &self.entries[i];
272                    if e.max_arg > count {
273                        out.push(TextIssue::new(
274                            key,
275                            TextIssueKind::BadNumber {
276                                number: e.max_arg,
277                                count,
278                            },
279                        ));
280                    }
281                }
282            }
283        }
284        let known: std::collections::HashSet<&str> =
285            script.iter().map(|(k, _)| k.as_str()).collect();
286        for e in &self.entries {
287            if !known.contains(e.key.as_str()) {
288                out.push(TextIssue::new(&e.key, TextIssueKind::Unused));
289            }
290        }
291        out
292    }
293
294    /// Makes a table (a template) whose translations are the originals, for all bodies with stable IDs in the scripts.
295    /// `${expr}` becomes a numbered `${n}` (in the order written). Translators rewrite it into translations.
296    pub fn template(program: &Program, language: impl Into<String>) -> Self {
297        let mut table = Self::new(language);
298        for (key, parts) in program.text_entries() {
299            let mut value = String::new();
300            let mut n = 0;
301            for p in parts {
302                match p {
303                    TextPart::Lit(t) => escape_literal(t, &mut value),
304                    TextPart::Interp => {
305                        n += 1;
306                        value.push_str(&format!("${{{n}}}"));
307                    }
308                }
309            }
310            table
311                .insert(key, value)
312                .expect("原文から作った訳文は解析できる");
313        }
314        table
315    }
316
317    /// Reads a table from the text of a file (a line-oriented format for tools; section 5.7 of `spec/host/05-texts.md`).
318    ///
319    /// - Empty lines are skipped. Lines starting with `#` are comments.
320    /// - A line `@lang language` sets the language name (empty if absent).
321    /// - Other lines are `key` TAB `translation`. In translations, `\n` is a newline, `\t` a TAB and `\r` a carriage return.
322    ///   Other `\` sequences are translation escapes (such as `\\`).
323    /// - A key appearing twice, or a translation that is an error in [`TextTable::insert`], gives an error with the line.
324    pub fn from_file(source: &str) -> Result<Self, TextError> {
325        let source = source.strip_prefix('\u{feff}').unwrap_or(source);
326        let mut table = Self::new("");
327        for (i, line) in source.lines().enumerate() {
328            let no = (i + 1) as u32;
329            let fail = |kind, key: Option<String>| TextError {
330                kind,
331                key,
332                line: Some(no),
333            };
334            if line.is_empty() || line.starts_with('#') {
335                continue;
336            }
337            if let Some(rest) = line.strip_prefix('@') {
338                let (name, arg) = match rest.split_once([' ', '\t']) {
339                    Some((n, a)) => (n, a.trim()),
340                    None => (rest, ""),
341                };
342                if name != "lang" {
343                    return Err(fail(
344                        TextErrorKind::UnknownDirective {
345                            name: name.to_string(),
346                        },
347                        None,
348                    ));
349                }
350                table.language = arg.to_string();
351                continue;
352            }
353            let Some((key, value)) = line.split_once('\t') else {
354                return Err(fail(TextErrorKind::MissingTab, None));
355            };
356            if key.is_empty() {
357                return Err(fail(TextErrorKind::EmptyKey, None));
358            }
359            if table.index.contains_key(key) {
360                return Err(fail(TextErrorKind::DuplicateKey, Some(key.to_string())));
361            }
362            table
363                .insert(key, unescape_file(value))
364                .map_err(|e| TextError {
365                    line: Some(no),
366                    ..e
367                })?;
368        }
369        Ok(table)
370    }
371
372    /// Turns the table into the text of a file (it can be read back with [`TextTable::from_file`]).
373    pub fn to_file(&self) -> String {
374        let mut out = String::new();
375        if !self.language.is_empty() {
376            out.push_str("@lang ");
377            out.push_str(&self.language);
378            out.push('\n');
379        }
380        for e in &self.entries {
381            out.push_str(&e.key);
382            out.push('\t');
383            for c in e.raw.chars() {
384                match c {
385                    '\n' => out.push_str("\\n"),
386                    '\t' => out.push_str("\\t"),
387                    '\r' => out.push_str("\\r"),
388                    c => out.push(c),
389                }
390            }
391            out.push('\n');
392        }
393        out
394    }
395
396    /// Returns the translation of the key, filled with `values` (the values of `${expr}` of the original, from the first).
397    /// `None` if the key is missing.
398    pub(crate) fn render(&self, key: &str, values: &[String]) -> Option<String> {
399        let e = &self.entries[*self.index.get(key)?];
400        let mut out = String::new();
401        for p in &e.parts {
402            match p {
403                Part::Lit(t) => out.push_str(t),
404                Part::Arg(n) => {
405                    if let Some(v) = values.get(*n as usize - 1) {
406                        out.push_str(v);
407                    }
408                }
409            }
410        }
411        Some(out)
412    }
413
414    /// Checks only for number errors (errors) against the scripts ([`Vm::set_texts`](crate::Vm::set_texts)).
415    pub(crate) fn number_errors(&self, program: &Program) -> Vec<TextIssue> {
416        self.check(program)
417            .into_iter()
418            .filter(|i| matches!(i.kind, TextIssueKind::BadNumber { .. }))
419            .collect()
420    }
421}
422
423/// The number of `${expr}` in the original.
424fn interp_count(parts: &[TextPart]) -> u32 {
425    parts
426        .iter()
427        .filter(|p| matches!(p, TextPart::Interp))
428        .count() as u32
429}
430
431/// Turns characters of the original into translation notation (escapes `\` and a `$` before `{`).
432fn escape_literal(text: &str, out: &mut String) {
433    let mut chars = text.chars().peekable();
434    while let Some(c) = chars.next() {
435        match c {
436            '\\' => out.push_str("\\\\"),
437            '$' if chars.peek() == Some(&'{') => out.push_str("\\$"),
438            c => out.push(c),
439        }
440    }
441}
442
443/// Turns `\n`, `\t` and `\r` in translations in the file into a newline, TAB and carriage return. Other `\` and the next
444/// character are kept as is (`insert` reads them as translation escapes).
445fn unescape_file(value: &str) -> String {
446    let mut out = String::with_capacity(value.len());
447    let mut chars = value.chars();
448    while let Some(c) = chars.next() {
449        if c != '\\' {
450            out.push(c);
451            continue;
452        }
453        match chars.next() {
454            Some('n') => out.push('\n'),
455            Some('t') => out.push('\t'),
456            Some('r') => out.push('\r'),
457            Some(n) => {
458                out.push('\\');
459                out.push(n);
460            }
461            None => out.push('\\'),
462        }
463    }
464    out
465}
466
467/// Parses a translation.
468fn parse_value(value: &str) -> Result<Vec<Part>, TextErrorKind> {
469    let mut parts = Vec::new();
470    let mut text = String::new();
471    let mut rest = value;
472    while let Some(c) = rest.chars().next() {
473        match c {
474            '\\' => {
475                let after = &rest[1..];
476                match after.chars().next() {
477                    Some(n @ ('「' | '」' | '$' | '\\' | '=' | '#')) => {
478                        text.push(n);
479                        rest = &after[n.len_utf8()..];
480                    }
481                    Some(n) => {
482                        return Err(TextErrorKind::InvalidEscape {
483                            found: format!("\\{n}"),
484                        });
485                    }
486                    None => {
487                        return Err(TextErrorKind::InvalidEscape {
488                            found: "\\".to_string(),
489                        });
490                    }
491                }
492            }
493            '$' if rest[1..].starts_with('{') => {
494                let inner_all = &rest[2..];
495                let Some(close) = inner_all.find('}') else {
496                    return Err(TextErrorKind::InvalidPlaceholder {
497                        found: rest.to_string(),
498                    });
499                };
500                let inner = &inner_all[..close];
501                let n = (!inner.is_empty() && inner.bytes().all(|b| b.is_ascii_digit()))
502                    .then(|| inner.parse::<u32>().ok())
503                    .flatten()
504                    .filter(|&n| n >= 1);
505                let Some(n) = n else {
506                    return Err(TextErrorKind::InvalidPlaceholder {
507                        found: format!("${{{inner}}}"),
508                    });
509                };
510                if !text.is_empty() {
511                    parts.push(Part::Lit(std::mem::take(&mut text)));
512                }
513                parts.push(Part::Arg(n));
514                rest = &inner_all[close + 1..];
515            }
516            c => {
517                text.push(c);
518                rest = &rest[c.len_utf8()..];
519            }
520        }
521    }
522    if !text.is_empty() {
523        parts.push(Part::Lit(text));
524    }
525    Ok(parts)
526}
527
528/// Information about a stop point whose arguments are replaced ([`localize_args`]).
529pub(crate) struct StopCtx<'a> {
530    pub program: &'a Program,
531    pub kind: StopKind,
532    /// `module.label`.
533    pub label: &'a str,
534    /// `module.label#id` of a plain line, quote line or command (`None` if there is no ID).
535    pub key: Option<&'a str>,
536    /// The translatable arguments of the command.
537    pub text_arg: Option<TextArg>,
538}
539
540/// Replaces, among the arguments of a stop point, the bodies (plain lines, quote lines, option texts and translatable
541/// command arguments) and the display name of a quote line's identity with the translations of the text table. Without a
542/// table, without the key, or when the arguments do not have the expected shape, they stay as the original. `values` are
543/// the values of `${expr}` for each body.
544pub(crate) fn localize_args(
545    table: Option<&TextTable>,
546    ctx: &StopCtx<'_>,
547    args: &[Value],
548    values: &[Vec<String>],
549) -> Vec<Value> {
550    let mut out = args.to_vec();
551    let Some(table) = table else {
552        return out;
553    };
554    let label = ctx.label;
555    match ctx.kind {
556        StopKind::Plain | StopKind::Quote => {
557            let at = if ctx.kind == StopKind::Plain { 0 } else { 1 };
558            if let (Some(key), Some(Value::Str(_))) = (ctx.key, args.get(at))
559                && let Some(t) = table.render(key, values.first().map_or(&[], Vec::as_slice))
560            {
561                out[at] = Value::Str(t.into());
562            }
563            if ctx.kind == StopKind::Quote
564                && let Some(Value::Option(Some(who))) = args.first()
565                && let Value::Identity(who) = &**who
566                && let module = label.split_once('.').map_or("", |(m, _)| m)
567                && let Some(key) = ctx.program.identity_key_of(module, &who.id, &who.name)
568                && let Some(t) = table.render(&key, &[])
569            {
570                let new = Identity {
571                    id: who.id.clone(),
572                    name: t,
573                };
574                out[0] = Value::Option(Some(Box::new(Value::Identity(new.into()))));
575            }
576        }
577        StopKind::Choice => {
578            if let [Value::List(texts), Value::List(ids)] = args {
579                let mut new = texts.clone().into_vec();
580                for (i, id) in ids.iter().enumerate() {
581                    let (Some(slot), Value::Option(Some(id))) = (new.get_mut(i), id) else {
582                        continue;
583                    };
584                    let Value::Str(id) = &**id else { continue };
585                    let key = format!("{label}#{id}");
586                    if let Some(t) = table.render(&key, values.get(i).map_or(&[], Vec::as_slice)) {
587                        *slot = Value::Str(t.into());
588                    }
589                }
590                out[0] = Value::List(new.into());
591            }
592        }
593        StopKind::Command => {
594            if let (Some(ta), Some(key)) = (ctx.text_arg, ctx.key)
595                && let Some(Value::Str(_)) = args.get(ta.arg as usize)
596                && let Some(t) = table.render(
597                    key,
598                    values.get(ta.values as usize).map_or(&[], Vec::as_slice),
599                )
600            {
601                out[ta.arg as usize] = Value::Str(t.into());
602            }
603        }
604    }
605    out
606}