ewts 1.0.0

Converter between EWTS (Extended Wylie Transliteration Scheme) and Tibetan Unicode symbols (lib)
Documentation
use crate::dict::{Final, Syntax};
use crate::tokenizer::{EwtsToUnicodeTokenizer, Token, TokenType};
use std::fmt;

/// What is wrong in the input of [`ewts_to_unicode`](crate::ewts_to_unicode).
///
/// New kinds may be added in minor versions.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EwtsWarningKind {
    /// An ASCII char that means nothing in EWTS, copied as is: `q`, `,`, a `]` with no `[`.
    NotEwts,
    /// A backslash with nothing after it, or a `\u` / `\U` without 4 / 8 hex digits; copied as is.
    BadEscape,
    /// A `[` with no `]`: the rest of the input is non-Tibetan text.
    UnclosedBracket,
    /// A `.` that is neither between two letters nor before a vowel; it does nothing.
    StrayDot,
    /// The same final sign twice in a row: `ka^^`, `kaMM`.
    RepeatedFinal,
}

impl fmt::Display for EwtsWarningKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(match self {
            EwtsWarningKind::NotEwts => "not EWTS",
            EwtsWarningKind::BadEscape => "bad escape",
            EwtsWarningKind::UnclosedBracket => "unclosed bracket",
            EwtsWarningKind::StrayDot => "stray dot",
            EwtsWarningKind::RepeatedFinal => "repeated final",
        })
    }
}

/// A problem in the input of [`ewts_to_unicode`](crate::ewts_to_unicode).
///
/// ```
/// use ewts::EwtsWarningKind;
///
/// let src = "ka \\u0fzz";
/// let warning = ewts::ewts_to_unicode(src).warnings[0];
///
/// assert_eq!(warning.kind, EwtsWarningKind::BadEscape);
/// assert_eq!(warning.pos, 3);
/// assert_eq!(warning.ch, '\\');
/// assert_eq!(&src[warning.pos..warning.pos + warning.len], "\\u0fzz");
/// assert_eq!(warning.to_string(), "bad escape at byte 3: '\\\\'");
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct EwtsWarning {
    /// What is wrong.
    pub kind: EwtsWarningKind,
    /// Byte offset in the source string.
    pub pos: usize,
    /// The char at `pos`.
    pub ch: char,
    /// Byte length of the fragment the warning is about, `&src[pos..pos + len]`: the char for
    /// [`NotEwts`](EwtsWarningKind::NotEwts) and [`StrayDot`](EwtsWarningKind::StrayDot), the whole sign for
    /// [`RepeatedFinal`](EwtsWarningKind::RepeatedFinal), the backslash with the `u` / `U` and up to 4 / 8 letters
    /// or digits after it for [`BadEscape`](EwtsWarningKind::BadEscape), the rest of the input for
    /// [`UnclosedBracket`](EwtsWarningKind::UnclosedBracket).
    pub len: usize,
}

/// "not EWTS at byte 1: 'q'".
impl fmt::Display for EwtsWarning {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{} at byte {}: {:?}", self.kind, self.pos, self.ch)
    }
}

// Warnings found while tokenizing and converting. A warning points at a token and a byte offset inside it;
// the byte positions of the tokens are looked up only when there are warnings.
#[derive(Default)]
pub(crate) struct EwtsWarnings(Vec<(EwtsWarningKind, usize, usize)>);

impl EwtsWarnings {
    pub(crate) fn check_bracket(&mut self, token: usize, depth: usize) {
        if depth > 0 {
            self.push(EwtsWarningKind::UnclosedBracket, token, 0);
        }
    }

    pub(crate) fn check_other_ascii(&mut self, token: usize, b: u8) {
        if b == Syntax::Escape.get() {
            self.push(EwtsWarningKind::BadEscape, token, 0);
        } else if !b.is_ascii_whitespace() {
            self.push(EwtsWarningKind::NotEwts, token, 0);
        }
    }

    // A bad escape at `offset` in a "[...]" token.
    pub(crate) fn bad_escape_in_bracket(&mut self, token: usize, offset: usize) {
        self.push(EwtsWarningKind::BadEscape, token, offset);
    }

    pub(crate) fn check_dot(&mut self, token: usize, prev: &TokenType, next: Option<&Token>) {
        // Between letters it keeps them from stacking ("g.ya"); before a vowel it starts a syllable with a-chen
        // ("ka.i" is not "kai").
        let between_letters = *prev == TokenType::Con && matches!(next, Some(Token::Con(_)));
        if !between_letters && !matches!(next, Some(Token::Vowel(_))) {
            self.push(EwtsWarningKind::StrayDot, token, 0);
        }
    }

    pub(crate) fn check_final(&mut self, token: usize, f: Final, prev: Option<&Token>) {
        if prev == Some(&Token::Final(f)) {
            self.push(EwtsWarningKind::RepeatedFinal, token, 0);
        }
    }

    fn push(&mut self, kind: EwtsWarningKind, token: usize, offset: usize) {
        self.0.push((kind, token, offset));
    }

    pub(crate) fn into_warnings(self, src: &str) -> Vec<EwtsWarning> {
        if self.0.is_empty() {
            return Vec::new();
        }
        let starts = EwtsToUnicodeTokenizer::token_starts(src);
        let mut warnings: Vec<EwtsWarning> = (self.0.into_iter())
            .map(|(kind, token, offset)| {
                let pos = starts[token] + offset;
                let ch = src[pos..].chars().next().unwrap_or(char::REPLACEMENT_CHARACTER);
                let len = if kind == EwtsWarningKind::BadEscape {
                    bad_escape_len(&src.as_bytes()[pos..])
                } else {
                    starts.get(token + 1).map_or(src.len(), |&next| next) - pos
                };
                EwtsWarning { kind, pos, ch, len }
            })
            .collect();
        // The tokenizer's warnings were collected before the converter's.
        warnings.sort_by_key(|w| w.pos);
        warnings
    }
}

// A backslash, then a "u" / "U" and up to 4 / 8 ASCII letters or digits.
fn bad_escape_len(escape: &[u8]) -> usize {
    match escape.get(1).and_then(|&b| Syntax::unicode_escape_digits(b)) {
        Some(digits) => {
            2 + escape[2..]
                .iter()
                .take(digits)
                .take_while(|b| b.is_ascii_alphanumeric())
                .count()
        }
        None => 1,
    }
}

#[cfg(test)]
mod tests {
    use super::EwtsWarningKind::{BadEscape, NotEwts, RepeatedFinal, StrayDot, UnclosedBracket};
    use super::*;

    // The kind, the byte position and the fragment.
    type Expected<'a> = (EwtsWarningKind, usize, &'a str);

    fn warnings_of(src: &str) -> Vec<Expected<'_>> {
        (crate::ewts_to_unicode(src).warnings.iter())
            .map(|w| {
                let fragment = &src[w.pos..w.pos + w.len];
                assert_eq!(fragment.chars().next(), Some(w.ch), "src: {src:?}");
                (w.kind, w.pos, fragment)
            })
            .collect()
    }

    #[test]
    fn etu_warnings() {
        let data: &[(&str, &[Expected])] = &[
            ("bkra shis bde legs/", &[]),
            ("oM aHhU~M` badz+ra gu ru pad+ma sid+d+hi hU~M`:", &[]),
            ("ka\n\tka\r\n", &[]),
            ("g.ya k+ +a [a [b] \\] c] \\u0f40\\[", &[]),
            ("kqa", &[(NotEwts, 1, "q")]),
            ("a]b", &[(NotEwts, 1, "]")]),
            ("ཀ q", &[(NotEwts, 4, "q")]),
            ("\\u0fzz", &[(BadEscape, 0, "\\u0fzz")]),
            ("\\U00f", &[(BadEscape, 0, "\\U00f")]),
            ("\\u+f40", &[(BadEscape, 0, "\\u")]),
            ("ka\\", &[(BadEscape, 2, "\\")]),
            ("[a\\u0fzzb]", &[(BadEscape, 2, "\\u0fzz")]),
            ("[ab\\", &[(UnclosedBracket, 0, "[ab\\"), (BadEscape, 3, "\\")]),
            ("ka [abc", &[(UnclosedBracket, 3, "[abc")]),
            ("[a [b] c", &[(UnclosedBracket, 0, "[a [b] c")]),
            ("[\\]", &[(UnclosedBracket, 0, "[\\]")]),
            (".ka", &[(StrayDot, 0, ".")]),
            ("ka.", &[(StrayDot, 2, ".")]),
            ("ga.ya", &[(StrayDot, 2, ".")]),
            ("ka..ka", &[(StrayDot, 2, "."), (StrayDot, 3, ".")]),
            ("ka^^", &[(RepeatedFinal, 3, "^")]),
            ("kaMM", &[(RepeatedFinal, 3, "M")]),
            ("ka~M`~M`", &[(RepeatedFinal, 5, "~M`")]),
            ("kaMH kaM", &[]),
            ("g.ya ka.i ka.u k.o kaM.o ka?.i", &[]),
        ];
        for &(src, expected) in data {
            assert_eq!(warnings_of(src), expected, "src: {src:?}");
        }
    }
}