ewts 1.0.0

Converter between EWTS (Extended Wylie Transliteration Scheme) and Tibetan Unicode symbols (lib)
Documentation
use super::{RawWarnings, UnicodeToEwtsMaps, UnicodeWarningKind};
use crate::dict::{Con, ConSpec, Final, Sign, Vowel};
use crate::util::{can_prefix, can_suffix2, is_root_first, is_standard_pair, is_standard_triple, is_suffix};

fn plus() -> &'static str {
    ConSpec::Plus.get().0
}

// Usually one vowel; more only with "+" ("e+e"), so they go to the heap.
#[derive(Default)]
struct Vowels {
    first: Option<Vowel>,
    rest: Vec<Vowel>,
}

impl Vowels {
    fn is_empty(&self) -> bool {
        self.first.is_none()
    }

    fn push(&mut self, v: Vowel) {
        match self.first {
            None => self.first = Some(v),
            Some(_) => self.rest.push(v),
        }
    }

    fn last_mut(&mut self) -> Option<&mut Vowel> {
        self.rest.last_mut().or(self.first.as_mut())
    }

    fn iter(&self) -> impl Iterator<Item = Vowel> + '_ {
        self.first.iter().chain(&self.rest).copied()
    }
}

#[derive(Default)]
struct Stack {
    // Letters from top to bottom, e.g. ["r", "g", "y"]; empty for a bare a-chen with a vowel ("i" for "ཨི").
    cons: Vec<Con>,
    vowels: Vowels,
    finals: Vec<Final>,
    tsa_phru: bool,
    // A prefix, suffix or 2nd suffix: takes no `a`.
    affix: bool,
    dot: bool,
}

impl Stack {
    // A single letter with nothing attached: a candidate for a prefix or a suffix.
    fn single_cons(&self) -> Option<Con> {
        match self.cons[..] {
            [c] if !self.tsa_phru && self.vowels.is_empty() && self.finals.is_empty() => Some(c),
            _ => None,
        }
    }

    // Empty `cons` is an a-chen with a vowel.
    fn starts_with_a_chen(&self) -> bool {
        self.cons.first().is_none_or(|&c| c == Con::AChen)
    }
}

#[inline]
fn parse_stack(maps: &UnicodeToEwtsMaps, chars: &[char], mut i: usize, warnings: &mut RawWarnings) -> (Stack, usize) {
    let mut st = Stack::default();
    // Signs after the letter are written out in this order: subjoined letters, vowels, tsa-phru, other finals.
    let mut max_rank = 0;

    if let Some(Sign::Base(e)) = maps.sign(chars[i]) {
        st.cons.push(e);
    }
    i += 1;

    while let Some(&c) = chars.get(i) {
        let mut repeated = false;
        let rank = match maps.sign(c) {
            Some(Sign::Sub(e)) => {
                st.cons.push(e);
                0
            }
            Some(Sign::Vowel(v)) => {
                match (st.vowels.last_mut(), long_vowel(c)) {
                    (Some(prev @ Vowel::ABig), Some(long)) => *prev = long,
                    _ => st.vowels.push(v),
                }
                1
            }
            Some(Sign::Final(Final::TsaPhru)) => {
                repeated = st.tsa_phru;
                st.tsa_phru = true;
                2
            }
            Some(Sign::Final(f)) => {
                st.finals.push(f);
                3
            }
            _ => break,
        };
        if rank < max_rank || repeated {
            warnings.push((UnicodeWarningKind::SignOrder, i));
        }
        max_rank = max_rank.max(rank);
        i += 1;
    }

    // "ཨི" is written "i": a vowel without a letter gets a-chen.
    if st.cons == [Con::AChen] && !st.vowels.is_empty() {
        st.cons.clear();
    }

    // "ph^" is "f", "b^" is "v".
    if st.tsa_phru {
        let fv = match st.cons[..] {
            [Con::Ph] => Some(Con::F),
            [Con::B] => Some(Con::V),
            _ => None,
        };
        if let Some(fv) = fv {
            st.cons[0] = fv;
            st.tsa_phru = false;
        }
    }

    (st, i)
}

// `A` (U+0F71) followed by another vowel sign is a single EWTS vowel: `I`, `U`, `-I`.
#[inline]
fn long_vowel(second: char) -> Option<Vowel> {
    let a_long = Vowel::ABig.get().1;
    Vowel::list().iter().copied().find(|v| {
        v.get()
            .1
            .strip_prefix(a_long)
            .is_some_and(|rest| rest.chars().eq([second]))
    })
}

// `#[inline]` here and on the other functions called once per stack or syllable keeps them in the main loop
// function; without it the conversion gets 5-10% slower, depending on how the crate is split for codegen.
#[inline]
pub(super) fn push_tsekbar(
    maps: &UnicodeToEwtsMaps,
    chars: &[char],
    mut i: usize,
    out: &mut String,
    warnings: &mut RawWarnings,
) -> usize {
    let mut stacks = Vec::new();
    loop {
        let (st, next) = parse_stack(maps, chars, i, warnings);
        i = next;
        let visarga = st.finals.contains(&Final::Visarga);
        stacks.push(st);
        // A visarga ends the syllable: "duHkha" is "duH" + "kha".
        if visarga || !matches!(chars.get(i).and_then(|&c| maps.sign(c)), Some(Sign::Base(_))) {
            break;
        }
    }

    mark_affixes(&mut stacks);

    for st in &stacks {
        push_stack(st, out);
    }
    i
}

// Marks prefixes and suffixes: they take no `a`, every other letter without a vowel does.
// "mkhan": m (prefix) kha n (suffix); "sarba", "karma": sa rba, ka rma.
#[inline]
fn mark_affixes(stacks: &mut [Stack]) {
    let n = stacks.len();
    let last = n - 1;
    let (mut prefix, mut suffix, mut suffix2_pair) = (false, false, false);

    if n > 1 {
        if let Some(p) = stacks[0].single_cons() {
            prefix = can_prefix(p, &stacks[1].cons);
        }
        if let Some(s) = stacks[last].single_cons() {
            suffix = is_suffix(s);
        }
    }

    if n > 2
        && let (Some(s1), Some(s2)) = (stacks[last - 1].single_cons(), stacks[last].single_cons())
    {
        suffix2_pair = is_suffix(s1) && can_suffix2(s2, s1);
    }

    // Two letters that could be prefix and suffix: the first is the root ("dag").
    if n == 2 && prefix && suffix {
        prefix = false;
    }

    // Three letters that could be prefix, suffix and 2nd suffix: the middle one is the root ("dgas"), with exceptions ("bags").
    if n == 3 && prefix && suffix2_pair {
        let letters = [0, 1, 2].map(|k| stacks[k].cons[0]);
        if is_root_first(&letters) {
            prefix = false;
        } else {
            suffix2_pair = false;
        }
    }

    // "g.yon": the prefix and the root could be read as one stack.
    // A root written with "+" stacks its first letter under the prefix too: "g.y+w".
    if prefix {
        let (prefix, root) = (&stacks[0].cons, &stacks[1].cons);
        stacks[0].dot =
            is_standard_joined(prefix, root) || (!is_plain_stack(root) && is_standard_joined(prefix, &root[..1]));
    }

    // "r.d", "l.d" for a suffix and a 2nd suffix.
    if suffix2_pair {
        stacks[last - 1].dot = is_standard_joined(&stacks[last - 1].cons, &stacks[last].cons);
    }

    stacks[0].affix = prefix;
    stacks[last].affix |= suffix || suffix2_pair;
    if suffix2_pair {
        stacks[last - 1].affix = true;
    }

    // "ka.i": a lone a-chen with a vowel is written as the vowel, otherwise it would read "kai".
    // "a.a": an a-chen right after a letter ending with a-chen would be read as its vowel.
    // An a-chen with subjoined letters is written as a letter, "kaa+k", and needs no dot.
    for k in 1..n {
        let prev = &stacks[k - 1];
        let prev_ends_with_a_chen =
            prev.cons.last() == Some(&Con::AChen) && prev.vowels.is_empty() && prev.finals.is_empty() && !prev.tsa_phru;
        let written_as_vowel = stacks[k].cons.len() <= 1 && !stacks[k].vowels.is_empty();
        if stacks[k].starts_with_a_chen() && (written_as_vowel || prev_ends_with_a_chen) {
            stacks[k - 1].dot = true;
        }
    }
}

#[inline]
fn push_stack(st: &Stack, out: &mut String) {
    let sep = if is_plain_stack(&st.cons) { "" } else { plus() };
    for (k, c) in st.cons.iter().enumerate() {
        if k > 0 {
            out.push_str(sep);
        }
        out.push_str(c.get().0);
    }

    if !st.vowels.is_empty() {
        // "c+a+i": after a subjoined a-chen, "+ai" would be read as the "ai" vowel.
        if st.cons.last() == Some(&Con::AChen) {
            out.push_str(plus());
        }
        for (k, v) in st.vowels.iter().enumerate() {
            if k > 0 {
                out.push_str(plus());
            }
            out.push_str(v.get().0);
        }
    } else if !st.affix && st.cons.last() != Some(&Con::AChen) {
        out.push_str(Con::AChen.get().0);
    }

    // Unicode canonical order puts tsa-phru after vowel signs.
    if st.tsa_phru {
        out.push_str(Final::TsaPhru.get().0);
    }
    st.finals.iter().for_each(|f| out.push_str(f.get().0));

    if st.dot {
        out.push_str(ConSpec::Period.get().0);
    }
}

// A stack written without "+": a single letter or a standard Tibetan stack.
fn is_plain_stack(cons: &[Con]) -> bool {
    cons.len() <= 1 || is_standard_stack(cons)
}

// Stacks the forward converter builds from plain letters, e.g. "rgy": from SUPERSCRIPTS and SUBSCRIPTS.
fn is_standard_stack(cons: &[Con]) -> bool {
    match *cons {
        [top, bottom] => is_standard_pair(top, bottom),
        [top, middle, bottom] => is_standard_triple(top, middle, bottom),
        _ => false,
    }
}

// Whether `top` and `bottom` written as one stack would be a standard one.
fn is_standard_joined(top: &[Con], bottom: &[Con]) -> bool {
    let n = top.len() + bottom.len();
    if n > 3 {
        return false;
    }
    let mut joined = [Con::K; 3];
    joined[..top.len()].copy_from_slice(top);
    joined[top.len()..n].copy_from_slice(bottom);
    is_standard_stack(&joined[..n])
}