obadh_engine 0.9.1

A linguistically accurate Roman to Bengali transliteration engine
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
use std::collections::BTreeSet;

use obadh_engine::definitions::{
    consonant_categories, consonant_value, diacritic_rules, diacritic_value, is_vowel,
    numeral_rules, symbol_rules, symbol_value, vowel_value,
};
use obadh_engine::ObadhEngine;

const CARGO_MANIFEST_DOC: &str = include_str!("../Cargo.toml");
const CONSONANT_RULES_DOC: &str = include_str!("../data/rules/consonants.md");
const README_DOC: &str = include_str!("../README.md");
const CONJUNCT_RULES_DOC: &str = include_str!("../data/rules/conjunct.wiki");
const DELIBERATE_INPUT_CORPUS_DOC: &str = include_str!("../data/rules/deliberate_input_corpus.md");
const SIMPLIFIED_RULES_DOC: &str = include_str!("../data/rules/simplified_rules.md");
const VOWEL_RULES_DOC: &str = include_str!("../data/rules/vowels.md");

#[test]
fn documented_basic_vowel_table_matches_runtime_rules() {
    for row in basic_vowel_table_rows(VOWEL_RULES_DOC) {
        for roman in roman_rule_keys(row.roman_input) {
            let vowel =
                vowel_value(roman).unwrap_or_else(|| panic!("documented vowel {roman:?} missing"));

            assert_eq!(
                vowel.independent, row.independent,
                "documented independent vowel for {roman:?} should match runtime"
            );
            assert_eq!(
                vowel.dependent,
                documented_dependent_vowel(row.dependent),
                "documented dependent vowel for {roman:?} should match runtime"
            );
        }
    }
}

#[test]
fn documented_lowercase_oi_ou_policy_matches_runtime_behavior() {
    assert!(!is_vowel("oi"));
    assert!(!is_vowel("ou"));

    let engine = ObadhEngine::new();
    assert_eq!(engine.transliterate("boi bou koi kou"), "বই বউ কই কউ");
    assert_eq!(engine.transliterate("bOI bOU kOI kOU"), "বৈ বৌ কৈ কৌ");
}

#[test]
fn documented_consonant_vowel_examples_match_runtime_behavior() {
    let engine = ObadhEngine::new();

    for row in consonant_vowel_example_rows(VOWEL_RULES_DOC) {
        assert_eq!(
            engine.transliterate(row.roman_input),
            row.bengali_output,
            "documented consonant-vowel example {:?} should match runtime",
            row.roman_input
        );
    }
}

#[test]
fn documented_simplified_rule_signals_match_runtime_behavior() {
    let engine = ObadhEngine::new();

    for example in documented_arrow_examples(SIMPLIFIED_RULES_DOC) {
        assert_eq!(
            engine.transliterate(example.roman_input),
            example.bengali_output,
            "documented simplified rule signal {:?} on line {} should match runtime",
            example.roman_input,
            example.line_number
        );
    }
}

#[test]
fn deliberate_input_rule_probe_corpus_matches_runtime_behavior() {
    let engine = ObadhEngine::new();
    let rows = deliberate_input_corpus_rows(DELIBERATE_INPUT_CORPUS_DOC);
    let mut inputs = BTreeSet::new();
    let mut categories = BTreeSet::new();

    assert_eq!(
        rows.len(),
        24,
        "rule probe corpus should keep the deliberate seed coverage set complete"
    );

    for row in rows {
        assert!(
            categories.insert(row.category),
            "rule probe corpus should not duplicate category {:?}",
            row.category
        );
        assert!(
            inputs.insert(row.roman_input),
            "rule probe corpus should not duplicate Roman input {:?}",
            row.roman_input
        );
        assert_eq!(
            engine.transliterate(row.roman_input),
            row.bengali_output,
            "rule probe corpus row {} in category {:?} should match runtime",
            row.line_number,
            row.category
        );
    }
}

#[test]
fn documented_numeral_table_matches_runtime_rules() {
    let documented_rows = simplified_numeral_table_rows(SIMPLIFIED_RULES_DOC).collect::<Vec<_>>();

    assert_eq!(
        documented_rows.len(),
        numeral_rules().len(),
        "simplified rules doc should list every runtime numeral rule"
    );

    for (&(roman, bengali), row) in numeral_rules().iter().zip(documented_rows) {
        assert_eq!(
            row.latin, roman,
            "documented numeral row should follow runtime numeral order"
        );
        assert_eq!(
            row.bengali, bengali,
            "documented Bengali numeral for {roman:?} should match runtime"
        );
    }
}

#[test]
fn deliberate_input_contract_documents_every_diacritic_rule() {
    let documented_signals = deliberate_input_contract_signal_cells(README_DOC);

    for &(roman, expected) in diacritic_rules() {
        assert_eq!(
            diacritic_value(roman),
            Some(expected),
            "diacritic {roman:?} should be directly renderable"
        );
        assert!(
            documented_signals
                .iter()
                .any(|signal| signal_cell_mentions(signal, roman)),
            "runtime diacritic signal {roman:?} is missing from README deliberate input contract"
        );
    }
}

#[test]
fn deliberate_input_contract_documents_every_symbol_rule() {
    let documented_signals = deliberate_input_contract_signal_cells(README_DOC);
    let engine = ObadhEngine::new();

    for &(roman, expected) in symbol_rules() {
        assert_eq!(
            symbol_value(roman),
            Some(expected),
            "symbol {roman:?} should be directly renderable"
        );
        assert_eq!(
            engine.transliterate(roman),
            expected,
            "symbol {roman:?} should render through the public engine path"
        );
        assert!(
            documented_signals
                .iter()
                .any(|signal| signal_cell_mentions(signal, roman)),
            "runtime symbol signal {roman:?} is missing from README deliberate input contract"
        );
    }

    assert_eq!(
        engine.transliterate("12.34 12.34."),
        "১২.৩৪ ১২.৩৪।",
        "decimal periods should stay ASCII periods between number-bearing tokens"
    );
}

#[test]
fn documented_consonant_table_matches_runtime_rules() {
    let mut documented_keys = BTreeSet::new();

    for row in basic_consonant_table_rows(CONSONANT_RULES_DOC) {
        for roman in roman_rule_keys(row.roman_input) {
            assert!(
                documented_keys.insert(roman),
                "documented consonant key {roman:?} should appear only once"
            );
            assert_eq!(
                consonant_value(roman),
                Some(row.bengali_output),
                "documented consonant output for {roman:?} should match runtime"
            );
        }
    }

    for category in consonant_categories() {
        for &(roman, expected) in category {
            assert_eq!(
                consonant_value(roman),
                Some(expected),
                "consonant {roman:?} should be directly renderable"
            );
            assert!(
                documented_keys.contains(roman),
                "runtime consonant signal {roman:?} is missing from data/rules/consonants.md"
            );
        }
    }
}

#[test]
fn deliberate_input_contract_documents_non_conjunct_ra_ya_zwnj_source_note() {
    let zwnj_ra_ya = "\u{200C}\u{09CD}";

    assert!(
        CONJUNCT_RULES_DOC.contains(zwnj_ra_ya),
        "source conjunct notes should retain the non-conjunct ra-ya ZWNJ example"
    );
    assert!(
        README_DOC.contains("`rZy`") && README_DOC.contains(zwnj_ra_ya),
        "README deliberate input contract should document the non-conjunct ra-ya ZWNJ signal"
    );
}

#[test]
fn cargo_package_excludes_non_runtime_audit_and_playground_assets() {
    for excluded_path in [
        "/data/autocorrect/**",
        "/data/autosuggest/**",
        "/docs/**",
        "/tools/**",
        "/www/**",
        "/.gitmodules",
        "/Makefile",
        "/build.sh",
        "/init.sh",
    ] {
        assert!(
            cargo_manifest_exclude_entries(CARGO_MANIFEST_DOC).contains(&excluded_path),
            "Cargo package should exclude {excluded_path} from the shipped crate"
        );
    }
}

struct VowelTableRow<'a> {
    roman_input: &'a str,
    independent: &'a str,
    dependent: &'a str,
}

struct ConsonantTableRow<'a> {
    roman_input: &'a str,
    bengali_output: &'a str,
}

struct ConsonantVowelExampleRow<'a> {
    roman_input: &'a str,
    bengali_output: &'a str,
}

struct DocumentedExample<'a> {
    line_number: usize,
    roman_input: &'a str,
    bengali_output: &'a str,
}

struct NumeralTableRow<'a> {
    latin: &'a str,
    bengali: &'a str,
}

struct RuleProbeRow<'a> {
    line_number: usize,
    category: &'a str,
    roman_input: &'a str,
    bengali_output: &'a str,
}

#[derive(Clone, Copy)]
struct CodeSpan<'a> {
    start: usize,
    end: usize,
    text: &'a str,
}

fn basic_consonant_table_rows(markdown: &str) -> impl Iterator<Item = ConsonantTableRow<'_>> {
    markdown
        .lines()
        .skip_while(|line| !line.starts_with("| Roman Input | Bengali Output |"))
        .skip(2)
        .take_while(|line| line.starts_with('|'))
        .filter_map(parse_consonant_table_row)
}

fn parse_consonant_table_row(line: &str) -> Option<ConsonantTableRow<'_>> {
    let mut columns = line.trim_matches('|').split('|').map(str::trim);

    Some(ConsonantTableRow {
        roman_input: columns.next()?,
        bengali_output: columns.next()?,
    })
}

fn consonant_vowel_example_rows(
    markdown: &str,
) -> impl Iterator<Item = ConsonantVowelExampleRow<'_>> {
    markdown
        .lines()
        .skip_while(|line| !line.starts_with("| Combination | Roman Input | Bengali Output |"))
        .skip(2)
        .take_while(|line| line.starts_with('|'))
        .filter_map(parse_consonant_vowel_example_row)
}

fn parse_consonant_vowel_example_row(line: &str) -> Option<ConsonantVowelExampleRow<'_>> {
    let mut columns = line.trim_matches('|').split('|').map(str::trim);
    let _combination = columns.next()?;

    Some(ConsonantVowelExampleRow {
        roman_input: columns.next()?,
        bengali_output: columns.next()?,
    })
}

fn basic_vowel_table_rows(markdown: &str) -> impl Iterator<Item = VowelTableRow<'_>> {
    markdown
        .lines()
        .skip_while(|line| !line.starts_with("| Roman Input | Independent Vowel |"))
        .skip(2)
        .take_while(|line| line.starts_with('|'))
        .filter_map(parse_vowel_table_row)
}

fn parse_vowel_table_row(line: &str) -> Option<VowelTableRow<'_>> {
    let mut columns = line.trim_matches('|').split('|').map(str::trim);

    Some(VowelTableRow {
        roman_input: columns.next()?,
        independent: columns.next()?,
        dependent: columns.next()?,
    })
}

fn roman_rule_keys(input: &str) -> impl Iterator<Item = &str> {
    input.split('/').map(str::trim)
}

fn documented_dependent_vowel(value: &str) -> Option<&str> {
    if value.starts_with('-') {
        None
    } else {
        Some(value)
    }
}

fn simplified_numeral_table_rows(markdown: &str) -> impl Iterator<Item = NumeralTableRow<'_>> {
    markdown
        .lines()
        .skip_while(|line| !line.starts_with("| Latin | Bengali |"))
        .skip(2)
        .take_while(|line| line.starts_with('|'))
        .filter_map(parse_numeral_table_row)
}

fn parse_numeral_table_row(line: &str) -> Option<NumeralTableRow<'_>> {
    let mut columns = line.trim_matches('|').split('|').map(str::trim);

    Some(NumeralTableRow {
        latin: columns.next()?,
        bengali: columns.next()?,
    })
}

fn deliberate_input_corpus_rows(markdown: &str) -> Vec<RuleProbeRow<'_>> {
    let rows = markdown
        .lines()
        .enumerate()
        .skip_while(|(_, line)| !line.starts_with("| Category | Roman Input | Bengali Output |"))
        .skip(2)
        .take_while(|(_, line)| line.starts_with('|'))
        .map(|(line_index, line)| parse_rule_probe_row(line_index + 1, line))
        .collect::<Vec<_>>();

    assert!(
        !rows.is_empty(),
        "rule probe corpus table is missing or empty"
    );

    rows
}

fn parse_rule_probe_row(line_number: usize, line: &str) -> RuleProbeRow<'_> {
    let columns = line
        .trim_matches('|')
        .split('|')
        .map(str::trim)
        .collect::<Vec<_>>();

    assert_eq!(
        columns.len(),
        4,
        "Malformed rule probe corpus row {line_number}: expected 4 columns, got {}",
        columns.len()
    );

    assert!(
        !columns[0].is_empty(),
        "Rule probe corpus row {line_number} should have a category"
    );
    assert!(
        !columns[3].is_empty(),
        "Rule probe corpus row {line_number} should explain the contract"
    );

    RuleProbeRow {
        line_number,
        category: columns[0],
        roman_input: single_code_span_text(columns[1]).unwrap_or_else(|| {
            panic!("Rule probe corpus row {line_number} should have one Roman input code span")
        }),
        bengali_output: single_code_span_text(columns[2]).unwrap_or_else(|| {
            panic!("Rule probe corpus row {line_number} should have one Bengali output code span")
        }),
    }
}

fn single_code_span_text(cell: &str) -> Option<&str> {
    let spans = code_spans(cell);
    (spans.len() == 1).then_some(spans[0].text)
}

fn cargo_manifest_exclude_entries(manifest: &str) -> BTreeSet<&str> {
    let mut entries = BTreeSet::new();
    let mut in_exclude = false;

    for line in manifest.lines() {
        let line = line.trim();

        if line.starts_with("exclude = [") {
            in_exclude = true;
            continue;
        }

        if in_exclude && line == "]" {
            break;
        }

        if in_exclude {
            let Some(entry) = line
                .strip_prefix('"')
                .and_then(|line| line.split_once('"').map(|(entry, _)| entry))
            else {
                continue;
            };
            entries.insert(entry);
        }
    }

    entries
}

fn deliberate_input_contract_signal_cells(markdown: &str) -> Vec<&str> {
    markdown
        .lines()
        .skip_while(|line| !line.starts_with("| Roman Signal | Bengali Rule Intent |"))
        .skip(2)
        .take_while(|line| line.starts_with('|'))
        .filter_map(|line| line.trim_matches('|').split('|').next().map(str::trim))
        .collect()
}

fn signal_cell_mentions(signal: &str, roman: &str) -> bool {
    signal.contains(&format!("`{roman}`")) || signal.contains(&format!("<code>{roman}</code>"))
}

fn documented_arrow_examples(markdown: &str) -> Vec<DocumentedExample<'_>> {
    let mut examples = Vec::new();

    for (line_index, line) in markdown.lines().enumerate() {
        let spans = code_spans(line);
        for (arrow_index, arrow) in line.match_indices('') {
            let Some(output_span) = spans.iter().find(|span| span.start > arrow_index) else {
                continue;
            };

            for input_span in connected_input_spans_before_arrow(line, &spans, arrow_index) {
                examples.push(DocumentedExample {
                    line_number: line_index + 1,
                    roman_input: input_span.text,
                    bengali_output: output_span.text,
                });
            }

            debug_assert_eq!(arrow, "");
        }
    }

    examples
}

fn connected_input_spans_before_arrow<'line, 'spans>(
    line: &'line str,
    spans: &'spans [CodeSpan<'line>],
    arrow_index: usize,
) -> &'spans [CodeSpan<'line>] {
    let Some(last_input_index) = spans
        .iter()
        .rposition(|span| span.end <= arrow_index && connector_text(line, span.end, arrow_index))
    else {
        return &[];
    };

    let mut first_input_index = last_input_index;
    while first_input_index > 0 {
        let previous = spans[first_input_index - 1];
        let current = spans[first_input_index];
        if !connector_text(line, previous.end, current.start) {
            break;
        }
        first_input_index -= 1;
    }

    &spans[first_input_index..=last_input_index]
}

fn connector_text(line: &str, start: usize, end: usize) -> bool {
    line[start..end]
        .chars()
        .all(|character| character.is_whitespace() || character == '/')
}

fn code_spans(line: &str) -> Vec<CodeSpan<'_>> {
    let mut spans = Vec::new();
    let mut cursor = 0;

    while cursor < line.len() {
        let next_backtick = line[cursor..].find('`').map(|offset| cursor + offset);
        let next_html = line[cursor..].find("<code>").map(|offset| cursor + offset);

        if let Some(content_start) = next_html.filter(|&html_start| {
            next_backtick.is_none_or(|backtick_start| html_start < backtick_start)
        }) {
            if let Some(content_end) = line[content_start + 6..]
                .find("</code>")
                .map(|offset| content_start + 6 + offset)
            {
                spans.push(CodeSpan {
                    start: content_start,
                    end: content_end + 7,
                    text: &line[content_start + 6..content_end],
                });
                cursor = content_end + 7;
                continue;
            }
        }

        let Some(content_start) = next_backtick else {
            break;
        };
        let Some(content_end) = line[content_start + 1..]
            .find('`')
            .map(|offset| content_start + 1 + offset)
        else {
            break;
        };

        spans.push(CodeSpan {
            start: content_start,
            end: content_end + 1,
            text: &line[content_start + 1..content_end],
        });
        cursor = content_end + 1;
    }

    spans.sort_unstable_by_key(|span| span.start);
    spans
}