1use std::collections::BTreeMap;
11
12use crate::diag::Severity;
13use crate::program::{Program, StopKind, TextArg, TextPart};
14use crate::value::{Identity, Value};
15
16#[non_exhaustive]
18#[derive(Debug, Clone, PartialEq, Eq)]
19pub enum TextErrorKind {
20 InvalidEscape {
22 found: String,
24 },
25 InvalidPlaceholder {
28 found: String,
30 },
31 MissingTab,
33 EmptyKey,
35 DuplicateKey,
37 UnknownDirective {
39 name: String,
41 },
42}
43
44impl TextErrorKind {
45 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#[non_exhaustive]
60#[derive(Debug, Clone, PartialEq, Eq)]
61pub struct TextError {
62 pub kind: TextErrorKind,
64 pub key: Option<String>,
66 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#[non_exhaustive]
87#[derive(Debug, Clone, PartialEq, Eq)]
88pub enum TextIssueKind {
89 Missing,
91 Unused,
93 BadNumber {
95 number: u32,
97 count: u32,
99 },
100}
101
102impl TextIssueKind {
103 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 pub fn severity(&self) -> Severity {
114 match self {
115 TextIssueKind::BadNumber { .. } => Severity::Error,
116 _ => Severity::Warning,
117 }
118 }
119}
120
121#[non_exhaustive]
123#[derive(Debug, Clone, PartialEq, Eq)]
124pub struct TextIssue {
125 pub severity: Severity,
127 pub key: String,
129 pub kind: TextIssueKind,
131}
132
133impl TextIssue {
134 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#[derive(Debug, Clone, PartialEq, Eq)]
146enum Part {
147 Lit(String),
149 Arg(u32),
151}
152
153#[derive(Debug, Clone, PartialEq, Eq)]
155struct Entry {
156 key: String,
157 raw: String,
159 parts: Vec<Part>,
160 max_arg: u32,
162}
163
164#[derive(Debug, Clone, PartialEq, Eq)]
169pub struct TextTable {
170 language: String,
171 entries: Vec<Entry>,
173 index: BTreeMap<String, usize>,
175}
176
177impl TextTable {
178 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 pub fn language(&self) -> &str {
189 &self.language
190 }
191
192 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 pub fn get(&self, key: &str) -> Option<&str> {
237 self.index.get(key).map(|&i| self.entries[i].raw.as_str())
238 }
239
240 pub fn len(&self) -> usize {
242 self.entries.len()
243 }
244
245 pub fn is_empty(&self) -> bool {
247 self.entries.is_empty()
248 }
249
250 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 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 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 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 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 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 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
423fn interp_count(parts: &[TextPart]) -> u32 {
425 parts
426 .iter()
427 .filter(|p| matches!(p, TextPart::Interp))
428 .count() as u32
429}
430
431fn 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
443fn 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
467fn 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
528pub(crate) struct StopCtx<'a> {
530 pub program: &'a Program,
531 pub kind: StopKind,
532 pub label: &'a str,
534 pub key: Option<&'a str>,
536 pub text_arg: Option<TextArg>,
538}
539
540pub(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}