Cotton code
411 lines · 14.3 KB · RustRaw
//! English input extraction without a clock or I/O. Spans are half-open UTF-8//! byte offsets into the original input. Candidates are ordered best first;//! unqualified hours prefer 07:00–21:59, then the next occurrence from `now`.use chrono::{DateTime, Datelike, Duration, NaiveDate, Timelike};use chrono_tz::Tz;use regex::Regex;use serde::{Deserialize, Serialize};use std::sync::{Arc, LazyLock, Mutex};#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]pub struct Span {    pub start: usize,    pub end: usize,}#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]pub struct Understood {    pub text: String,    pub span: Span,    pub candidates: Vec<String>,}#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]pub struct ParsedPhrase {    pub date: Option<Understood>,    pub time: Option<Understood>,    pub project: Option<Understood>,    pub person: Option<Understood>,    pub verb: Option<Understood>,    pub remainder: String,    /// Original untouched segments, including their whitespace and punctuation.    pub remainder_spans: Vec<Span>,}fn pattern(p: &str) -> Regex {    Regex::new(p).expect("static phrase pattern")}fn understood(text: &str, start: usize, end: usize, candidates: Vec<String>) -> Understood {    Understood {        text: text[start..end].into(),        span: Span { start, end },        candidates,    }}fn overlaps(start: usize, end: usize, used: &[Span]) -> bool {    used.iter().any(|s| start < s.end && end > s.start)}fn word_boundary(text: &str, start: usize, end: usize) -> bool {    let word = |c: char| c.is_alphanumeric() || c == '_';    !text[..start].chars().next_back().is_some_and(word)        && !text[end..].chars().next().is_some_and(word)}type NamePatterns = Arc<Vec<(String, Regex)>>;type NamePatternCache = Vec<(Vec<String>, NamePatterns)>;// Two dictionaries (projects and people) stay warm across keystrokes. Limit// retained bytes so a caller cannot turn this performance cache into storage.fn name_patterns(names: &[String]) -> Result<NamePatterns, String> {    static CACHE: LazyLock<Mutex<NamePatternCache>> = LazyLock::new(|| Mutex::new(Vec::new()));    let mut cache = CACHE        .lock()        .unwrap_or_else(|poisoned| poisoned.into_inner());    cached_name_patterns(names, &mut cache)}fn cached_name_patterns(    names: &[String],    cache: &mut NamePatternCache,) -> Result<NamePatterns, String> {    if let Some((_, patterns)) = cache.iter().find(|(key, _)| key == names) {        return Ok(Arc::clone(patterns));    }    let patterns: NamePatterns = Arc::new(        names            .iter()            .filter(|n| !n.trim().is_empty())            .map(|name| {                Regex::new(&format!(r"(?i){}", regex::escape(name)))                    .map(|pattern| (name.clone(), pattern))                    .map_err(|_| "a supplied name exceeds the matcher size limit".to_string())            })            .collect::<Result<_, _>>()?,    );    if names.iter().map(String::len).sum::<usize>() <= 1024 * 1024 {        if cache.len() == 2 {            cache.remove(0);        }        cache.push((names.to_vec(), Arc::clone(&patterns)));    }    Ok(patterns)}fn name_match(text: &str, names: &[String], used: &[Span]) -> Result<Option<Understood>, String> {    let mut hits = Vec::new();    let patterns = name_patterns(names)?;    for (name, re) in patterns.iter() {        for m in re.find_iter(text) {            if !word_boundary(text, m.start(), m.end()) || overlaps(m.start(), m.end(), used) {                continue;            }            hits.push((m.start(), m.end(), name.clone()));        }    }    // Longest name wins (Sam Lee before Sam); ties follow the text, then name.    hits.sort_by(|a, b| {        (b.1 - b.0)            .cmp(&(a.1 - a.0))            .then(a.0.cmp(&b.0))            .then(a.2.cmp(&b.2))    });    Ok(hits        .first()        .map(|(s, e, n)| understood(text, *s, *e, vec![n.clone()])))}fn remember(value: &Option<Understood>, used: &mut Vec<Span>) {    if let Some(v) = value {        used.push(v.span.clone());    }}fn ordinal_suffix(day: u32) -> &'static str {    if (11..=13).contains(&(day % 100)) {        "th"    } else {        match day % 10 {            1 => "st",            2 => "nd",            3 => "rd",            _ => "th",        }    }}fn hour_alternatives(hour: u32, explicit: bool, minute: u32, current: u32) -> Vec<u32> {    let mut hours = if explicit {        vec![hour]    } else {        vec![hour % 12, hour % 12 + 12]    };    hours.sort_by_key(|h| {        (            !(7..22).contains(h),            (h * 60 + minute + 1440 - current) % 1440,        )    });    hours}fn next_month_day(today: NaiveDate, month: u32, day: u32) -> Option<NaiveDate> {    (today.year()..=today.year() + 8)        .filter_map(|y| NaiveDate::from_ymd_opt(y, month, day))        .find(|d| *d >= today)}fn next_ordinal(today: NaiveDate, day: u32) -> Option<NaiveDate> {    (0..24)        .filter_map(|offset| {            let m = today.month0() + offset;            NaiveDate::from_ymd_opt(today.year() + (m / 12) as i32, m % 12 + 1, day)        })        .find(|d| *d >= today)}/// `now` must be RFC3339 with an explicit offset; `time_zone` is an IANA name./// Invalid context is an error, never a fallback to the machine's clock/zone./// One match per field is consumed; later mentions remain in the remainder.pub fn parse_phrase(    text: &str,    now: &str,    time_zone: &str,    projects: &[String],    people: &[String],) -> Result<ParsedPhrase, String> {    let now = DateTime::parse_from_rfc3339(now)        .map_err(|_| "now must be RFC3339 with an offset".to_string())?;    let zone: Tz = time_zone        .parse()        .map_err(|_| "time_zone must be an IANA time zone".to_string())?;    let local = now.with_timezone(&zone);    let today = local.date_naive();    let mut used = Vec::new();    // Names take precedence: a project named Friday must not turn into a date.    let project = name_match(text, projects, &used)?;    remember(&project, &mut used);    let person = name_match(text, people, &used)?;    remember(&person, &mut used);    static DATES: LazyLock<Regex> = LazyLock::new(|| {        pattern(            r"(?i-u)\b(?:(today|tomorrow|yesterday)|(next\s+)?(monday|tuesday|wednesday|thursday|friday|saturday|sunday)|(?P<day>[0-9]{1,2})(?P<suffix>st|nd|rd|th)?\s+(?P<month>jan(?:uary)?|feb(?:ruary)?|mar(?:ch)?|apr(?:il)?|may|jun(?:e)?|jul(?:y)?|aug(?:ust)?|sep(?:tember)?|oct(?:ober)?|nov(?:ember)?|dec(?:ember)?)|(?P<month_first>jan(?:uary)?|feb(?:ruary)?|mar(?:ch)?|apr(?:il)?|may|jun(?:e)?|jul(?:y)?|aug(?:ust)?|sep(?:tember)?|oct(?:ober)?|nov(?:ember)?|dec(?:ember)?)\s+(?P<day_last>[0-9]{1,2})(?P<suffix_last>st|nd|rd|th)?|on\s+the\s+(?P<ordinal>[0-9]{1,2})(?P<ordinal_suffix>st|nd|rd|th))\b",        )    });    let mut date = None;    for c in DATES.captures_iter(text) {        let m = c.get(0).unwrap();        if !word_boundary(text, m.start(), m.end()) || overlaps(m.start(), m.end(), &used) {            continue;        }        let mut alternative = None;        let value = if let Some(relative) = c.get(1) {            let days = match relative.as_str().to_ascii_lowercase().as_str() {                "tomorrow" => 1,                "yesterday" => -1,                _ => 0,            };            today.checked_add_signed(Duration::days(days))        } else if let Some(weekday) = c.get(3) {            let target = [                "monday",                "tuesday",                "wednesday",                "thursday",                "friday",                "saturday",                "sunday",            ]            .iter()            .position(|d| weekday.as_str().eq_ignore_ascii_case(d))            .unwrap() as i64;            let mut delta = (target - i64::from(today.weekday().num_days_from_monday()) + 7) % 7;            let same_weekday = delta == 0;            if same_weekday && c.get(2).is_some() {                delta = 7;            }            if c.get(2).is_some() && !same_weekday {                alternative = today.checked_add_signed(Duration::days(delta + 7));            }            today.checked_add_signed(Duration::days(delta))        } else if let Some(day) = c.name("day").or_else(|| c.name("day_last")) {            let day: u32 = day.as_str().parse().unwrap();            if c.name("suffix")                .or_else(|| c.name("suffix_last"))                .is_some_and(|suffix| !suffix.as_str().eq_ignore_ascii_case(ordinal_suffix(day)))            {                continue;            }            let month = c                .name("month")                .or_else(|| c.name("month_first"))                .unwrap()                .as_str()[..3]                .to_ascii_lowercase();            let month = [                "jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec",            ]            .iter()            .position(|v| *v == month)            .unwrap() as u32                + 1;            next_month_day(today, month, day)        } else {            let day: u32 = c.name("ordinal").unwrap().as_str().parse().unwrap();            if !c                .name("ordinal_suffix")                .unwrap()                .as_str()                .eq_ignore_ascii_case(ordinal_suffix(day))            {                continue;            }            next_ordinal(today, day)        };        if let Some(value) = value {            date = Some(understood(                text,                m.start(),                m.end(),                std::iter::once(value)                    .chain(alternative)                    .map(|date| date.to_string())                    .collect(),            ));            break;        }    }    remember(&date, &mut used);    static TIMES: LazyLock<Regex> = LazyLock::new(|| {        pattern(            r"(?i-u)\b(?:(?:at\s+)?(noon|midnight)|(?:at\s+)?([0-9]{1,2})(?::([0-9]{2}))?\s*(am|pm)|(?:at\s+)?([0-9]{1,2}):([0-9]{2})|at\s+([0-9]{1,2}))\b",        )    });    let mut time = None;    for c in TIMES.captures_iter(text) {        let m = c.get(0).unwrap();        if !word_boundary(text, m.start(), m.end()) || overlaps(m.start(), m.end(), &used) {            continue;        }        // Do not reinterpret an invalid colon time as its bare hour.        if text[m.end()..].starts_with(':') {            continue;        }        let (hours, minute) = if let Some(word) = c.get(1) {            (                vec![if word.as_str().eq_ignore_ascii_case("noon") {                    12                } else {                    0                }],                0,            )        } else if let Some(h) = c.get(2) {            let h: u32 = h.as_str().parse().unwrap();            let minute = c.get(3).map_or(0, |v| v.as_str().parse::<u32>().unwrap());            if !(1..=12).contains(&h) || minute > 59 {                continue;            }            (                vec![                    h % 12                        + if c.get(4).unwrap().as_str().eq_ignore_ascii_case("pm") {                            12                        } else {                            0                        },                ],                minute,            )        } else if let Some(h) = c.get(5) {            let h: u32 = h.as_str().parse().unwrap();            let minute: u32 = c.get(6).unwrap().as_str().parse().unwrap();            if h > 23 || minute > 59 {                continue;            }            let explicit = h > 12 || h == 0 || c.get(5).unwrap().as_str().starts_with('0');            (                hour_alternatives(h, explicit, minute, local.hour() * 60 + local.minute()),                minute,            )        } else {            let h: u32 = c.get(7).unwrap().as_str().parse().unwrap();            if h > 23 {                continue;            }            (                hour_alternatives(                    h,                    h > 12 || h == 0 || c.get(7).unwrap().as_str().starts_with('0'),                    0,                    local.hour() * 60 + local.minute(),                ),                0,            )        };        time = Some(understood(            text,            m.start(),            m.end(),            hours                .into_iter()                .map(|h| format!("{h:02}:{minute:02}"))                .collect(),        ));        break;    }    remember(&time, &mut used);    // Imperative verbs are only recognised at the beginning, avoiding destructive    // commands inferred from prose such as "please don't delete this". "go to"    // is "open": a spoken line that opens with either asks to be taken there.    static VERBS: LazyLock<Regex> = LazyLock::new(|| {        pattern(r"(?i-u)^\s*(done|move|delete|rename|add|new|remind|open|go\s+to)\b")    });    let verb = VERBS.captures(text).and_then(|c| {        let m = c.get(1).unwrap();        if !word_boundary(text, m.start(), m.end()) || overlaps(m.start(), m.end(), &used) {            return None;        }        let v = m.as_str().to_ascii_lowercase();        Some(understood(            text,            m.start(),            m.end(),            vec![match v.as_str() {                "new" => "add".into(),                _ if v.starts_with("go") => "open".into(),                _ => v,            }],        ))    });    remember(&verb, &mut used);    used.sort_by_key(|s| s.start);    let mut remainder_spans = Vec::new();    let mut end = 0;    for s in used {        if end < s.start {            remainder_spans.push(Span {                start: end,                end: s.start,            });        }        end = s.end;    }    if end < text.len() {        remainder_spans.push(Span {            start: end,            end: text.len(),        });    }    let remainder = if end == 0 {        text.to_string()    } else {        remainder_spans            .iter()            .map(|s| text[s.start..s.end].trim())            .filter(|v| {                v.chars()                    .any(|c| !c.is_whitespace() && c != ',' && c != ';')            })            .collect::<Vec<_>>()            .join(" ")    };    Ok(ParsedPhrase {        date,        time,        project,        person,        verb,        remainder,        remainder_spans,    })}pub mod money;#[cfg(test)]mod tests;