ewts 1.0.0

Converter between EWTS (Extended Wylie Transliteration Scheme) and Tibetan Unicode symbols (lib)
Documentation
use crate::dict::{Con, ConSpec, Final, Syntax};
use crate::ewts_warning::{EwtsWarning, EwtsWarnings};
use crate::tokenizer::{EwtsToUnicodeTokenizer, Token, TokenType, TokenizeResult};
use crate::util::{is_standard_bottom, is_standard_pair, is_standard_triple, unicode_escape};

/// The result of [`ewts_to_unicode`](crate::ewts_to_unicode).
#[must_use]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EwtsToUnicode {
    /// The converted text.
    pub unicode: String,
    /// Problems in the source, sorted by position.
    pub warnings: Vec<EwtsWarning>,
}

pub(crate) struct EwtsToUnicodeConverter<'a> {
    src: &'a str,
    ind: usize,
    tokenize_result: &'a TokenizeResult,
    tokens_len: usize,
    prev_type: TokenType,
    // Valid while `prev_type` is `Con`: the previous letter and the one before it, if that is a letter too.
    prev_con: Option<Con>,
    prev2_con: Option<Con>,
    prev_con_combined: bool,
    warnings: EwtsWarnings,
}

impl EwtsToUnicodeConverter<'_> {
    pub(crate) fn convert(src: &str) -> EwtsToUnicode {
        let mut tokenize_result = EwtsToUnicodeTokenizer::tokenize(src);
        let warnings = std::mem::take(&mut tokenize_result.warnings);
        let converter = EwtsToUnicodeConverter {
            src,
            ind: 0,
            tokenize_result: &tokenize_result,
            tokens_len: tokenize_result.tokens.len(),
            prev_type: TokenType::Other,
            prev_con: None,
            prev2_con: None,
            prev_con_combined: false,
            warnings,
        };

        converter.run()
    }

    fn run(mut self) -> EwtsToUnicode {
        let mut result = String::with_capacity(self.tokens_len * 3);

        let a_chen_tib_str = Con::AChen.get().1;
        let tsa_phru_tib_str = Final::TsaPhru.get().1;
        let mut str_ranges = self.tokenize_result.non_tibetan_str_ranges.iter();
        let mut chars = self.tokenize_result.non_tibetan_chars.iter();

        self.tokenize_result.tokens.iter().for_each(|tkn| {
            match tkn {
                Token::Con(c) => 'con: {
                    let tuple = c.get();

                    let mut curr_prev_con_combined = false;
                    let prev_con = if self.prev_type == TokenType::Con {
                        self.prev_con
                    } else {
                        None
                    };

                    if let Some(prev) = prev_con {
                        if c.is_a_chen() {
                            self.prev_type = TokenType::Vowel;
                            self.prev_con_combined = false;
                            break 'con;
                        }

                        if self.is_lower_form(prev, *c) {
                            result.push_str(tuple.2);
                            curr_prev_con_combined = true;
                        } else {
                            result.push_str(tuple.1);
                        }
                    } else if self.prev_type == TokenType::Plus {
                        result.push_str(tuple.2);
                        curr_prev_con_combined = true;
                    } else {
                        result.push_str(tuple.1);
                    }

                    self.prev2_con = prev_con;
                    self.prev_con = Some(*c);
                    self.prev_con_combined = curr_prev_con_combined;
                    self.prev_type = TokenType::Con;
                }
                Token::Vowel(v) => {
                    let attaches_to_prev = matches!(self.prev_type, TokenType::Con | TokenType::Plus);
                    let vowel = v.get().1;

                    if !attaches_to_prev {
                        result.push_str(a_chen_tib_str);
                        result.push_str(vowel);
                    } else if result.ends_with(tsa_phru_tib_str) {
                        result.insert_str(result.len() - tsa_phru_tib_str.len(), vowel);
                    } else {
                        result.push_str(vowel);
                    }
                    self.prev_type = TokenType::Vowel;
                }
                Token::Sym(t) => {
                    result.push_str(t.get().1);
                    self.prev_type = TokenType::Other;
                }
                Token::ConSpec(s) => self.push_con_spec(*s, &mut result),
                Token::Final(f) => {
                    let prev = self.ind.checked_sub(1).map(|i| &self.tokenize_result.tokens[i]);
                    self.warnings.check_final(self.ind, *f, prev);
                    result.push_str(f.get().1);
                    self.prev_type = TokenType::Other;
                }
                Token::OtherAscii(u) => {
                    self.warnings.check_other_ascii(self.ind, *u);
                    result.push(*u as char);
                    self.prev_type = TokenType::Other;
                }
                Token::NonTibetanStr => {
                    if let Some(range) = str_ranges.next() {
                        // Offsets in the text of "[...]" are one byte after the "[".
                        let token = self.ind;
                        push_unescaped(&mut result, &self.src[range.clone()], |at| {
                            self.warnings.bad_escape_in_bracket(token, 1 + at);
                        });
                    }
                    self.prev_type = TokenType::Other;
                }
                Token::NonTibetanChar => {
                    if let Some(ch) = chars.next() {
                        result.push(*ch);
                    }
                    self.prev_type = TokenType::Other;
                }
            }
            self.ind += 1;
        });

        //println!("tokens_len {} -- results_len {} ", self.tokens_len, result.len());
        EwtsToUnicode {
            unicode: result,
            warnings: self.warnings.into_warnings(self.src),
        }
    }

    // A "+" joins only a letter or vowel to a letter or vowel; otherwise it is kept as is.
    // A "." keeps the letters around it from stacking or starts a syllable with a-chen before a vowel.
    fn push_con_spec(&mut self, s: ConSpec, result: &mut String) {
        let next = self.tokenize_result.tokens.get(self.ind + 1);
        if s.is_plus()
            && matches!(self.prev_type, TokenType::Con | TokenType::Vowel)
            && matches!(next, Some(Token::Con(_) | Token::Vowel(_)))
        {
            self.prev_type = TokenType::Plus;
        } else if s.is_plus() {
            result.push_str(s.get().0);
            self.prev_type = TokenType::Other;
        } else {
            self.warnings.check_dot(self.ind, &self.prev_type, next);
            self.prev_type = TokenType::Dot;
        }
    }

    // Whether `cur` goes under `prev`: "rk", "rky", "k+sm"; in "brl" the "b" is a prefix and "rl" a stack.
    fn is_lower_form(&self, prev: Con, cur: Con) -> bool {
        if !self.prev_con_combined && is_standard_pair(prev, cur) {
            // A next letter that can be a bottom but makes no triple with `prev` + `cur` makes `prev` a prefix.
            self.get_con_at(self.ind + 1)
                .is_none_or(|next| next.is_a_chen() || !is_standard_bottom(next) || is_standard_triple(prev, cur, next))
        } else {
            self.prev2_con.map_or(is_standard_pair(prev, cur), |prev2| {
                is_standard_triple(prev2, prev, cur)
            })
        }
    }

    fn get_con_at(&self, ind: usize) -> Option<Con> {
        self.tokenize_result.tokens.get(ind).map(|tkn| tkn.get_con())?
    }
}

// Text of "[...]": "\]" is a "]", "\u0f40" is "ཀ"; a bad "\u" escape or a backslash at the end is kept as is
// and its offset passed to `on_bad_escape`.
fn push_unescaped(out: &mut String, text: &str, mut on_bad_escape: impl FnMut(usize)) {
    let escape = Syntax::Escape.get() as char;
    let mut k = 0;
    while let Some(pos) = text[k..].find(escape) {
        out.push_str(&text[k..k + pos]);
        let at = k + pos;
        let rest = &text[at + 1..];
        k = at + 1;
        if let Some((ch, n)) = unicode_escape(rest.as_bytes()) {
            out.push(ch);
            k += n;
        } else if let Some(ch) = rest.chars().next()
            && !Syntax::is_unicode_escape_start(ch)
        {
            out.push(ch);
            k += ch.len_utf8();
        } else {
            on_bad_escape(at);
            out.push(escape);
        }
    }
    out.push_str(&text[k..]);
}