Cotton code
182 lines · 7.3 KB · RustRaw
//! A command said aloud: the words a definition gives a command so a line//! spoken to Home runs it ("order my usual from Paradise", "order a chicken//! biryani from Paradise to home"). The definition names the words; this//! reads a line against them and hands back the names it heard. Which//! records those names are is the caller's to resolve, and a line that does//! not read whole is not the command — it stays a thought.use serde::{Deserialize, Serialize};/// How a command is said: `verbs` start the line, the record of the/// command's own table is named after `record`, a picked record after/// `pick`, and the words between the verb and `record` are `counted`.#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]pub struct CommandSpoken {    pub verbs: Vec<String>,    pub record: String,    #[serde(default, skip_serializing_if = "Option::is_none")]    pub pick: Option<String>,    /// A line may leave the picked record unsaid, and the verb answers for    /// it from the person's own records (Request food: where the    /// restaurant's usual, else its last order, went).    #[serde(default, skip_serializing_if = "Option::is_none")]    pub pick_unsaid: Option<bool>,    #[serde(default, skip_serializing_if = "Option::is_none")]    pub counted: Option<SpokenCounted>,}/// Words read as counted names ("a chicken biryani and two naans") into the/// command's `argument`; a line saying one of `absent` ("my usual") sends no/// argument at all.#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]pub struct SpokenCounted {    pub argument: String,    #[serde(default)]    pub absent: Vec<String>,}/// What a line said, by name.#[derive(Debug, Clone, PartialEq, Eq)]pub struct Heard {    pub record: String,    pub pick: Option<String>,    /// `None` when the command counts nothing or the line said `absent`.    pub counted: Option<Vec<Counted>>,}#[derive(Debug, Clone, PartialEq, Eq, Serialize)]pub struct Counted {    pub name: String,    pub quantity: u32,}/// Words around a command that say nothing themselves.const FILLER: [&str; 8] = ["please", "can", "could", "would", "you", "kindly", "hey", "just"];/// Words before a name that are not the name ("to my home", "from the deli").const ARTICLES: [&str; 3] = ["my", "the", "our"];fn tokens(line: &str) -> Vec<String> {    let mut said = Vec::new();    let mut word = String::new();    for character in line.to_lowercase().chars() {        if character.is_alphanumeric() || character == '\'' || character == '’' {            word.push(character);            continue;        }        if !word.is_empty() {            said.push(std::mem::take(&mut word));        }        if character == ',' {            said.push(",".into());        }    }    if !word.is_empty() {        said.push(word);    }    said}fn quantity(word: &str) -> Option<u32> {    const WORDS: [&str; 11] = ["a", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten"];    if word == "an" {        return Some(1);    }    if let Some(at) = WORDS.iter().position(|w| *w == word) {        return Some(at.max(1) as u32);    }    word.parse().ok().filter(|n| *n > 0)}fn name(words: &[String]) -> Option<String> {    let start = words.iter().take_while(|w| ARTICLES.contains(&w.as_str())).count();    let said = words[start..].iter().filter(|w| *w != ",").cloned().collect::<Vec<_>>().join(" ");    (!said.is_empty()).then_some(said)}fn counted(words: &[String]) -> Option<Vec<Counted>> {    let mut items = Vec::new();    for chunk in words.split(|w| w == "and" || w == ",").filter(|chunk| !chunk.is_empty()) {        let (quantity, rest) = match quantity(&chunk[0]) {            Some(n) if chunk.len() > 1 => (n, &chunk[1..]),            _ => (1, chunk),        };        items.push(Counted { name: name(rest)?, quantity });    }    (!items.is_empty()).then_some(items)}/// The line read against `spoken`, or `None` when it is not this command.pub fn hear(spoken: &CommandSpoken, line: &str) -> Option<Heard> {    let mut said = tokens(line);    while said.last().is_some_and(|w| FILLER.contains(&w.as_str()) || w == ",") {        said.pop();    }    let start = said.iter().take_while(|w| FILLER.contains(&w.as_str())).count();    let said = &said[start..];    let verb = spoken.verbs.iter().map(|v| tokens(v)).find(|v| !v.is_empty() && said.starts_with(v))?;    let mut rest = &said[verb.len()..];    if rest.first().is_some_and(|w| w == "me") {        rest = &rest[1..];    }    let record_word = tokens(&spoken.record);    let at = rest.iter().rposition(|w| record_word.first() == Some(w))?;    let (between, after) = (&rest[..at], &rest[at + 1..]);    let (record, pick) = match spoken.pick.as_deref().map(tokens).and_then(|p| p.first().cloned()) {        Some(word) => match after.iter().rposition(|w| *w == word) {            Some(to) => (name(&after[..to])?, Some(name(&after[to + 1..])?)),            None => (name(after)?, None),        },        None => (name(after)?, None),    };    let counted = match &spoken.counted {        None if between.is_empty() => None,        None => return None,        Some(spec) => {            let phrase = between.join(" ");            if spec.absent.iter().any(|absent| tokens(absent).join(" ") == phrase) {                None            } else {                Some(counted(between)?)            }        }    };    Some(Heard { record, pick, counted })}#[cfg(test)]mod tests {    use super::*;    fn food() -> CommandSpoken {        serde_json::from_value(serde_json::json!({            "verbs": ["order"], "record": "from", "pick": "to",            "counted": {"argument": "items", "absent": ["my usual", "the usual", "usual"]}        }))        .unwrap()    }    /// RULE: A spoken command runs only on a line that reads whole against its definition's words — the verb first, a name after the record word — and its counted words are read as name and quantity; anything else stays a thought.    #[test]    fn a_spoken_order_reads_its_names_and_counts() {        let spoken = food();        let usual = hear(&spoken, "Order my usual from Example Kitchen.").unwrap();        assert_eq!(usual, Heard { record: "example kitchen".into(), pick: None, counted: None });        let named = hear(&spoken, "Please order a chicken biryani and two plain naan from Example Kitchen to home").unwrap();        assert_eq!(named.record, "example kitchen");        assert_eq!(named.pick.as_deref(), Some("home"));        assert_eq!(            named.counted.unwrap(),            vec![                Counted { name: "chicken biryani".into(), quantity: 1 },                Counted { name: "plain naan".into(), quantity: 2 }            ]        );        assert_eq!(hear(&spoken, "order 3 rotis from the deli to my office").unwrap().counted.unwrap()[0].quantity, 3);        for thought in ["remember to order from Example Kitchen", "order my usual", "order a dosa from", "order from Example Kitchen to", "Example Kitchen was great"] {            assert!(hear(&spoken, thought).is_none(), "{thought}");        }        let plain = CommandSpoken { counted: None, ..food() };        assert!(hear(&plain, "order a dosa from Example Kitchen").is_none());        assert_eq!(hear(&plain, "order from Example Kitchen").unwrap().record, "example kitchen");    }}