garage44.eu/jeroen/pinnacle

logclone: git clone https://garage44.eu/jeroen/pinnacle.git

.. /speech/src/rules.rs

raw

//! Letter-to-sound rules: how a spelling is read, a few letters at a time.
//!
//! A rule is written `left[letters]right=sounds`: the letters in brackets
//! are read as the sounds after `=` when what stands before them matches
//! `left` and what follows matches `right`. The rules are tried in their
//! order and the first that fits wins, so a list puts its special cases
//! before its general ones and ends each letter with the plain reading of
//! that letter alone. This is the scheme of the Naval Research Laboratory's
//! English rules of 1976, which a small machine could run; the rules here
//! are this crate's own.
//!
//! The contexts may hold letters, and these signs for kinds of letter:
//!
//! - ` ` the edge of the word
//! - `#` one or more vowels
//! - `:` any number of consonants, none included
//! - `*` one or more consonants
//! - `^` exactly one consonant, x not counted (it is two sounds, k s)
//! - `.` one voiced consonant: b d g j l m n r v w z
//! - `+` one front vowel: e i y
//! - `&` a hissing sound: s c g z x j, or ch sh
//! - `@` a consonant after which "u" is said without a "y": t s r d l z n
//!   j, or th ch sh
//! - `%` an ending: -e -ed -er -es -ely -ing, ending the word
//! - `$` (after the letters only) two or three consonants that can begin a
//!   syllable together, such as bl, tr, st, spr, sch: what follows a Dutch
//!   prefix ("be-stand", "ge-sprek"), as against the double consonant
//!   after a short vowel ("bel-len")
//!
//! The vowels are a e i o u y. A sign matches greedily and never gives back
//! what it took, as in the original scheme: rules are written knowing it.

use alloc::string::String;
use alloc::vec::Vec;

struct Rule<'a> {
    left: &'a [u8],
    letters: &'a [u8],
    right: &'a [u8],
    sounds: &'a str,
}

fn parse(rule: &str) -> Option<Rule<'_>> {
    let open = rule.find('[')?;
    let close = rule.find(']')?;
    let equals = rule.find('=')?;
    if close < open + 2 || equals < close {
        return None;
    }
    let b = rule.as_bytes();
    Some(Rule {
        left: &b[..open],
        letters: &b[open + 1..close],
        right: &b[close + 1..equals],
        sounds: &rule[equals + 1..],
    })
}

fn letter(c: u8) -> bool {
    c.is_ascii_lowercase()
}

fn vowel(c: u8) -> bool {
    matches!(c, b'a' | b'e' | b'i' | b'o' | b'u' | b'y')
}

fn consonant(c: u8) -> bool {
    letter(c) && !vowel(c)
}

/// A consonant that is one sound: not x, which is said k s.
fn single(c: u8) -> bool {
    consonant(c) && c != b'x'
}

fn voiced(c: u8) -> bool {
    matches!(
        c,
        b'b' | b'd' | b'g' | b'j' | b'l' | b'm' | b'n' | b'r' | b'v' | b'w' | b'z'
    )
}

fn front(c: u8) -> bool {
    matches!(c, b'e' | b'i' | b'y')
}

fn hissing(c: u8) -> bool {
    matches!(c, b's' | b'c' | b'g' | b'z' | b'x' | b'j')
}

fn plain_u_after(c: u8) -> bool {
    matches!(c, b't' | b's' | b'r' | b'd' | b'l' | b'z' | b'n' | b'j')
}

/// The pairs `&` and `@` take as one sound.
fn pair(a: u8, b: u8, with_th: bool) -> bool {
    matches!((a, b), (b'c', b'h') | (b's', b'h')) || (with_th && (a, b) == (b't', b'h'))
}

const ENDINGS: [&[u8]; 6] = [b"ing", b"ely", b"er", b"es", b"ed", b"e"];

/// The clusters `$` matches, the longer before the shorter they begin.
const ONSETS: [&[u8]; 36] = [
    b"schr", b"sch", b"spr", b"str", b"spl", b"skr", b"bl", b"br", b"dr", b"dw", b"fl", b"fr", b"gl", b"gr",
    b"gn", b"kl", b"kn", b"kr", b"kw", b"pl", b"pr", b"tr", b"tw", b"vl", b"vr", b"wr", b"zw", b"sk", b"sl",
    b"sm", b"sn", b"sp", b"st", b"sw", b"ch", b"th",
];

/// Whether `pattern` matches the word leftwards from before its letter
/// `end`, where the rule's own letters begin.
fn left_fits(pattern: &[u8], word: &[u8], end: usize) -> bool {
    // `p` counts the letters still to the left, so 0 is the word's start,
    // and `at(p)` is the letter just left of there.
    let mut p = end;
    let at = |p: usize| if p == 0 { b' ' } else { word[p - 1] };
    for &c in pattern.iter().rev() {
        match c {
            b' ' => {
                if letter(at(p)) {
                    return false;
                }
                p = p.saturating_sub(1);
            }
            b'#' | b'*' => {
                let kind: fn(u8) -> bool = if c == b'#' { vowel } else { consonant };
                let from = p;
                while p > 0 && kind(at(p)) {
                    p -= 1;
                }
                if p == from {
                    return false;
                }
            }
            b':' => {
                while p > 0 && consonant(at(p)) {
                    p -= 1;
                }
            }
            b'&' | b'@' => {
                let single = if c == b'&' {
                    hissing(at(p))
                } else {
                    plain_u_after(at(p))
                };
                if p >= 2 && pair(at(p - 1), at(p), c == b'@') {
                    p -= 2;
                } else if p > 0 && single {
                    p -= 1;
                } else {
                    return false;
                }
            }
            _ => {
                let fits = match c {
                    b'^' => single(at(p)),
                    b'.' => voiced(at(p)),
                    b'+' => front(at(p)),
                    _ => at(p) == c,
                };
                if p == 0 || !fits {
                    return false;
                }
                p -= 1;
            }
        }
    }
    true
}

/// Whether `pattern` matches the word rightwards from `at`, the letter just
/// after the rule's own letters.
fn right_fits(pattern: &[u8], word: &[u8], at: usize) -> bool {
    let mut p = at;
    let at = |p: usize| word.get(p).copied().unwrap_or(b' ');
    for &c in pattern {
        match c {
            b' ' => {
                if letter(at(p)) {
                    return false;
                }
                p += 1;
            }
            b'#' | b'*' => {
                let kind: fn(u8) -> bool = if c == b'#' { vowel } else { consonant };
                let from = p;
                while kind(at(p)) {
                    p += 1;
                }
                if p == from {
                    return false;
                }
            }
            b':' => {
                while consonant(at(p)) {
                    p += 1;
                }
            }
            b'%' => {
                let rest = word.get(p..).unwrap_or(&[]);
                let ending = ENDINGS
                    .iter()
                    .find(|e| rest.starts_with(e) && !letter(at(p + e.len())));
                match ending {
                    Some(e) => p += e.len(),
                    None => return false,
                }
            }
            b'$' => {
                let rest = word.get(p..).unwrap_or(&[]);
                match ONSETS.iter().find(|o| rest.starts_with(o)) {
                    Some(o) => p += o.len(),
                    None => return false,
                }
            }
            b'&' | b'@' => {
                let single = if c == b'&' {
                    hissing(at(p))
                } else {
                    plain_u_after(at(p))
                };
                if pair(at(p), at(p + 1), c == b'@') {
                    p += 2;
                } else if single {
                    p += 1;
                } else {
                    return false;
                }
            }
            _ => {
                let fits = match c {
                    b'^' => single(at(p)),
                    b'.' => voiced(at(p)),
                    b'+' => front(at(p)),
                    _ => at(p) == c,
                };
                if !fits {
                    return false;
                }
                p += 1;
            }
        }
    }
    true
}

/// `word`, lowercase letters a to z only, read by `rules` into the crate's
/// symbols (with the marks [`crate::phonemes::sounds`] understands). A
/// letter no rule reads is silent.
pub fn read(word: &str, rules: &[&str]) -> String {
    let word = word.as_bytes();
    let parsed: Vec<Rule<'_>> = rules.iter().filter_map(|r| parse(r)).collect();
    let mut out = String::new();
    let mut i = 0;
    while i < word.len() {
        let fits = parsed.iter().find(|r| {
            r.letters[0] == word[i]
                && word[i..].starts_with(r.letters)
                && left_fits(r.left, word, i)
                && right_fits(r.right, word, i + r.letters.len())
        });
        match fits {
            Some(r) => {
                let sounds = r.sounds.trim();
                if !sounds.is_empty() {
                    if !out.is_empty() {
                        out.push(' ');
                    }
                    out.push_str(sounds);
                }
                i += r.letters.len();
            }
            None => i += 1,
        }
    }
    out
}

/// Whether every rule is written as one.
#[cfg(test)]
pub fn all_parse(rules: &[&str]) -> bool {
    rules.iter().all(|r| parse(r).is_some())
}

#[cfg(test)]
mod tests {
    use super::*;

    const RULES: &[&str] = &[
        " [a] =A", "[a]^%=eI", "#:[e] =", "[a]={", "[ch]=tS", "[c]+=s", "[c]=k", "[e]=E", "[k]=k", "[m]=m",
        "[t]=t", "[s]=s",
    ];

    #[test]
    fn contexts() {
        assert_eq!(read("make", RULES), "m eI k");
        assert_eq!(read("mat", RULES), "m { t");
        assert_eq!(read("a", RULES), "A");
        assert_eq!(read("cat", RULES), "k { t");
        assert_eq!(read("ace", RULES), "eI s");
        assert_eq!(read("match", RULES), "m { t tS");
        assert_eq!(read("makes", RULES), "m eI k E s");
        assert_eq!(read("q", RULES), "");
        assert!(all_parse(RULES));
        assert!(!all_parse(&["a=b"]));
    }
}