Cotton code
480 lines · 18.5 KB · RustRaw
//! A day and a time read out of one typed or dictated line ("Dinner with//! Rose Thursday 7pm", "dentist next Tue 3", "someday"). What it understood//! comes back for the pill, with the stretches of the line it read as the day//! and the time, so the person can see and correct it (DECISIONS.md: adding//! is one line). The words it knows are data (`when.json`), one entry per//! language; English first.use std::collections::HashMap;use std::sync::OnceLock;use serde::{Deserialize, Serialize};use super::layout::clock;use super::words::{fill, Words};use super::weekday_monday_first;use crate::zoned_clock::{civil_from_days, day_number, days_in_month};#[derive(Debug, Clone, Deserialize)]struct Lexicon {    someday: Vec<String>,    today: Vec<String>,    tomorrow: Vec<String>,    next: Vec<String>,    this: Vec<String>,    weekdays: Vec<Vec<String>>,    months: Vec<Vec<String>>,    ordinals: Vec<String>,    am: Vec<String>,    pm: Vec<String>,    at: Vec<String>,    from: Vec<String>,    until: Vec<String>,    noon: Vec<String>,    midnight: Vec<String>,    dropped: Vec<String>,    /// "for": what leads into a length ("for an hour").    #[serde(default)]    lasting: Vec<String>,    /// "a", "an", "one": one of a unit.    #[serde(default)]    one: Vec<String>,    #[serde(default)]    hours: Vec<String>,    #[serde(default)]    minutes: Vec<String>,    #[serde(default)]    half_hour: Vec<String>,    #[serde(default)]    and_a_half: Vec<String>,}fn lexicon(language: &str) -> &'static Lexicon {    static ALL: OnceLock<HashMap<String, Lexicon>> = OnceLock::new();    let all = ALL.get_or_init(|| {        let raw: serde_json::Map<String, serde_json::Value> = serde_json::from_str(include_str!("when.json")).expect("days/when.json reads");        raw.into_iter()            .filter(|(key, _)| key != "about")            .map(|(key, value)| (key, serde_json::from_value(value).expect("a when entry reads")))            .collect()    });    all.get(language).or_else(|| all.get("en")).expect("days/when.json holds en")}/// One stretch of the line that was read as something.#[derive(Debug, Clone, PartialEq, Eq, Serialize)]pub struct Said {    /// Character offsets into the line, `from..to`.    pub from: usize,    pub to: usize,    pub what: &'static str,}/// What a line says.#[derive(Debug, Clone, PartialEq, Eq, Serialize)]pub struct Understood {    /// The words left once the day and time are taken out.    pub title: String,    /// The day it names, a day number; `None` with `someday` false: no day said.    #[serde(skip)]    pub day: Option<i64>,    /// "someday", "sometime": deliberately no day.    pub someday: bool,    /// Minutes after midnight.    #[serde(skip)]    pub time: Option<i64>,    #[serde(skip)]    pub end: Option<i64>,    pub said: Vec<Said>,}#[derive(Debug, Clone)]struct Token {    text: String,    from: usize,    to: usize,}fn tokenize(line: &str) -> Vec<Token> {    let mut out = Vec::new();    let mut current = String::new();    let mut start = 0;    let chars: Vec<char> = line.chars().collect();    let flush = |current: &mut String, start: usize, end: usize, out: &mut Vec<Token>| {        let text = current.trim_end_matches([',', '!', '?', ';']).to_string();        if !text.is_empty() {            out.push(Token { text: text.to_lowercase(), from: start, to: start + text.chars().count().min(end - start) });        }        current.clear();    };    for (at, c) in chars.iter().enumerate() {        if c.is_whitespace() {            flush(&mut current, start, at, &mut out);            start = at + 1;        } else if (*c == '-' || *c == '–') && !current.is_empty() && current.chars().all(|c| c.is_ascii_digit() || c == ':' || c == '.' || c.is_ascii_alphabetic()) && current.chars().any(|c| c.is_ascii_digit()) {            // "7-9pm": the dash is its own word.            flush(&mut current, start, at, &mut out);            out.push(Token { text: c.to_string(), from: at, to: at + 1 });            start = at + 1;        } else {            if current.is_empty() {                start = at;            }            current.push(*c);        }    }    flush(&mut current, start, chars.len(), &mut out);    out}/// How many tokens from `at` a phrase of the list matches (longest first).fn phrase(tokens: &[Token], at: usize, list: &[String]) -> usize {    let mut best = 0;    for one in list {        let words: Vec<&str> = one.split(' ').collect();        if words.len() > best && at + words.len() <= tokens.len() && words.iter().enumerate().all(|(i, w)| tokens[at + i].text.trim_end_matches('.') == w.trim_end_matches('.')) {            best = words.len();        }    }    best}fn weekday_of(text: &str, lex: &Lexicon) -> Option<usize> {    let text = text.trim_end_matches('.');    lex.weekdays.iter().position(|names| names.iter().any(|name| name == text))}fn month_of(text: &str, lex: &Lexicon) -> Option<i64> {    let text = text.trim_end_matches('.');    lex.months.iter().position(|names| names.iter().any(|name| name == text)).map(|at| at as i64 + 1)}fn date_number(text: &str, lex: &Lexicon) -> Option<i64> {    let digits = lex.ordinals.iter().find_map(|o| text.strip_suffix(o.as_str())).unwrap_or(text);    digits.parse::<i64>().ok().filter(|day| (1..=31).contains(day))}/// A clock: "7", "7pm", "7:30", "7.30pm", "19:00". Answers the hour, the/// minute, whether am/pm was written on it, and whether it was written as a/// 24-hour clock ("07:00", "19:00").fn clock_of(text: &str, lex: &Lexicon) -> Option<(i64, i64, Option<bool>, bool)> {    let mut rest = text;    let mut half = None;    for (list, pm) in [(&lex.am, false), (&lex.pm, true)] {        for word in list.iter().filter(|w| !w.contains(' ')) {            if let Some(cut) = rest.strip_suffix(word.as_str()) {                if !cut.is_empty() {                    rest = cut;                    half = Some(pm);                }            }        }    }    let (hour, minute) = match rest.split_once([':', '.']) {        Some((h, m)) => (h, Some(m)),        None => (rest, None),    };    if hour.is_empty() || hour.len() > 2 || !hour.chars().all(|c| c.is_ascii_digit()) {        return None;    }    let h: i64 = hour.parse().ok()?;    let m: i64 = match minute {        Some(m) if m.len() == 2 && m.chars().all(|c| c.is_ascii_digit()) => m.parse().ok()?,        Some(_) => return None,        None => 0,    };    if m > 59 || h > 23 || (half.is_some() && !(1..=12).contains(&h)) {        return None;    }    let twenty_four = minute.is_some() && (hour.len() == 2 && hour.starts_with('0') || h >= 13);    Some((h, m, half, twenty_four))}/// The minute of the day a clock means. Without am/pm, an hour from 1 to 7/// is the afternoon or evening ("dinner at 7", "dentist Tue 3"), 8 to 11 the/// morning, 12 noon; a 24-hour clock means itself.fn minute_of(hour: i64, minute: i64, half: Option<bool>, twenty_four: bool) -> i64 {    let hour = match half {        Some(true) if hour < 12 => hour + 12,        Some(false) if hour == 12 => 0,        Some(_) => hour,        None if twenty_four => hour,        None if (1..=7).contains(&hour) => hour + 12,        None => hour,    };    hour * 60 + minute}/// Read a line. `today` is the person's today (a day number).pub fn read(line: &str, today: i64, language: &str) -> Understood {    let lex = lexicon(language);    let tokens = tokenize(line);    let mut used = vec![false; tokens.len()];    let mut said = Vec::new();    let mut day: Option<i64> = None;    let mut someday = false;    let mut time: Option<i64> = None;    let mut end: Option<i64> = None;    let mark = |used: &mut Vec<bool>, said: &mut Vec<Said>, from: usize, n: usize, what: &'static str| {        for flag in used.iter_mut().skip(from).take(n) {            *flag = true;        }        // A word that only leads into it ("on", "at", "next") goes with it.        let mut first = from;        while first > 0 && !used[first - 1] && lex.dropped.iter().any(|w| *w == tokens[first - 1].text) {            first -= 1;            used[first] = true;        }        said.push(Said { from: tokens[first].from, to: tokens[from + n - 1].to, what });    };    let mut at = 0;    while at < tokens.len() {        if used[at] {            at += 1;            continue;        }        // someday        let n = phrase(&tokens, at, &lex.someday);        if n > 0 && day.is_none() {            someday = true;            mark(&mut used, &mut said, at, n, "day");            at += n;            continue;        }        // today / tomorrow (longest phrase first: "tomorrow night")        let (nt, nm) = (phrase(&tokens, at, &lex.today), phrase(&tokens, at, &lex.tomorrow));        if (nt > 0 || nm > 0) && day.is_none() && !someday {            let (n, offset) = if nm >= nt { (nm, 1) } else { (nt, 0) };            day = Some(today + offset);            mark(&mut used, &mut said, at, n, "day");            at += n;            continue;        }        // [next|this] weekday        let lead_next = phrase(&tokens, at, &lex.next);        let lead_this = if lead_next == 0 { phrase(&tokens, at, &lex.this) } else { 0 };        let lead = lead_next + lead_this;        if day.is_none() && !someday && at + lead < tokens.len() {            if let Some(weekday) = weekday_of(&tokens[at + lead].text, lex) {                let now = weekday_monday_first(today);                let mut ahead = (weekday as i64 - now as i64).rem_euclid(7);                if lead_next > 0 && ahead == 0 {                    ahead = 7;                }                day = Some(today + ahead);                mark(&mut used, &mut said, at, lead + 1, "day");                at += lead + 1;                continue;            }        }        // a date: "26 Nov", "26th of November", "Nov 26", "26/11"        if day.is_none() && !someday {            if let Some((found, n)) = date_at(&tokens, at, today, lex) {                day = Some(found);                mark(&mut used, &mut said, at, n, "day");                at += n;                continue;            }        }        // a length after the time: "for an hour", "for 90 minutes", "for 2h", "for half an hour"        if let (Some(start), None) = (time, end) {            let lead = phrase(&tokens, at, &lex.lasting);            if lead > 0 {                if let Some((minutes, n)) = length_at(&tokens, at + lead, lex) {                    end = Some((start + minutes) % (24 * 60));                    for flag in used.iter_mut().skip(at).take(lead + n) {                        *flag = true;                    }                    said.push(Said { from: tokens[at].from, to: tokens[at + lead + n - 1].to, what: "time" });                    at += lead + n;                    continue;                }            }        }        // a time, maybe a range: "7pm", "at 7", "7-9pm", "from 7 to 9", "noon"        if time.is_none() {            if let Some((start, finish, n)) = time_at(&tokens, at, day.is_some() && at > 0 && used[at - 1], lex) {                time = Some(start);                end = finish;                mark(&mut used, &mut said, at, n, "time");                at += n;                continue;            }        }        at += 1;    }    let title = tokens        .iter()        .zip(&used)        .filter(|(_, used)| !**used)        .map(|(token, _)| line.chars().skip(token.from).take(token.to - token.from).collect::<String>())        .collect::<Vec<_>>()        .join(" ");    said.sort_by_key(|one| one.from);    Understood { title: title.trim().to_string(), day, someday, time, end, said }}/// A length at `at`, under a day: its minutes and how many tokens it took. "an hour", "one hour and a half",/// "half an hour", "90 minutes", "1.5 hours", "2h", "45min".fn length_at(tokens: &[Token], at: usize, lex: &Lexicon) -> Option<(i64, usize)> {    let text = |i: usize| tokens.get(i).map(|t| t.text.trim_end_matches('.').to_string());    let unit = |word: &str| -> Option<i64> {        if lex.hours.iter().any(|w| w == word) {            Some(60)        } else if lex.minutes.iter().any(|w| w == word) {            Some(1)        } else {            None        }    };    let half = phrase(tokens, at, &lex.half_hour);    if half > 0 {        return Some((30, half));    }    let first = text(at)?;    // "2h", "45min", "1.5hrs": the number and its unit in one word.    let split = first.find(|c: char| !(c.is_ascii_digit() || c == '.')).unwrap_or(first.len());    let (number, rest) = first.split_at(split);    let (count, taken_unit, n) = if lex.one.iter().any(|w| *w == first) {        (1.0, unit(&text(at + 1)?)?, 2)    } else if !number.is_empty() && !rest.is_empty() {        (number.parse::<f64>().ok()?, unit(rest)?, 1)    } else if !number.is_empty() {        (number.parse::<f64>().ok()?, unit(&text(at + 1)?)?, 2)    } else {        return None;    };    let mut minutes = (count * taken_unit as f64).round() as i64;    let extra = phrase(tokens, at + n, &lex.and_a_half);    if extra > 0 && taken_unit == 60 {        minutes += 30;    }    (1..24 * 60).contains(&minutes).then_some((minutes, n + extra))}fn date_at(tokens: &[Token], at: usize, today: i64, lex: &Lexicon) -> Option<(i64, usize)> {    let text = |i: usize| tokens.get(i).map(|t| t.text.as_str());    let (year_now, _, _) = civil_from_days(today);    let land = |month: i64, date: i64, year: Option<i64>| -> Option<i64> {        let pick = |y: i64| (date <= days_in_month(y, month)).then(|| day_number(y, month, date));        match year {            Some(y) => pick(y),            None => pick(year_now).filter(|d| *d >= today).or_else(|| pick(year_now + 1)),        }    };    let year_of = |i: usize| text(i).and_then(|t| t.parse::<i64>().ok()).filter(|y| (1900..=2200).contains(y));    // 26/11 or 26/11/2026: day first, as the person's own calendar writes it.    if let Some(t) = text(at) {        let parts: Vec<&str> = t.split('/').collect();        if parts.len() >= 2 && parts.len() <= 3 && parts.iter().all(|p| !p.is_empty() && p.chars().all(|c| c.is_ascii_digit())) {            let date: i64 = parts[0].parse().ok()?;            let month: i64 = parts[1].parse().ok()?;            let year = parts.get(2).and_then(|y| y.parse::<i64>().ok()).map(|y| if y < 100 { 2000 + y } else { y });            if (1..=12).contains(&month) && (1..=31).contains(&date) {                return land(month, date, year).map(|d| (d, 1));            }        }    }    // 26 [of] Nov [2026]    if let Some(date) = text(at).and_then(|t| date_number(t, lex)) {        let of = usize::from(text(at + 1) == Some("of"));        if let Some(month) = text(at + 1 + of).and_then(|t| month_of(t, lex)) {            let year = year_of(at + 2 + of);            return land(month, date, year).map(|d| (d, 2 + of + usize::from(year.is_some())));        }    }    // Nov 26 [2026]    if let Some(month) = text(at).and_then(|t| month_of(t, lex)) {        if let Some(date) = text(at + 1).and_then(|t| date_number(t, lex)) {            let year = year_of(at + 2);            return land(month, date, year).map(|d| (d, 2 + usize::from(year.is_some())));        }    }    None}/// A time at `at`: its minute, its end, and how many tokens it took. A bare/// number is read as a time only after "at"/"from", or straight after the/// day ("Tue 3"), so "Buy 3 lemons" keeps its three.fn time_at(tokens: &[Token], at: usize, after_day: bool, lex: &Lexicon) -> Option<(i64, Option<i64>, usize)> {    let text = |i: usize| tokens.get(i).map(|t| t.text.as_str());    let n_at = phrase(tokens, at, &lex.at).max(phrase(tokens, at, &lex.from));    let lead = n_at;    let start_at = at + lead;    let one = |i: usize| -> Option<(i64, usize, Option<bool>, bool)> {        if phrase(tokens, i, &lex.noon) > 0 {            return Some((12 * 60, phrase(tokens, i, &lex.noon), Some(true), true));        }        if phrase(tokens, i, &lex.midnight) > 0 {            return Some((0, phrase(tokens, i, &lex.midnight), Some(false), true));        }        let (h, m, half, twenty_four) = clock_of(text(i)?, lex)?;        // "7 pm": the half as its own word.        let (half, n) = match half {            Some(_) => (half, 1),            None => {                let (am, pm) = (phrase(tokens, i + 1, &lex.am), phrase(tokens, i + 1, &lex.pm));                if pm > 0 && (1..=12).contains(&h) {                    (Some(true), 1 + pm)                } else if am > 0 && (1..=12).contains(&h) {                    (Some(false), 1 + am)                } else {                    (None, 1)                }            }        };        Some((minute_of(h, m, half, twenty_four), n, half, twenty_four || half.is_some()))    };    let (start, n, _, firm) = one(start_at)?;    let bare = !firm && text(start_at).is_some_and(|t| t.chars().all(|c| c.is_ascii_digit()));    if bare && lead == 0 && !after_day {        return None;    }    let mut taken = lead + n;    let mut end = None;    let until = phrase(tokens, at + taken, &lex.until);    if until > 0 {        if let Some((finish, m, end_half, _)) = one(at + taken + until) {            let mut finish = finish;            // "11-1": an end before its start is the afternoon's.            if finish <= start && finish + 12 * 60 > start && end_half.is_none() {                finish += 12 * 60;            }            // "10pm to 2am": an end said after midnight, the evening running on            // into the night (adding puts it on the next day).            let past_midnight = finish < start && end_half == Some(false) && start >= 12 * 60;            if finish > start || past_midnight {                end = Some(finish);                taken += until + m;                return Some((start, end, taken));            }        }    }    Some((start, end, taken))}/// The pill: "Thu 26 Nov · 19:00", "Thu 26 Nov", "Sometime".pub fn pill(day: Option<i64>, time: Option<i64>, end: Option<i64>, words: &Words) -> String {    let Some(day) = day else {        return words.no_day.clone();    };    let (_, month, date) = civil_from_days(day);    let mut out = fill(        &words.pill_day,        &[            ("weekday", &words.weekdays_short[weekday_monday_first(day)]),            ("day", &date.to_string()),            ("month", &words.months_short[(month - 1) as usize]),        ],    );    if let Some(time) = time {        out.push_str(&words.pill_join);        out.push_str(&clock(time));        if let Some(end) = end {            out.push_str(" – ");            out.push_str(&clock(end));        }    }    out}