Adds all date parsing and refactors date into a module

This commit is contained in:
Dandaedre 2024-10-31 17:12:44 +01:00 committed by Dandaedre
parent 207bf2815c
commit 71c7428c4e
6 changed files with 290 additions and 56 deletions

240
src/date/date_parse.rs Normal file
View File

@ -0,0 +1,240 @@
//! 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, preceded, 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<Month>,
},
/// 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<DateObject>,
// }
/// Type defining a list of dates
///
/// This type is parsed from : DateObject (, DateObject)*
pub type DateList = Vec<DateObject>;
/// Parse a month with either french or english delimitation
///
/// Ignores all trailing and leading spaces
fn parse_month(input: &str) -> IResult<&str, Month> {
delimited(
space0,
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")),
)),
)),
space0,
)(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)),
|(_, month, _sep, day)| DatePoint::Date {
day: day.parse_to().unwrap(),
month: Some(month),
},
),
map(
tuple((space0, digit1, space0, parse_month)),
|(_, day, _, month)| DatePoint::Date {
day: day.parse_to().unwrap(),
month: Some(month),
},
),
map(preceded(space0, digit1), |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<DateObject>> {
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é").unwrap();
assert_eq!(output, Month::January);
assert_eq!(leftover_input, "€rré");
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),
}),
];
println!("{:?}", output);
for (a, b) in output.into_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<Vec<&str>, 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)
// }

View File

@ -1,32 +1,12 @@
//! 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;
use chrono::Duration;
use chrono::Local;
use chrono::Month;
use chrono::Months;
use chrono::NaiveDate;
use chrono::Weekday;
/// Returns the date corresponding to the implicit Weekday
///
@ -42,9 +22,9 @@ pub(crate) fn relative_day_to_date(day: Weekday, context: Option<NaiveDate>) ->
#[derive(Debug)]
pub(crate) struct PartialDate {
/// The month implied in the date
month: Option<Month>,
pub(crate) month: Option<Month>,
/// 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 +57,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);

27
src/date/mod.rs Normal file
View File

@ -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;

View File

@ -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<dyn Error>> {
// let (remaining_input, output) = do_nothing_parser("my_input")?;
// assert_eq!(remaining_input, "my_input");
// assert_eq!(output, "");
// Ok(())
// }

View File

@ -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<nom::error::Error<Box<str>>>),
}
impl From<nom::Err<nom::error::Error<&str>>> for IdleError {
fn from(err: nom::Err<nom::error::Error<&str>>) -> Self {
Self::IncorrectDate(err.map_input(|input| input.into()))
}
}
#[cfg(test)]

View File

@ -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();
}