braillify 2.1.0

Rust 기반 크로스플랫폼 한국어 점역 라이브러리
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
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
use super::*;

impl EnglishUebEngine {
    /// §9: encode a styled word's base letters as an ordinary word (caps +
    /// contractions, with its standing-alone context taken from `tokens[i-1]` and
    /// `tokens[j]`) — the typeform indicator is emitted separately by the caller.
    pub(super) fn encode_styled_word(
        &self,
        chars: &[char],
        i: usize,
        j: usize,
        ctx: StyledContext<'_>,
        out: &mut Vec<u8>,
    ) -> Option<()> {
        let lower_word: String = chars.iter().flat_map(|c| c.to_lowercase()).collect();
        if super::super::rule_10_9::whole_word_cells(&lower_word).is_some() {
            let prev = i.checked_sub(1).map(|p| &ctx.tokens[p]);
            let next = ctx.tokens.get(j);
            let standing_alone = is_standing_alone(prev, next);
            return self.encode_word(
                chars,
                WordContext {
                    standing_alone,
                    upper_usable: false,
                    shortform_usable: standing_alone,
                    allow_longer_shortforms: true,
                    lower_usable: false,
                    suppress_caps: ctx.suppress_caps,
                    word_initial: word_initial_boundary(prev),
                    restricted_prefix_boundary: word_initial_boundary(prev),
                    digit_adjacent: false,
                },
                out,
            );
        }
        if let Some((accent_code, spanish)) = ctx.foreign_scope {
            let cells =
                super::super::rule_13::encode_uncontracted_word(chars, accent_code, spanish)?;
            out.extend(cells);
            return Some(());
        }
        if chars.iter().all(|c| c.is_ascii_digit()) {
            out.extend(super::super::rule_6::encode_number(chars)?);
            return Some(());
        }
        if chars.len() == 1 && !chars[0].is_ascii_alphabetic() {
            encode_styled_nonword_symbol(chars[0], out)?;
            return Some(());
        }
        let prev = i.checked_sub(1).map(|p| &ctx.tokens[p]);
        let next = ctx.tokens.get(j);
        if super::super::rule_10_9::is_pure_shortform_abbreviation(&lower_word) {
            let standing_alone = is_standing_alone(prev, next);
            return self.encode_word(
                chars,
                WordContext {
                    standing_alone,
                    upper_usable: false,
                    shortform_usable: standing_alone,
                    allow_longer_shortforms: true,
                    lower_usable: false,
                    suppress_caps: ctx.suppress_caps,
                    word_initial: word_initial_boundary(prev),
                    restricted_prefix_boundary: word_initial_boundary(prev),
                    digit_adjacent: false,
                },
                out,
            );
        }
        if !ctx.suppress_caps
            && let Some((accent_code, spanish)) =
                styled_phrase_foreign_scope(ctx.tokens, i, styled_form_at(ctx.tokens, i)?)
        {
            out.extend(super::super::rule_13::encode_uncontracted_word(
                chars,
                accent_code,
                spanish,
            )?);
            return Some(());
        }
        let form = styled_form_at(ctx.tokens, i)?;
        if super::super::rule_10_9::whole_word_cells(&lower_word).is_none()
            && styled_titlecase_phrase_from_named_place(ctx.tokens, i)
        {
            out.extend(super::super::rule_13::encode_uncontracted_word(
                chars,
                super::super::rule_13::AccentCode::Ueb,
                false,
            )?);
            return Some(());
        }
        if !ctx.suppress_caps
            && !styled_word_in_english_title(ctx.tokens, i, form)
            && !styled_word_in_lowercase_phrase_before_word(ctx.tokens, i, form, "of")
            && !domain_component_context(ctx.tokens, i)
            && styled_single_word_is_foreign(chars)
        {
            let doc_letters = document_letters(ctx.tokens);
            let accent_code = if super::super::rule_13::has_foreign_code_signal(&doc_letters) {
                super::super::rule_13::AccentCode::Foreign
            } else {
                super::super::rule_13::AccentCode::Ueb
            };
            out.extend(super::super::rule_13::encode_uncontracted_word(
                chars,
                accent_code,
                super::super::rule_13::spanish_context(&doc_letters),
            )?);
            return Some(());
        }
        if let Some(cells) =
            lower_sequence_before_apostrophe_cells(chars, &self.contractions, prev, next, true)
        {
            out.extend(lower_sequence_word_cells(chars, &cells)?);
            return Some(());
        }
        let standing_alone = is_standing_alone(prev, next);
        let shortform_usable =
            standing_alone && !matches!(next, Some(EnglishToken::Symbol('@' | '/')));
        let lower_usable = standing_alone
            && styled_lower_wordsign_usable(&lower_word, prev, next)
            && !styled_scansion_word(ctx.tokens, &lower_word);
        self.encode_word(
            chars,
            WordContext {
                standing_alone,
                upper_usable: standing_alone
                    && !matches!(prev, Some(EnglishToken::Symbol('/')))
                    && !matches!(next, Some(EnglishToken::Symbol('/'))),
                shortform_usable,
                allow_longer_shortforms: true,
                lower_usable,
                suppress_caps: ctx.suppress_caps,
                word_initial: word_initial_boundary(prev),
                restricted_prefix_boundary: word_initial_boundary(prev),
                digit_adjacent: false,
            },
            out,
        )
    }

    /// §9.5: encode a *multi-segment* styled word — its same-`form` styled letter
    /// runs (each as an ordinary word with its own §2.6 standing-alone context)
    /// and the symbols attached between them (`𝑜𝑓-𝑡ℎ𝑒` → `⠷⠤⠮`, `ℎ𝑡𝑡𝑝://…` →
    /// `⠓⠞⠞⠏⠒⠸⠌⠸⠌…`) — under the single typeform indicator emitted by the caller.
    pub(super) fn encode_styled_span(
        &self,
        start: usize,
        span_end: usize,
        form: super::super::token::Typeform,
        ctx: StyledContext<'_>,
        out: &mut Vec<u8>,
    ) -> Option<()> {
        // §13.2.1 hyphenated foreign compound: if ANY segment in the span is
        // foreign (`foih-𝑐ℎ𝑎𝑖`, `𝑙'𝑜𝑒𝑖𝑙-𝑑𝑒-𝑏𝑜𝑒𝑢𝑓`), every segment is uncontracted
        // — a single foreign word can be spelled across hyphens and its
        // anglicised-looking sub-segment (`chai`, `de`) shares the foreign
        // context. This is a span-level context that the per-segment
        // `styled_word_is_foreign` check cannot see.
        let span_foreign_scope = if ctx.foreign_scope.is_some() {
            ctx.foreign_scope
        } else {
            let mut any_foreign = false;
            let mut kk = start;
            while kk < span_end {
                if let Some(EnglishToken::Styled(_, f)) = ctx.tokens.get(kk)
                    && *f == form
                {
                    let seg_start = kk;
                    let mut seg = Vec::new();
                    while kk < span_end
                        && matches!(&ctx.tokens.get(kk), Some(EnglishToken::Styled(_, g)) if *g == form)
                    {
                        if let Some(EnglishToken::Styled(c, _)) = ctx.tokens.get(kk) {
                            seg.push(*c);
                        }
                        kk += 1;
                    }
                    // §13.2.1: any segment carrying explicit foreign evidence
                    // OR a segment that is not itself a recorded English word
                    // (`chai`, `foih`, `boeuf`) makes the whole hyphenated span
                    // foreign — the surrounding italic marks the compound as
                    // foreign per §13.1.2 and contractions are suppressed for
                    // every segment.
                    if !domain_component_context(ctx.tokens, seg_start)
                        && (styled_word_has_foreign_signal(&seg)
                            || styled_single_word_is_foreign(&seg))
                    {
                        any_foreign = true;
                        break;
                    }
                } else {
                    kk += 1;
                }
            }
            if any_foreign {
                let doc_letters = document_letters(ctx.tokens);
                let accent_code = if super::super::rule_13::has_foreign_code_signal(&doc_letters) {
                    super::super::rule_13::AccentCode::Foreign
                } else {
                    super::super::rule_13::AccentCode::Ueb
                };
                Some((
                    accent_code,
                    super::super::rule_13::spanish_context(&doc_letters),
                ))
            } else {
                None
            }
        };
        let mut k = start;
        while k < span_end {
            match &ctx.tokens[k] {
                EnglishToken::Styled(_, f) if *f == form => {
                    let seg_start = k;
                    let mut seg_chars = Vec::new();
                    while k < span_end
                        && matches!(&ctx.tokens[k], EnglishToken::Styled(_, g) if *g == form)
                    {
                        if let EnglishToken::Styled(c, _) = &ctx.tokens[k] {
                            seg_chars.push(*c);
                        }
                        k += 1;
                    }
                    self.encode_styled_word(
                        &seg_chars,
                        seg_start,
                        k,
                        StyledContext {
                            tokens: ctx.tokens,
                            suppress_caps: ctx.suppress_caps,
                            foreign_scope: span_foreign_scope,
                        },
                        out,
                    )?;
                }
                EnglishToken::Symbol(c) => {
                    let cells = super::super::rule_7::encode_punctuation(*c)
                        .or_else(|| super::super::rule_3::encode_symbol(*c))?;
                    out.extend(cells);
                    k += 1;
                }
                EnglishToken::LineBreak => {
                    super::super::rule_10_13::append_break(out, false);
                    k += 1;
                }
                _ => return None,
            }
        }
        Some(())
    }

    /// UEB §9.1.3: encode a URL-shaped underlined span with its typeform omitted
    /// because the underline is a hyperlink enhancement, not significant emphasis.
    pub(super) fn encode_styled_as_unstyled_span(
        &self,
        start: usize,
        span_end: usize,
        form: super::super::token::Typeform,
        ctx: StyledContext<'_>,
        out: &mut Vec<u8>,
    ) -> Option<()> {
        let mut k = start;
        while k < span_end {
            match &ctx.tokens[k] {
                EnglishToken::Styled(c, f) if *f == form && c.is_ascii_alphabetic() => {
                    let seg_start = k;
                    let mut seg_chars = Vec::new();
                    while k < span_end
                        && matches!(&ctx.tokens[k], EnglishToken::Styled(ch, g) if *g == form && ch.is_ascii_alphabetic())
                    {
                        if let EnglishToken::Styled(ch, _) = &ctx.tokens[k] {
                            seg_chars.push(*ch);
                        }
                        k += 1;
                    }
                    self.encode_styled_word(
                        &seg_chars,
                        seg_start,
                        k,
                        StyledContext {
                            tokens: ctx.tokens,
                            suppress_caps: ctx.suppress_caps,
                            foreign_scope: ctx.foreign_scope,
                        },
                        out,
                    )?;
                }
                EnglishToken::Styled(c, f) if *f == form && c.is_ascii_digit() => {
                    let mut digits = Vec::new();
                    while k < span_end
                        && matches!(&ctx.tokens[k], EnglishToken::Styled(ch, g) if *g == form && ch.is_ascii_digit())
                    {
                        if let EnglishToken::Styled(ch, _) = &ctx.tokens[k] {
                            digits.push(*ch);
                        }
                        k += 1;
                    }
                    out.extend(super::super::rule_6::encode_number(&digits)?);
                }
                EnglishToken::Styled(c, f) if *f == form => {
                    encode_styled_nonword_symbol(*c, out)?;
                    k += 1;
                }
                EnglishToken::Symbol(c) => {
                    let cells = super::super::rule_7::encode_punctuation(*c)
                        .or_else(|| super::super::rule_3::encode_symbol(*c))?;
                    out.extend(cells);
                    k += 1;
                }
                EnglishToken::LineBreak => {
                    super::super::rule_10_13::append_break(out, false);
                    k += 1;
                }
                _ => return None,
            }
        }
        Some(())
    }

    /// UEB §10.13.1-§10.13.12: encode an originally unhyphenated word with an
    /// explicit line-division point, never allowing a contraction to span it.
    pub(super) fn encode_divided_word(
        &self,
        chars: &[char],
        break_at: usize,
        suppress_caps: bool,
        out: &mut Vec<u8>,
    ) -> Option<()> {
        if break_at == 0 || break_at >= chars.len() {
            return None;
        }
        if classify_caps(chars).is_none() {
            self.encode_divided_mixed_case(chars, break_at, out)?;
            return Some(());
        }

        let lower: Vec<char> = chars.iter().flat_map(|c| c.to_lowercase()).collect();
        let mut first_line_has_upper_prefix = false;
        match classify_caps(chars)? {
            _ if suppress_caps => {}
            Caps::None => {}
            Caps::Single => {
                out.push(CAPITAL);
                first_line_has_upper_prefix = true;
            }
            Caps::Word => {
                out.push(CAPITAL);
                out.push(CAPITAL);
                first_line_has_upper_prefix = true;
            }
        }
        let cells = super::super::rule_10_9::encode_with_division(
            &lower,
            &self.contractions,
            super::super::rule_10_13::WordDivision { index: break_at },
            first_line_has_upper_prefix,
        )?;
        out.extend(cells);
        Some(())
    }

    /// §10.13 with §8.2: a mixed-case divided word is split into its printed line
    /// segments, so a capital at the start of line two keeps its own indicator.
    pub(super) fn encode_divided_mixed_case(
        &self,
        chars: &[char],
        break_at: usize,
        out: &mut Vec<u8>,
    ) -> Option<()> {
        self.encode_word(
            &chars[..break_at],
            WordContext {
                standing_alone: false,
                upper_usable: false,
                shortform_usable: false,
                allow_longer_shortforms: true,
                lower_usable: false,
                suppress_caps: false,
                word_initial: false,
                restricted_prefix_boundary: false,
                digit_adjacent: false,
            },
            out,
        )?;
        super::super::rule_10_13::append_break(out, true);
        self.encode_word(
            &chars[break_at..],
            WordContext {
                standing_alone: false,
                upper_usable: false,
                shortform_usable: false,
                allow_longer_shortforms: true,
                lower_usable: false,
                suppress_caps: false,
                word_initial: true,
                restricted_prefix_boundary: true,
                digit_adjacent: false,
            },
            out,
        )
    }
}

#[cfg(test)]
mod tests {
    use super::super::test_support::{cells, enc};
    use super::*;

    #[test]
    fn styled_unstyled_span_helper_encodes_all_token_kinds() {
        let engine = EnglishUebEngine::new();
        let form = super::super::super::token::Typeform::Underline;
        let tokens = [
            EnglishToken::Styled('a', form),
            EnglishToken::Styled('b', form),
            EnglishToken::Symbol('/'),
            EnglishToken::Styled('1', form),
            EnglishToken::Styled('2', form),
            EnglishToken::LineBreak,
            EnglishToken::Styled('?', form),
        ];
        let mut out = Vec::new();
        engine
            .encode_styled_as_unstyled_span(
                0,
                tokens.len(),
                form,
                StyledContext {
                    tokens: &tokens,
                    suppress_caps: false,
                    foreign_scope: None,
                },
                &mut out,
            )
            .unwrap();
        assert_eq!(out, cells("⠁⠃⠸⠌⠼⠁⠃\n⠰⠦"));

        let wrong_form = [EnglishToken::Styled(
            'a',
            super::super::super::token::Typeform::Italic,
        )];
        let mut rejected = Vec::new();
        assert_eq!(
            engine.encode_styled_as_unstyled_span(
                0,
                wrong_form.len(),
                form,
                StyledContext {
                    tokens: &wrong_form,
                    suppress_caps: false,
                    foreign_scope: None,
                },
                &mut rejected,
            ),
            None
        );
    }

    #[test]
    fn styled_span_helper_preserves_line_breaks_between_segments() {
        let engine = EnglishUebEngine::new();
        let form = super::super::super::token::Typeform::Italic;
        let tokens = [
            EnglishToken::Styled('a', form),
            EnglishToken::LineBreak,
            EnglishToken::Styled('b', form),
        ];
        let mut out = Vec::new();

        engine
            .encode_styled_span(
                0,
                tokens.len(),
                form,
                StyledContext {
                    tokens: &tokens,
                    suppress_caps: false,
                    foreign_scope: None,
                },
                &mut out,
            )
            .unwrap();

        assert!(out.contains(&255));
    }

    #[test]
    fn styled_word_surface_encodes_plain_multiletter_run() {
        let engine = EnglishUebEngine::new();
        let form = super::super::super::token::Typeform::Italic;
        let tokens = [
            EnglishToken::Styled('r', form),
            EnglishToken::Styled('a', form),
            EnglishToken::Styled('d', form),
            EnglishToken::Styled('a', form),
            EnglishToken::Styled('r', form),
        ];

        let encoded = engine.encode(&tokens, false).unwrap();

        assert!(encoded.starts_with(&super::super::super::rule_9::word_indicator(form)));
    }

    #[test]
    fn divided_word_helper_covers_caps_mixed_and_invalid_breaks() {
        let engine = EnglishUebEngine::new();

        let mut invalid = Vec::new();
        assert_eq!(
            engine.encode_divided_word(&['c', 'a', 't'], 0, false, &mut invalid),
            None
        );
        assert_eq!(
            engine.encode_divided_word(&['c', 'a', 't'], 3, false, &mut invalid),
            None
        );

        let mut lower = Vec::new();
        engine
            .encode_divided_word(&['c', 'a', 't', 's'], 2, false, &mut lower)
            .unwrap();
        assert!(lower.contains(&255));

        let mut title = Vec::new();
        engine
            .encode_divided_word(&['C', 'a', 't', 's'], 2, false, &mut title)
            .unwrap();
        assert!(title.starts_with(&[CAPITAL]));

        let mut caps = Vec::new();
        engine
            .encode_divided_word(&['C', 'A', 'T', 'S'], 2, false, &mut caps)
            .unwrap();
        assert!(caps.starts_with(&[CAPITAL, CAPITAL]));
        assert!(caps.contains(&255));

        let mut mixed = Vec::new();
        engine
            .encode_divided_word(&['M', 'c', 'D', 'o', 'g'], 2, false, &mut mixed)
            .unwrap();
        assert!(mixed.contains(&255));
        assert!(mixed.iter().filter(|cell| **cell == CAPITAL).count() >= 2);
    }

    #[test]
    fn styled_word_foreign_detects_non_accented_foreign_letter() {
        // §13: a dot-below foreign letter (`ọ`, U+1ECD) is foreign but not a §4.2
        // accent, so it is detected as foreign vocabulary / a foreign signal.
        assert!(styled_word_is_foreign(&['\u{1ECD}']));
        assert!(styled_word_has_foreign_signal(&['\u{1ECD}']));
        // A recorded English word is not foreign.
        assert!(!styled_word_is_foreign(&['c', 'a', 't']));
    }

    #[test]
    fn encode_divided_word_suppressed_caps_path() {
        // §10.13: a line-divided word encoded inside a §8.4 caps passage
        // (suppress_caps) skips the per-word capital indicator.
        let mut out = Vec::new();
        assert!(
            EnglishUebEngine::new()
                .encode_divided_word(&['r', 'e', 'a', 'd', 'i', 'n', 'g'], 4, true, &mut out)
                .is_some()
        );
    }

    #[test]
    fn encode_styled_word_handles_single_symbol() {
        use super::super::super::token::Typeform;
        // A one-character styled word that is not a letter encodes as its symbol.
        let tokens = [EnglishToken::Styled('&', Typeform::Italic)];
        let ctx = StyledContext {
            tokens: &tokens,
            suppress_caps: false,
            foreign_scope: None,
        };
        let mut out = Vec::new();
        assert!(
            EnglishUebEngine::new()
                .encode_styled_word(&['&'], 0, 1, ctx, &mut out)
                .is_some()
        );
        assert!(!out.is_empty());
    }

    #[test]
    fn encode_styled_span_rejects_non_styled_interior_token() {
        use super::super::super::token::Typeform;
        // A styled span whose interior carries a bare Space (not styled / symbol /
        // line break) is not a well-formed multi-segment styled word.
        let tokens = [
            EnglishToken::Styled('x', Typeform::Italic),
            EnglishToken::Space,
            EnglishToken::Styled('y', Typeform::Italic),
        ];
        let ctx = StyledContext {
            tokens: &tokens,
            suppress_caps: false,
            foreign_scope: None,
        };
        let mut out = Vec::new();
        assert!(
            EnglishUebEngine::new()
                .encode_styled_span(0, 3, Typeform::Italic, ctx, &mut out)
                .is_none()
        );
    }

    #[test]
    fn encode_styled_word_encodes_all_digit_word_as_number() {
        use super::super::super::token::Typeform;
        // §6/§9: a styled word made only of digits encodes as a number.
        let tokens = [
            EnglishToken::Styled('1', Typeform::Italic),
            EnglishToken::Styled('2', Typeform::Italic),
        ];
        let ctx = StyledContext {
            tokens: &tokens,
            suppress_caps: false,
            foreign_scope: None,
        };
        let mut out = Vec::new();
        assert!(
            EnglishUebEngine::new()
                .encode_styled_word(&['1', '2'], 0, 2, ctx, &mut out)
                .is_some()
        );
        assert!(!out.is_empty());
    }

    #[test]
    fn styled_titlecase_place_phrase_encodes_uncontracted_word() {
        assert!(enc("\u{1D43A}\u{1D45F}\u{1D452}\u{1D44E}\u{1D461} \u{1D439}\u{1D44E}\u{1D459}\u{1D459}\u{1D460} from Montana").is_some());
    }
}