ewts 1.0.0

Converter between EWTS (Extended Wylie Transliteration Scheme) and Tibetan Unicode symbols (lib)
Documentation
use crate::dict::{NOT_EQUIVALENT, PRECOMPOSED, Sign};
use crate::tests::{Rng, random_iterations};
use crate::{UnicodeToEwts, UnicodeWarningKind, unicode_to_ewts};

fn assert_round_trip(unicode: &str) {
    let ewts = unicode_to_ewts(unicode).ewts;
    assert_eq!(crate::ewts_to_unicode(&ewts).unicode, unicode, "ewts: {ewts:?}");
}

// EWTS -> unicode -> EWTS gives back the source.
#[test]
fn ute_same_ewts() {
    let data = [
        "bsgribs mkhan gyon g.yon ",
        "brgyad brjod g.yeng gyeng g.yul brlabs bsgrags 'khor lo ",
        "dga' dga'o gangs mngon bkra shis bde legs/",
        "pa'i na'ang de'ang la'am mi'am ",
        "dgas bags mangs mags 'gas dbas ",
        "sat+t+wa bru+e rdo+e rta ",
        "sarba karma yoka mang+galaM pad+ma sid+d+hi ",
        "oM aHhU~M` gu ru hU~M`:",
        "a khu/_ug pa/_aM/",
        "mA duH phaT duHkha ",
        "R+na R+Ya R+ya rnya rla rwa s+Wa r+sha l+ra h+ya ",
        "va fi ki^ &ung sha ai gaang angs ka.i ",
        // A dot only where it changes the reading.
        "kaa+ka ka.o kaM.o a.a d+haa+k+Sho ",
        "khong [New York] la phebs song /",
        "@#/_/sangs rgyas chos dang tshogs kyi mchog rnams la/_/'gro la phan phyir sangs rgyas 'grub par shog_!",
    ];

    for ewts in data {
        let unicode = crate::ewts_to_unicode(ewts).unicode;
        assert_eq!(unicode_to_ewts(&unicode).ewts, ewts, "unicode: {unicode:?}");
    }
}

#[test]
fn ute_non_tibetan() {
    let data = [
        ("ཀ་привет", "ka привет"),
        ("ཀ་2024", "ka [2024]"),
        ("ཀ abc ཁ", "ka_[abc]_kha"),
        ("u U", "[u U]"),
        ("ཀ\nཁ, ཁ", "ka\nkha[,]_kha"),
        // ASCII that is not EWTS goes in brackets too: `ewts_to_unicode` would warn about it.
        ("K", "[K]"),
        ("Hello, world", "[Hello, world]"),
        ("ཀ \"x\" {a}]", "ka_[\"x\" {a}\\]]"),
        ("\t\r\u{c}", "\t\r\u{c}"),
        ("\u{0}\u{7f}", "[\u{0}\u{7f}]"),
        ("།།", "/\\u0f0d"),
        ("༎།", "///"),
        ("ཀ༁", "ka\\u0f01"),
        ("\u{f71}\u{f72}", "\\u0f71\\u0f72"),
        ("don\u{2019}t ཀ", "[don\u{2019}t]_ka"),
        ("ཀ\u{2019}", "ka[\u{2019}]"),
        ("ཀ་привет\u{2019}", "ka привет[\u{2019}]"),
    ];

    for (unicode, ewts) in data {
        assert_eq!(unicode_to_ewts(unicode).ewts, ewts, "unicode: {unicode:?}");
        assert_round_trip(unicode);
    }
}

// Brackets and backslashes in non-Tibetan text are escaped inside "[...]".
#[test]
fn ute_non_tibetan_syntax_chars() {
    for unicode in [
        "ཀ་a[b",
        "a[b]c",
        "ཀ་x\\y",
        "\\",
        "[",
        "ཀ་[[a]]",
        "a \\[ b",
        "ཀ\u{2019}",
        "a\u{2019}b",
        "д\u{02bc}",
    ] {
        assert_round_trip(unicode);
    }
}

// Precomposed chars convert back to their canonically equivalent decomposed form.
#[test]
fn ute_precomposed() {
    let data = [
        ("\u{f43}", "g+ha", "\u{f42}\u{fb7}"),
        ("\u{f40}\u{f73}", "kI", "\u{f40}\u{f71}\u{f72}"),
        ("\u{f66}\u{f75}", "sU", "\u{f66}\u{f71}\u{f74}"),
        ("\u{f69}", "k+Sha", "\u{f40}\u{fb5}"),
        ("\u{f54}\u{f93}", "p+g+ha", "\u{f54}\u{f92}\u{fb7}"),
        ("\u{f40}\u{f76}", "kr-i", "\u{f40}\u{fb2}\u{f80}"),
        ("\u{f00}", "oM", "\u{f68}\u{f7c}\u{f7e}"),
    ];

    for (unicode, ewts, decomposed) in data {
        assert_eq!(unicode_to_ewts(unicode).ewts, ewts, "unicode: {unicode:?}");
        assert_eq!(crate::ewts_to_unicode(ewts).unicode, decomposed, "ewts: {ewts:?}");
    }
}

#[test]
fn ute_round_trip_known_texts() {
    let texts = [crate::tests::TST_DATA, crate::rules_test::RULES_TST_DATA];
    for (_, unicode) in texts.iter().flat_map(|t| t.iter()) {
        assert_round_trip(unicode);
    }
}

// Random but well-formed syllables (letter, subjoined letters, vowels, tsa-phru, final signs) convert back exactly.
#[test]
fn ute_round_trip_random_syllables() {
    let bases: Vec<char> = "ཀཁགངཅཆཇཉཊཋཌཎཏཐདནཔཕབམཙཚཛཝཞཟའཡརལཤཥསཧཨཪ".chars().collect();
    let subs: Vec<char> = "ྐྑྒྔྕྖྗྙྚྛྜྞྟྠྡྣྤྥྦྨྩྪྫྭྮྯྰྱྲླྴྵྶྷྸྺྻྼ".chars().collect();
    let vowels: Vec<char> = "\u{f71}\u{f72}\u{f74}\u{f7a}\u{f7b}\u{f7c}\u{f7d}\u{f80}"
        .chars()
        .collect();
    let finals: Vec<char> = "\u{f7e}\u{f82}\u{f83}\u{f37}\u{f35}\u{f7f}\u{f84}".chars().collect();
    let separators = ["་", "།", " ", "༔", "\n"];

    let mut rng = Rng(0x9E37_79B9_7F4A_7C15);

    for _ in 0..20_000 {
        let mut s = String::new();
        for _ in 0..=rng.below(3) {
            for _ in 0..=rng.below(4) {
                s.push(rng.pick(&bases));
                for _ in 0..rng.pick(&[0, 0, 0, 1, 1, 2]) {
                    s.push(rng.pick(&subs));
                }
                for _ in 0..rng.pick(&[0, 0, 1, 1, 1, 2]) {
                    s.push(rng.pick(&vowels));
                }
                if rng.below(8) == 0 {
                    s.push('\u{f39}');
                }
                if rng.below(6) == 0 {
                    s.push(rng.pick(&finals));
                }
            }
            s.push_str(rng.pick(&separators));
        }
        assert_round_trip(&s);
    }
}

// Any chars, ill-formed included: no panics.
#[test]
fn ute_arbitrary_input() {
    let mut alphabet: Vec<char> = ('\u{0f00}'..='\u{0fff}').collect();
    alphabet.extend("abcuU[]\\-~+./_ 0123\n,ж😀\u{200b}".chars());

    let mut rng = Rng(0x2545_F491_4F6C_DD1D);

    for _ in 0..20_000 {
        let s: String = (0..rng.below(14)).map(|_| rng.pick(&alphabet)).collect();
        let _ = unicode_to_ewts(&s);
    }
}

fn warnings_of(src: &str) -> Vec<(UnicodeWarningKind, usize)> {
    let warnings = unicode_to_ewts(src).warnings;
    warnings.iter().map(|w| (w.kind, w.pos)).collect()
}

#[test]
fn ute_warnings() {
    use UnicodeWarningKind::*;
    let data: &[(&str, &[(UnicodeWarningKind, usize)])] = &[
        ("བཀྲ་ཤིས་བདེ་ལེགས།", &[]),
        ("ཀ\u{0f72}\u{0fb1}", &[(SignOrder, 6)]),
        ("ཀ\u{0f7e}\u{0f39}", &[(SignOrder, 6)]),
        ("ཀ\u{0f39}\u{0f39}", &[(SignOrder, 6)]),
        ("ཀ\u{0f00}", &[(NotEquivalent, 3)]),
        (" \u{0f72}", &[(NoLetter, 1)]),
        ("ཀ\u{0fbe}", &[(NoEwts, 3)]),
        // After a precomposed char of two parts.
        ("\u{0f43} \u{0f72}", &[(NoLetter, 4)]),
        // Both parts of a precomposed vowel sign after a final.
        ("ཀ\u{0f7e}\u{0f73}", &[(SignOrder, 6)]),
        (
            "\u{0f00}\u{0f72} \u{0f00}",
            &[(NotEquivalent, 0), (SignOrder, 3), (NotEquivalent, 7)],
        ),
    ];
    for &(src, expected) in data {
        assert_eq!(warnings_of(src), expected, "src: {src:?}");
    }
}

// Input that does not convert back exactly always gets a warning, and the other way round.
// Precomposed chars are left out: they come back decomposed by design.
#[test]
fn ute_warnings_match_round_trip() {
    let precomposed: Vec<char> = PRECOMPOSED.iter().map(|&(c, _)| c).collect();
    let alphabet: Vec<char> = ('\u{0f00}'..='\u{0fff}').filter(|c| !precomposed.contains(c)).collect();
    let mut rng = Rng(0x9E37_79B9_7F4A_7C15);

    for _ in 0..100_000 {
        let s: String = (0..=rng.below(5)).map(|_| rng.pick(&alphabet)).collect();
        let UnicodeToEwts { ewts, warnings } = unicode_to_ewts(&s);
        let exact = crate::ewts_to_unicode(&ewts).unicode == s;
        let lossy = warnings.iter().any(|w| w.kind.is_lossy());
        assert_eq!(exact, !lossy, "src: {s:?}, ewts: {ewts:?}, warnings: {warnings:?}");

        // Every escape, except symbols that would merge with the previous one ("//"), is a sign with no letter or a
        // char with no EWTS.
        let escaped = ewts
            .split("\\u")
            .skip(1)
            .filter_map(|rest| u32::from_str_radix(&rest[..4], 16).ok().and_then(char::from_u32))
            .filter(|&c| !matches!(super::MAPS.sign(c), Some(Sign::Sym(_))))
            .count();
        let reported = (warnings.iter())
            .filter(|w| matches!(w.kind, UnicodeWarningKind::NoLetter | UnicodeWarningKind::NoEwts))
            .count();
        assert_eq!(escaped, reported, "src: {s:?}, ewts: {ewts:?}, warnings: {warnings:?}");
    }
}

// Warning positions point at chars of the source, in order, also after precomposed chars.
#[test]
fn ute_warning_positions() {
    let alphabet: Vec<char> = ('\u{0f00}'..='\u{0fff}').chain("a ".chars()).collect();
    let mut rng = Rng(0x0123_4567_89AB_CDEF);

    for _ in 0..50_000 {
        let s: String = (0..=rng.below(8)).map(|_| rng.pick(&alphabet)).collect();
        let warnings = unicode_to_ewts(&s).warnings;
        for pair in warnings.windows(2) {
            assert!(pair[0].pos <= pair[1].pos, "src: {s:?}, warnings: {warnings:?}");
        }
        for w in &warnings {
            assert!(
                s.is_char_boundary(w.pos) && w.pos < s.len(),
                "src: {s:?}, warnings: {warnings:?}"
            );
            let c = s[w.pos..].chars().next().unwrap();
            assert_eq!(w.ch, c, "src: {s:?}, warning: {w:?}");
            let ok = match w.kind {
                UnicodeWarningKind::NotEquivalent => NOT_EQUIVALENT.contains(&c),
                UnicodeWarningKind::NoEwts => !matches!(c, 'a' | ' '),
                UnicodeWarningKind::NoLetter | UnicodeWarningKind::SignOrder => {
                    super::MAPS.decompose(c).unwrap_or(&[c]).iter().any(|&p| {
                        matches!(
                            super::MAPS.sign(p),
                            Some(Sign::Sub(_) | Sign::Vowel(_) | Sign::Final(_))
                        )
                    })
                }
            };
            assert!(ok, "src: {s:?}, warning: {w:?}");
        }
    }
}

// Any mix of Tibetan, ASCII, apostrophes and other text: the EWTS is valid and, with no lossy warning, converts back to
// the source with precomposed chars decomposed.
#[test]
fn ute_round_trip_mixed_input() {
    let mut alphabet: Vec<char> = ('\u{0f00}'..='\u{0fff}').chain(' '..='~').collect();
    alphabet.extend("\n\t\r\u{2bc}\u{2b9}\u{2018}\u{2019}\u{2be}ж😀\u{200b}".chars());
    let mut rng = Rng(0x5DEE_CE66_D1CE_4E5B);

    for _ in 0..random_iterations(100_000) {
        let s: String = (0..=rng.below(10)).map(|_| rng.pick(&alphabet)).collect();
        let UnicodeToEwts { ewts, warnings } = unicode_to_ewts(&s);
        let back = crate::ewts_to_unicode(&ewts);
        // A final sign repeated in the source is repeated in the EWTS too.
        let unexpected = (back.warnings.iter()).any(|w| w.kind != crate::EwtsWarningKind::RepeatedFinal);
        assert!(!unexpected, "src: {s:?}, ewts: {ewts:?}, back: {back:?}");

        let decomposed: String = (s.chars())
            .flat_map(|c| super::MAPS.decompose(c).map_or_else(|| vec![c], <[char]>::to_vec))
            .collect();
        if !warnings.iter().any(|w| w.kind.is_lossy()) {
            assert_eq!(
                back.unicode, decomposed,
                "src: {s:?}, ewts: {ewts:?}, warnings: {warnings:?}"
            );
        }
    }
}