diff --git a/TODO.md b/TODO.md index 5fbbd60..00c5d5f 100644 --- a/TODO.md +++ b/TODO.md @@ -1,13 +1,17 @@ +# Important +[ ] Get rid of the #deprecated +[ ] Get rid of the #dead_code + # Test Driven [ ] Config Load and persistance [ ] Config recovery [ ] Error testing framework - # Tasks ## Dan [ ] Finish testing to reach 100% coverage [ ] Implement Resilience & Recovery +[*] Parse date mini language ## Vky [ ] Write documentation for all functions in IO.rs diff --git a/src/date/date_parse.rs b/src/date/date_parse.rs new file mode 100644 index 0000000..bb3d114 --- /dev/null +++ b/src/date/date_parse.rs @@ -0,0 +1,268 @@ +//! Parse a date string sequence into structs +//! +//! The pseudo grammar is defined as: +//! date = (day) (month) | (month) (day) | (weekday) +//! daterange = (date) - (date) +//! dateobject = (date) | (daterange) +//! datelist = (dateobject) (, (dateobject))* +//! + +#![allow(dead_code)] +use chrono::{Month, Weekday}; +use nom::{ + branch::alt, + bytes::complete::tag_no_case, + character::complete::{char, digit1, space0}, + combinator::{map, value}, + multi::separated_list1, + sequence::{delimited, separated_pair, tuple}, + IResult, ParseTo, +}; + +/// A single relative date, which is either a day and an optionnal month or a weekday +/// +/// Parsed from: (\d) (Month)? | Day +#[derive(Clone, Debug)] +#[cfg_attr(test, derive(PartialEq))] +pub(crate) enum DatePoint { + /// A day specified by it's position in the month, and an optionnal month + Date { + /// The day of the month + day: usize, + /// An optional month + month: Option, + }, + /// A weekday (as in Mon, Tue, etc..) + Weekday(Weekday), +} + +/// A date range, signals a range between a starting point and an endpoint +/// +/// Parsed from : DatePoint - DatePoint +#[derive(Clone, Debug)] +#[cfg_attr(test, derive(PartialEq))] +pub(crate) struct DateRange { + /// The starting date in the range + start: DatePoint, + /// The end date in the range + stop: DatePoint, +} + +/// Main date structure, signals either a range between two relative dates or a single date +/// +/// Parsed from : DateRange | DatePoint +#[derive(Clone, Debug)] +#[cfg_attr(test, derive(PartialEq))] +pub enum DateObject { + /// A range between two relative dates + Range(DateRange), + /// A single date + Single(DatePoint), +} + +// struct DateList { +// inner: Vec, +// } + +/// Type defining a list of dates +/// +/// This type is parsed from : DateObject (, DateObject)* +pub type DateList = Vec; + +/// Parse a month with either french or english delimitation +/// +/// Ignores all trailing and leading spaces +fn parse_month(input: &str) -> IResult<&str, Month> { + alt(( + alt(( + value(Month::January, tag_no_case("jan")), + value(Month::February, tag_no_case("fev")), + value(Month::February, tag_no_case("feb")), + value(Month::March, tag_no_case("mar")), + value(Month::March, tag_no_case("avr")), + value(Month::April, tag_no_case("apr")), + value(Month::May, tag_no_case("mai")), + value(Month::May, tag_no_case("may")), + value(Month::June, tag_no_case("juin")), + value(Month::June, tag_no_case("jun")), + value(Month::July, tag_no_case("juil")), + value(Month::July, tag_no_case("jul")), + value(Month::August, tag_no_case("aou")), + value(Month::August, tag_no_case("aug")), + value(Month::September, tag_no_case("sep")), + value(Month::October, tag_no_case("oct")), + value(Month::November, tag_no_case("nov")), + value(Month::December, tag_no_case("dec")), + )), + alt(( + value(Month::January, tag_no_case("jr")), + value(Month::February, tag_no_case("fr")), + value(Month::March, tag_no_case("ms")), + value(Month::April, tag_no_case("al")), + value(Month::May, tag_no_case("mi")), + value(Month::June, tag_no_case("jn")), + value(Month::July, tag_no_case("jt")), + value(Month::August, tag_no_case("at")), + value(Month::September, tag_no_case("se")), + value(Month::October, tag_no_case("oe")), + value(Month::November, tag_no_case("ne")), + value(Month::December, tag_no_case("de")), + )), + ))(input) +} + +/// Parse a weekday using either french or english day acronims +fn parse_weekday(input: &str) -> IResult<&str, Weekday> { + delimited( + space0, + alt(( + value(Weekday::Mon, tag_no_case("mon")), + value(Weekday::Mon, tag_no_case("lun")), + value(Weekday::Tue, tag_no_case("tue")), + value(Weekday::Tue, tag_no_case("mar")), + value(Weekday::Wed, tag_no_case("wed")), + value(Weekday::Wed, tag_no_case("mer")), + value(Weekday::Thu, tag_no_case("thu")), + value(Weekday::Thu, tag_no_case("jeu")), + value(Weekday::Fri, tag_no_case("fri")), + value(Weekday::Fri, tag_no_case("ven")), + value(Weekday::Sat, tag_no_case("sat")), + value(Weekday::Sat, tag_no_case("sam")), + value(Weekday::Sun, tag_no_case("sun")), + value(Weekday::Sun, tag_no_case("dim")), + )), + space0, + )(input) +} + +/// Parse a single date ignoring all whitespace +/// +/// Parse from: Day (Month)? | (Month)? Day | Day +fn parse_simple_date(input: &str) -> IResult<&str, DatePoint> { + alt(( + map( + tuple((space0, parse_month, space0, digit1, space0)), + |(_, month, _sep, day, _)| DatePoint::Date { + day: day.parse_to().unwrap(), + month: Some(month), + }, + ), + map( + tuple((space0, digit1, space0, parse_month, space0)), + |(_, day, _, month, _)| DatePoint::Date { + day: day.parse_to().unwrap(), + month: Some(month), + }, + ), + map(delimited(space0, digit1, space0), |day: &str| { + DatePoint::Date { + day: day.parse_to().unwrap(), + month: None, + } + }), + map(parse_weekday, DatePoint::Weekday), + ))(input) +} + +/// Parse a single date, either a range or a single day +/// +/// Parse from: Date - Date | Date +fn parse_date_object(input: &str) -> IResult<&str, DateObject> { + alt(( + map( + separated_pair(parse_simple_date, char('-'), parse_simple_date), + |(start, stop)| DateObject::Range(DateRange { start, stop }), + ), + map(parse_simple_date, DateObject::Single), + ))(input) +} + +/// Parse a complete list of days separated by ',' +/// +/// Parses from: DateObject (, DateObject)* +pub fn parse_str_into_date(input: &str) -> IResult<&str, Vec> { + separated_list1(char(','), parse_date_object)(input) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_parsing() { + let (leftover_input, output) = parse_month("jan €rré jan feb v").unwrap(); + assert_eq!(leftover_input, " €rré jan feb v"); + assert_eq!(output, Month::January); + + let (leftover_input, output) = + parse_str_into_date(" 10 jan €rré10 jan 10 jan").unwrap(); + assert_eq!(leftover_input, "€rré10 jan 10 jan"); + let result = [DateObject::Single(DatePoint::Date { + day: 10, + month: Some(Month::January), + })]; + test_dates(&output, &result); + + let (leftover_input, output) = parse_str_into_date(" 10 jan 20").unwrap(); + assert_eq!(leftover_input, "20"); + let result = [DateObject::Single(DatePoint::Date { + day: 10, + month: Some(Month::January), + })]; + test_dates(&output, &result); + + let (leftover_input, output) = parse_str_into_date("feb 10 jan 20").unwrap(); + assert_eq!(leftover_input, "jan 20"); + let result = [DateObject::Single(DatePoint::Date { + day: 10, + month: Some(Month::February), + })]; + test_dates(&output, &result); + + let (leftover_input, output) = + parse_str_into_date(" 10 jan - 10 jan, tue , 23,mon-tue,").unwrap(); + assert_eq!(leftover_input, ","); + let result = [ + DateObject::Range(DateRange { + start: DatePoint::Date { + day: 10, + month: Some(Month::January), + }, + stop: DatePoint::Date { + day: 10, + month: Some(Month::January), + }, + }), + DateObject::Single(DatePoint::Weekday(Weekday::Tue)), + DateObject::Single(DatePoint::Date { + day: 23, + month: None, + }), + DateObject::Range(DateRange { + start: DatePoint::Weekday(Weekday::Mon), + stop: DatePoint::Weekday(Weekday::Tue), + }), + ]; + test_dates(&output, &result); + } + + fn test_dates(output: &Vec, result: &[DateObject]) { + println!("{:?}", output); + for (a, b) in output.iter().zip(result.iter()) { + println!("Found: {:?}. Expected: {:?}", a, b); + assert_eq!(a, b); + } + } +} + +// Procedural approach, in case all fails +// /// Parse all DatesObjects separated by commas +// fn parse_date_input(input: &str) -> Result, IdleError> { +// let (_, list_date) = separated_list0(char(','), complete::is_not(","))(input)?; +// // let find_ranges= list_date.iter().map(|date| separated_pair(, , )).collect(); +// Ok(list_date) +// } +// // /// Parse all DatesObjects separated by commas +// fn parse_all_commas(input: &str) -> IResult<&str, Vec<&str>> { +// separated_list0(char(','), complete::is_not(","))(input) +// } diff --git a/src/date.rs b/src/date/date_tools.rs similarity index 79% rename from src/date.rs rename to src/date/date_tools.rs index 7db9e7c..1983560 100644 --- a/src/date.rs +++ b/src/date/date_tools.rs @@ -1,32 +1,6 @@ -//! All parsing and logic associated to finding and parsing dates used in all commands -//! -//! Features: -//! Simple parsing logic: (dayname, daynumber, day month) with implicit month / year -//! Range finding: (date) - (date) -//! Comma separated dates: (date), (date) -//! Date utilities: Finding next monday etc... -#![allow(dead_code)] - -use chrono::{Datelike, Duration, Local, Month, Months, NaiveDate, Weekday}; - +//! Utilities to handle date and relative date selection use crate::error_handling::IdleError; - -// All structures -/// A punctual day (just one date) -pub struct DateEventPunctual {} - -/// An interval -pub struct DateEventInterval {} - -/// A date, wether punctual or interval -pub struct DateEventDate {} - -/// A series of dates or intervals -pub struct DateEvent {} - -// Define parser - -// Defines date routines +use chrono::{Datelike, Duration, Local, Month, Months, NaiveDate, Weekday}; /// Returns the date corresponding to the implicit Weekday /// @@ -42,9 +16,9 @@ pub(crate) fn relative_day_to_date(day: Weekday, context: Option) -> #[derive(Debug)] pub(crate) struct PartialDate { /// The month implied in the date - month: Option, + pub(crate) month: Option, /// The day of the month implied in the date - day: u32, + pub(crate) day: u32, } /// Finds the date corresponding to the loosely defined implicit partial date @@ -77,11 +51,11 @@ pub(crate) fn relative_date_to_date( } #[cfg(test)] -mod tests { +pub(crate) mod tests { use super::*; #[test] - fn test_relatave_dates() { + fn test_relative_dates() { let date = NaiveDate::from_ymd_opt(2024, 10, 30); let date_next_mon = NaiveDate::from_ymd_opt(2024, 11, 4); let date_next_tue = NaiveDate::from_ymd_opt(2024, 11, 7); diff --git a/src/date/mod.rs b/src/date/mod.rs new file mode 100644 index 0000000..7e7e8f2 --- /dev/null +++ b/src/date/mod.rs @@ -0,0 +1,27 @@ +//! All parsing and logic associated to finding and parsing dates used in all commands +//! +//! Features: +//! Simple parsing logic: (dayname, daynumber, day month) with implicit month / year +//! Range finding: (date) - (date) +//! Comma separated dates: (date), (date) +//! Date utilities: Finding next monday etc... +#![allow(dead_code)] + +mod date_parse; +// All structures +/// A punctual day (just one date) +pub struct DateEventPunctual {} + +/// An interval +pub struct DateEventInterval {} + +/// A date, wether punctual or interval +pub struct DateEventDate {} + +/// A series of dates or intervals +pub struct DateEvent {} + +// Defines date routines + +pub(crate) mod date_tools; +pub(crate) use date_tools::PartialDate; diff --git a/src/date_parse.rs b/src/date_parse.rs deleted file mode 100644 index 0d06dcc..0000000 --- a/src/date_parse.rs +++ /dev/null @@ -1,23 +0,0 @@ -//! Parse a date string sequence into structs -//! -//! The pseudo grammar is defined as: -//! date = (day) (month) | (month) (day) -//! daterange = (date) - (date) -//! dateobject = (date) | (daterange) -//! datelist = (dateobject) (, (dateobject))* -//! - -// use std::error::Error; - -// use nom::IResult; - -// pub fn do_nothing_parser(input: &str) -> IResult<&str, &str> { -// Ok((input, "")) -// } - -// fn main() -> Result<(), Box> { -// let (remaining_input, output) = do_nothing_parser("my_input")?; -// assert_eq!(remaining_input, "my_input"); -// assert_eq!(output, ""); -// Ok(()) -// } diff --git a/src/error_handling.rs b/src/error_handling.rs index 0215da5..bae4624 100644 --- a/src/error_handling.rs +++ b/src/error_handling.rs @@ -22,6 +22,15 @@ pub enum IdleError { /// A generic error when handling discord API calls #[error("An error occured while processing a Discord API call")] SerenityAPI(#[from] serenity_prelude::Error), + /// A parsing error occured, unwrapping this error into something better will be necessary (helper function ?) + #[error("An error occured while parsing the date given {0:?}")] + IncorrectDate(nom::Err>>), +} + +impl From>> for IdleError { + fn from(err: nom::Err>) -> Self { + Self::IncorrectDate(err.map_input(|input| input.into())) + } } #[cfg(test)] diff --git a/src/main.rs b/src/main.rs index 90a28c6..c6884c0 100644 --- a/src/main.rs +++ b/src/main.rs @@ -10,7 +10,6 @@ use io::discord_main_loop; mod config; mod date; -mod date_parse; mod error_handling; mod ids; mod io; @@ -26,4 +25,6 @@ async fn main() { init_logger(); discord_main_loop().await; + // use date_parse::test_parsing; + // test_parsing(); } diff --git a/src/votes.rs b/src/votes.rs index 04ffe2a..99ab501 100644 --- a/src/votes.rs +++ b/src/votes.rs @@ -7,7 +7,7 @@ //! ListCurrentEvents (struct) //! ListFutureEvents (struct) //! -#![allow(dead_code)] +#![allow(dead_code, deprecated)] use std::{collections::HashMap, sync::LazyLock};