scirs2-text 0.4.3

Text processing module for SciRS2 (scirs2-text)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
//! Hepburn romanisation for Japanese hiragana and katakana.
//!
//! Implements the Modified Hepburn system (the most widely-used standard).
//! Yōon (combination sounds) are matched before single kana so that e.g.
//! "きゃ" maps to "kya" rather than "ki"+"ya".
//! Long vowel marks (ー) and small-tsu doubled consonants are handled
//! context-sensitively when `use_macron` is true.

use super::Transliterator;

// ── Yōon (combination sounds) hiragana ───────────────────────────────────────
// Must come BEFORE single-kana entries so longest-match wins.
static HIRAGANA_YOON: &[(&str, &str)] = &[
    ("きゃ", "kya"),
    ("きゅ", "kyu"),
    ("きょ", "kyo"),
    ("しゃ", "sha"),
    ("しゅ", "shu"),
    ("しょ", "sho"),
    ("ちゃ", "cha"),
    ("ちゅ", "chu"),
    ("ちょ", "cho"),
    ("にゃ", "nya"),
    ("にゅ", "nyu"),
    ("にょ", "nyo"),
    ("ひゃ", "hya"),
    ("ひゅ", "hyu"),
    ("ひょ", "hyo"),
    ("みゃ", "mya"),
    ("みゅ", "myu"),
    ("みょ", "myo"),
    ("りゃ", "rya"),
    ("りゅ", "ryu"),
    ("りょ", "ryo"),
    ("ぎゃ", "gya"),
    ("ぎゅ", "gyu"),
    ("ぎょ", "gyo"),
    ("じゃ", "ja"),
    ("じゅ", "ju"),
    ("じょ", "jo"),
    ("びゃ", "bya"),
    ("びゅ", "byu"),
    ("びょ", "byo"),
    ("ぴゃ", "pya"),
    ("ぴゅ", "pyu"),
    ("ぴょ", "pyo"),
    ("ちゃ", "cha"),
    ("ちゅ", "chu"),
    ("ちょ", "cho"),
    ("にゃ", "nya"),
    ("にゅ", "nyu"),
    ("にょ", "nyo"),
];

// ── Base hiragana ─────────────────────────────────────────────────────────────
static HIRAGANA_BASE: &[(&str, &str)] = &[
    ("", "a"),
    ("", "i"),
    ("", "u"),
    ("", "e"),
    ("", "o"),
    ("", "ka"),
    ("", "ki"),
    ("", "ku"),
    ("", "ke"),
    ("", "ko"),
    ("", "sa"),
    ("", "shi"),
    ("", "su"),
    ("", "se"),
    ("", "so"),
    ("", "ta"),
    ("", "chi"),
    ("", "tsu"),
    ("", "te"),
    ("", "to"),
    ("", "na"),
    ("", "ni"),
    ("", "nu"),
    ("", "ne"),
    ("", "no"),
    ("", "ha"),
    ("", "hi"),
    ("", "fu"),
    ("", "he"),
    ("", "ho"),
    ("", "ma"),
    ("", "mi"),
    ("", "mu"),
    ("", "me"),
    ("", "mo"),
    ("", "ya"),
    ("", "yu"),
    ("", "yo"),
    ("", "ra"),
    ("", "ri"),
    ("", "ru"),
    ("", "re"),
    ("", "ro"),
    ("", "wa"),
    ("", "i"),
    ("", "e"),
    ("", "wo"),
    ("", "n"),
    // Voiced (dakuten)
    ("", "ga"),
    ("", "gi"),
    ("", "gu"),
    ("", "ge"),
    ("", "go"),
    ("", "za"),
    ("", "ji"),
    ("", "zu"),
    ("", "ze"),
    ("", "zo"),
    ("", "da"),
    ("", "ji"),
    ("", "zu"),
    ("", "de"),
    ("", "do"),
    ("", "ba"),
    ("", "bi"),
    ("", "bu"),
    ("", "be"),
    ("", "bo"),
    // Semi-voiced (handakuten)
    ("", "pa"),
    ("", "pi"),
    ("", "pu"),
    ("", "pe"),
    ("", "po"),
    // Small vowels (treated as regular vowels in output)
    ("", "a"),
    ("", "i"),
    ("", "u"),
    ("", "e"),
    ("", "o"),
    // Small ya/yu/yo (appear after yōon combos are consumed)
    ("", "ya"),
    ("", "yu"),
    ("", "yo"),
    // Small wa
    ("", "wa"),
    // Special
    ("", "vu"),
];

// ── Yōon katakana ─────────────────────────────────────────────────────────────
static KATAKANA_YOON: &[(&str, &str)] = &[
    ("キャ", "kya"),
    ("キュ", "kyu"),
    ("キョ", "kyo"),
    ("シャ", "sha"),
    ("シュ", "shu"),
    ("ショ", "sho"),
    ("チャ", "cha"),
    ("チュ", "chu"),
    ("チョ", "cho"),
    ("ニャ", "nya"),
    ("ニュ", "nyu"),
    ("ニョ", "nyo"),
    ("ヒャ", "hya"),
    ("ヒュ", "hyu"),
    ("ヒョ", "hyo"),
    ("ミャ", "mya"),
    ("ミュ", "myu"),
    ("ミョ", "myo"),
    ("リャ", "rya"),
    ("リュ", "ryu"),
    ("リョ", "ryo"),
    ("ギャ", "gya"),
    ("ギュ", "gyu"),
    ("ギョ", "gyo"),
    ("ジャ", "ja"),
    ("ジュ", "ju"),
    ("ジョ", "jo"),
    ("ビャ", "bya"),
    ("ビュ", "byu"),
    ("ビョ", "byo"),
    ("ピャ", "pya"),
    ("ピュ", "pyu"),
    ("ピョ", "pyo"),
    // Extended katakana for foreign words
    ("ファ", "fa"),
    ("フィ", "fi"),
    ("フェ", "fe"),
    ("フォ", "fo"),
    ("ウィ", "wi"),
    ("ウェ", "we"),
    ("ウォ", "wo"),
    ("ティ", "ti"),
    ("ディ", "di"),
    ("ツァ", "tsa"),
    ("ツェ", "tse"),
    ("ツォ", "tso"),
    ("チェ", "che"),
    ("ジェ", "je"),
    ("シェ", "she"),
    ("イェ", "ye"),
    ("ヴァ", "va"),
    ("ヴィ", "vi"),
    ("ヴェ", "ve"),
    ("ヴォ", "vo"),
];

// ── Base katakana ─────────────────────────────────────────────────────────────
static KATAKANA_BASE: &[(&str, &str)] = &[
    ("", "a"),
    ("", "i"),
    ("", "u"),
    ("", "e"),
    ("", "o"),
    ("", "ka"),
    ("", "ki"),
    ("", "ku"),
    ("", "ke"),
    ("", "ko"),
    ("", "sa"),
    ("", "shi"),
    ("", "su"),
    ("", "se"),
    ("", "so"),
    ("", "ta"),
    ("", "chi"),
    ("", "tsu"),
    ("", "te"),
    ("", "to"),
    ("", "na"),
    ("", "ni"),
    ("", "nu"),
    ("", "ne"),
    ("", "no"),
    ("", "ha"),
    ("", "hi"),
    ("", "fu"),
    ("", "he"),
    ("", "ho"),
    ("", "ma"),
    ("", "mi"),
    ("", "mu"),
    ("", "me"),
    ("", "mo"),
    ("", "ya"),
    ("", "yu"),
    ("", "yo"),
    ("", "ra"),
    ("", "ri"),
    ("", "ru"),
    ("", "re"),
    ("", "ro"),
    ("", "wa"),
    ("", "wo"),
    ("", "n"),
    // Voiced (dakuten)
    ("", "ga"),
    ("", "gi"),
    ("", "gu"),
    ("", "ge"),
    ("", "go"),
    ("", "za"),
    ("", "ji"),
    ("", "zu"),
    ("", "ze"),
    ("", "zo"),
    ("", "da"),
    ("", "ji"),
    ("", "zu"),
    ("", "de"),
    ("", "do"),
    ("", "ba"),
    ("", "bi"),
    ("", "bu"),
    ("", "be"),
    ("", "bo"),
    // Semi-voiced (handakuten)
    ("", "pa"),
    ("", "pi"),
    ("", "pu"),
    ("", "pe"),
    ("", "po"),
    // Small vowels
    ("", "a"),
    ("", "i"),
    ("", "u"),
    ("", "e"),
    ("", "o"),
    // Small ya/yu/yo
    ("", "ya"),
    ("", "yu"),
    ("", "yo"),
    // Small tsu handled separately
    // Small wa
    ("", "wa"),
    // Vu
    ("", "vu"),
];

// Unicode code points for special characters
const HIRAGANA_SMALL_TSU: char = '';
const KATAKANA_SMALL_TSU: char = '';
const KATAKANA_LONG_VOWEL: char = '';

// Macron-extended vowels for long vowel representation
const fn long_vowel_macron(romaji: &str) -> Option<&'static str> {
    match romaji.as_bytes() {
        b"a" => Some("ā"),
        b"i" => Some("ī"),
        b"u" => Some("ū"),
        b"e" => Some("ē"),
        b"o" => Some("ō"),
        _ => None,
    }
}

/// Hepburn romanisation transliterator for Japanese.
///
/// Converts hiragana and katakana to Hepburn romaji.
/// Non-Japanese characters are passed through unchanged.
///
/// # Long vowels
/// When `use_macron` is `true` (default), the katakana long-vowel mark `ー`
/// extends the preceding vowel using a macron (ā ī ū ē ō).
/// When `false`, `ー` is rendered as a repeated vowel.
///
/// # Doubled consonants
/// The small tsu `っ`/`ッ` is rendered by doubling the initial consonant of
/// the following syllable (e.g. `っき` → `kki`).
#[derive(Debug, Clone)]
pub struct HepburnTransliterator {
    use_macron: bool,
}

impl HepburnTransliterator {
    /// Create a new `HepburnTransliterator` with macron-based long vowels enabled.
    pub fn new() -> Self {
        Self { use_macron: true }
    }

    /// Create a new `HepburnTransliterator` with explicit macron setting.
    pub fn with_macron(use_macron: bool) -> Self {
        Self { use_macron }
    }
}

impl Default for HepburnTransliterator {
    fn default() -> Self {
        Self::new()
    }
}

impl Transliterator for HepburnTransliterator {
    fn transliterate(&self, input: &str) -> String {
        let chars: Vec<char> = input.chars().collect();
        let mut result = String::with_capacity(input.len() * 2);
        let mut i = 0;

        while i < chars.len() {
            let ch = chars[i];

            // Handle small tsu (doubled consonant)
            if ch == HIRAGANA_SMALL_TSU || ch == KATAKANA_SMALL_TSU {
                // Peek ahead: get the romaji of the next syllable
                if i + 1 < chars.len() {
                    let next_romaji = transliterate_single_char_or_combo(&chars, i + 1);
                    // The initial consonant of the next syllable is doubled
                    if let Some(first_byte) = next_romaji
                        .chars()
                        .next()
                        .filter(|c| c.is_ascii_alphabetic())
                    {
                        result.push(first_byte);
                        // Don't advance i; let the next iteration handle i+1 normally
                        i += 1;
                        continue;
                    }
                }
                // Fallback: emit nothing (small tsu with no following kana)
                i += 1;
                continue;
            }

            // Handle katakana long vowel mark ー
            if ch == KATAKANA_LONG_VOWEL {
                if self.use_macron {
                    // Find the last vowel in result and apply macron
                    let prev_vowel = get_last_vowel_char(&result);
                    if let Some(v) = prev_vowel.and_then(long_vowel_macron) {
                        // Replace last character (the short vowel) with macron version
                        replace_last_vowel_with_macron(&mut result, v);
                    } else {
                        result.push(ch); // pass through if no prior vowel
                    }
                } else {
                    // Repeat the last vowel
                    if let Some(v) = get_last_vowel_char(&result) {
                        let v_char = v.chars().next().unwrap_or('');
                        result.push(v_char);
                    } else {
                        result.push(ch);
                    }
                }
                i += 1;
                continue;
            }

            // Try yōon (2-char combo) first for both hiragana and katakana
            if i + 1 < chars.len() {
                let two_char: String = chars[i..=i + 1].iter().collect();
                if let Some(romaji) = lookup_table(HIRAGANA_YOON, &two_char)
                    .or_else(|| lookup_table(KATAKANA_YOON, &two_char))
                {
                    result.push_str(romaji);
                    i += 2;
                    continue;
                }
            }

            // Try single hiragana
            let one_char: String = std::iter::once(ch).collect();
            if let Some(romaji) = lookup_table(HIRAGANA_BASE, &one_char)
                .or_else(|| lookup_table(KATAKANA_BASE, &one_char))
            {
                result.push_str(romaji);
                i += 1;
                continue;
            }

            // Pass through unchanged (Latin, CJK, punctuation, etc.)
            result.push(ch);
            i += 1;
        }

        result
    }
}

// ── Helper functions ──────────────────────────────────────────────────────────

/// Look up a string in a static table; returns the romanisation or `None`.
fn lookup_table<'a>(table: &'a [(&str, &str)], key: &str) -> Option<&'a str> {
    table
        .iter()
        .find(|(src, _)| *src == key)
        .map(|(_, dst)| *dst)
}

/// Get the romaji of the syllable starting at index `idx` in `chars`,
/// used for peeking ahead to double the consonant after small-tsu.
fn transliterate_single_char_or_combo(chars: &[char], idx: usize) -> String {
    if idx >= chars.len() {
        return String::new();
    }
    // Try two-char combo first
    if idx + 1 < chars.len() {
        let two: String = chars[idx..=idx + 1].iter().collect();
        if let Some(r) =
            lookup_table(HIRAGANA_YOON, &two).or_else(|| lookup_table(KATAKANA_YOON, &two))
        {
            return r.to_string();
        }
    }
    // Single char
    let one: String = std::iter::once(chars[idx]).collect();
    lookup_table(HIRAGANA_BASE, &one)
        .or_else(|| lookup_table(KATAKANA_BASE, &one))
        .map(|s| s.to_string())
        .unwrap_or_default()
}

/// Return a static string slice for the last vowel in `s`, if any.
fn get_last_vowel_char(s: &str) -> Option<&'static str> {
    let last_char = s.chars().next_back()?;
    match last_char {
        'a' => Some("a"),
        'i' => Some("i"),
        'u' => Some("u"),
        'e' => Some("e"),
        'o' => Some("o"),
        // Already has a macron? Handle repeated ー
        'ā' => Some("a"),
        'ī' => Some("i"),
        'ū' => Some("u"),
        'ē' => Some("e"),
        'ō' => Some("o"),
        _ => None,
    }
}

/// Replace the last short vowel (or macron vowel) in `s` with the macron form.
fn replace_last_vowel_with_macron(s: &mut String, macron: &str) {
    // The last character might be a multi-byte char (macron vowel)
    // Pop the last char and replace with macron
    if s.is_empty() {
        s.push_str(macron);
        return;
    }
    // Find the byte offset of the last character
    let last_char_len = s.chars().next_back().map(|c| c.len_utf8()).unwrap_or(0);
    let new_len = s.len() - last_char_len;
    s.truncate(new_len);
    s.push_str(macron);
}

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

    #[test]
    fn test_hiragana_basic() {
        let t = HepburnTransliterator::new();
        assert_eq!(t.transliterate("あいうえお"), "aiueo");
    }

    #[test]
    fn test_hiragana_sakura() {
        let t = HepburnTransliterator::new();
        assert_eq!(t.transliterate("さくら"), "sakura");
    }

    #[test]
    fn test_hiragana_konnichiwa() {
        let t = HepburnTransliterator::new();
        // こんにちは — "ko" + "n" + "ni" + "chi" + "ha"
        assert_eq!(t.transliterate("こんにちは"), "konnichiha");
    }

    #[test]
    fn test_hiragana_yoon() {
        let t = HepburnTransliterator::new();
        assert_eq!(t.transliterate("きゃ"), "kya");
        assert_eq!(t.transliterate("しゃ"), "sha");
        assert_eq!(t.transliterate("ちゃ"), "cha");
    }

    #[test]
    fn test_small_tsu_doubled_consonant() {
        let t = HepburnTransliterator::new();
        // っき → kki
        assert_eq!(t.transliterate("っき"), "kki");
        // にっき → nikki
        assert_eq!(t.transliterate("にっき"), "nikki");
    }

    #[test]
    fn test_katakana_basic() {
        let t = HepburnTransliterator::new();
        assert_eq!(t.transliterate("アイウエオ"), "aiueo");
    }

    #[test]
    fn test_katakana_long_vowel_macron() {
        let t = HepburnTransliterator::new();
        // トーキョー → tōkyō
        let result = t.transliterate("トーキョー");
        assert!(
            result.contains('ō') || result.contains("oo"),
            "expected long-o: got {result}"
        );
    }

    #[test]
    fn test_katakana_long_vowel_no_macron() {
        let t = HepburnTransliterator::with_macron(false);
        // トー → "too"
        let result = t.transliterate("トー");
        assert_eq!(result, "too");
    }

    #[test]
    fn test_latin_passthrough() {
        let t = HepburnTransliterator::new();
        assert_eq!(t.transliterate("Hello"), "Hello");
    }

    #[test]
    fn test_mixed_latin_hiragana() {
        let t = HepburnTransliterator::new();
        let result = t.transliterate("Hello こんにちは World");
        assert!(result.contains("Hello"), "got: {result}");
        assert!(result.contains("World"), "got: {result}");
        assert!(result.contains("konnichiha"), "got: {result}");
    }

    #[test]
    fn test_dakuten_voiced() {
        let t = HepburnTransliterator::new();
        assert_eq!(t.transliterate(""), "ga");
        assert_eq!(t.transliterate(""), "ji");
        assert_eq!(t.transliterate(""), "bo");
    }

    #[test]
    fn test_handakuten_semivoiced() {
        let t = HepburnTransliterator::new();
        assert_eq!(t.transliterate(""), "pa");
        assert_eq!(t.transliterate(""), "po");
    }
}