nlcep 0.9.0

a library for parsing natural language calendar events
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
use std::str::FromStr;

use jiff::{
    civil::{date, Date},
    ToSpan, Zoned,
};
use strum::IntoEnumIterator;

use crate::EventParseError;

pub trait AsDate {
    fn as_date(&self, now: Zoned) -> Result<Date, EventParseError>;
}

trait FromMultiword {
    /// usize is the number of words matched
    fn parse_multiword(words: &[String]) -> Option<(Self, usize)>
    where
        Self: Sized;
}

#[derive(Debug, Clone, Copy, PartialEq, strum_macros::Display, strum_macros::EnumIter)]
pub enum DateRelativeLanguage {
    English,
    Finnish,
}
impl DateRelativeLanguage {
    pub const fn get_noun_prev(&self) -> &'static str {
        match self {
            DateRelativeLanguage::English => "last",
            DateRelativeLanguage::Finnish => "viime",
        }
    }
    pub const fn get_noun_next(&self) -> &'static str {
        match self {
            DateRelativeLanguage::English => "next",
            DateRelativeLanguage::Finnish => "ensi",
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, strum_macros::Display, strum_macros::EnumIter)]
pub enum DateRelativeWeekday {
    Monday,
    Tuesday,
    Wednesday,
    Thurdsday,
    Friday,
    Saturday,
    Sunday,
}
impl From<DateRelativeWeekday> for jiff::civil::Weekday {
    fn from(val: DateRelativeWeekday) -> Self {
        match val {
            DateRelativeWeekday::Monday => jiff::civil::Weekday::Monday,
            DateRelativeWeekday::Tuesday => jiff::civil::Weekday::Tuesday,
            DateRelativeWeekday::Wednesday => jiff::civil::Weekday::Wednesday,
            DateRelativeWeekday::Thurdsday => jiff::civil::Weekday::Thursday,
            DateRelativeWeekday::Friday => jiff::civil::Weekday::Friday,
            DateRelativeWeekday::Saturday => jiff::civil::Weekday::Saturday,
            DateRelativeWeekday::Sunday => jiff::civil::Weekday::Sunday,
        }
    }
}
impl DateRelativeWeekday {
    pub const fn to_locale_static_str(self, lang: DateRelativeLanguage) -> &'static str {
        match (self, lang) {
            (DateRelativeWeekday::Monday, DateRelativeLanguage::English) => "monday",
            (DateRelativeWeekday::Monday, DateRelativeLanguage::Finnish) => "maanantaina",

            (DateRelativeWeekday::Tuesday, DateRelativeLanguage::English) => "tuesday",
            (DateRelativeWeekday::Tuesday, DateRelativeLanguage::Finnish) => "tiistaina",

            (DateRelativeWeekday::Wednesday, DateRelativeLanguage::English) => "wednesday",
            (DateRelativeWeekday::Wednesday, DateRelativeLanguage::Finnish) => "keskiviikkona",

            (DateRelativeWeekday::Thurdsday, DateRelativeLanguage::English) => "thursday",
            (DateRelativeWeekday::Thurdsday, DateRelativeLanguage::Finnish) => "torstaina",

            (DateRelativeWeekday::Friday, DateRelativeLanguage::English) => "friday",
            (DateRelativeWeekday::Friday, DateRelativeLanguage::Finnish) => "perjantaina",

            (DateRelativeWeekday::Saturday, DateRelativeLanguage::English) => "saturday",
            (DateRelativeWeekday::Saturday, DateRelativeLanguage::Finnish) => "lauantaina",

            (DateRelativeWeekday::Sunday, DateRelativeLanguage::English) => "sunday",
            (DateRelativeWeekday::Sunday, DateRelativeLanguage::Finnish) => "sunnuntaina",
        }
    }
}

/// "Natural language" date formats
#[derive(Debug, PartialEq)]
pub enum DateRelative {
    LastWeekday(DateRelativeLanguage, DateRelativeWeekday),
    Yesterday(DateRelativeLanguage),
    Today(DateRelativeLanguage),
    Tomorrow(DateRelativeLanguage),
    Overmorrow(DateRelativeLanguage),
    NextWeekday(DateRelativeLanguage, DateRelativeWeekday),
}
impl FromStr for DateRelative {
    type Err = ();

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.to_lowercase().as_str() {
            "yesterday" => Ok(Self::Yesterday(DateRelativeLanguage::English)),
            "eilen" => Ok(Self::Yesterday(DateRelativeLanguage::Finnish)),

            "today" => Ok(Self::Today(DateRelativeLanguage::English)),
            "tänään" => Ok(Self::Today(DateRelativeLanguage::Finnish)),

            "tomorrow" => Ok(Self::Tomorrow(DateRelativeLanguage::English)),
            "huomenna" => Ok(Self::Tomorrow(DateRelativeLanguage::Finnish)),

            "overmorrow" | "day after tomorrow" => {
                Ok(Self::Overmorrow(DateRelativeLanguage::English))
            }
            "ylihuomenna" => Ok(Self::Overmorrow(DateRelativeLanguage::Finnish)),

            _ => Err(()),
        }
    }
}
impl FromMultiword for DateRelative {
    fn parse_multiword(words: &[String]) -> Option<(Self, usize)>
    where
        Self: Sized,
    {
        let check_sequence = |tokens: &[&'static str]| -> Option<()> {
            let mut iterator = words.iter().rev();
            let mut assume_next = |token: &'static str| -> Option<()> {
                let nxt = iterator.next()?;
                if nxt.as_str() == token.to_lowercase() {
                    return Some(());
                }
                None
            };
            for token in tokens.iter().rev() {
                assume_next(token)?;
            }
            Some(())
        };

        if check_sequence(&["day", "after", "tomorrow"]).is_some() {
            return Some((Self::Overmorrow(DateRelativeLanguage::English), 3));
        }

        for lang in DateRelativeLanguage::iter() {
            for weekday in DateRelativeWeekday::iter() {
                if check_sequence(&[lang.get_noun_next(), weekday.to_locale_static_str(lang)])
                    .is_some()
                {
                    return Some((Self::NextWeekday(lang, weekday), 2));
                }
            }

            for weekday in DateRelativeWeekday::iter() {
                if check_sequence(&[lang.get_noun_prev(), weekday.to_locale_static_str(lang)])
                    .is_some()
                {
                    return Some((Self::LastWeekday(lang, weekday), 2));
                }
            }
        }

        None
    }
}
impl AsDate for DateRelative {
    fn as_date(&self, now: Zoned) -> Result<Date, EventParseError> {
        match self {
            DateRelative::LastWeekday(_, weekday) => {
                let next_such_date = now
                    .nth_weekday(-1, (*weekday).into())
                    .map_err(|_e| EventParseError::AmbiguousTime)?;
                Ok(next_such_date.into())
            }
            DateRelative::Yesterday(_) => {
                let yesterday = now
                    .checked_sub(1.day())
                    .map_err(|_e| EventParseError::AmbiguousTime)?;
                Ok(yesterday.into())
            }
            DateRelative::Today(_) => Ok(now.into()),
            DateRelative::Tomorrow(_) => {
                let tomorrow = now
                    .checked_add(1.day())
                    .map_err(|_e| EventParseError::AmbiguousTime)?;
                Ok(tomorrow.into())
            }
            DateRelative::Overmorrow(_) => {
                let overmorrow = now
                    .checked_add(2.days())
                    .map_err(|_e| EventParseError::AmbiguousTime)?;
                Ok(overmorrow.into())
            }
            DateRelative::NextWeekday(_, weekday) => {
                let next_such_date = now
                    .nth_weekday(1, (*weekday).into())
                    .map_err(|_e| EventParseError::AmbiguousTime)?;
                Ok(next_such_date.into())
            }
        }
    }
}

#[derive(Debug, PartialEq)]
pub enum DateStructured {
    Ymd(i16, i8, i8),
    Ym(i8, i8),
}
impl FromStr for DateStructured {
    type Err = ();

    fn from_str(string: &str) -> Result<Self, Self::Err> {
        let mut split_by_dots = string.split('.');
        let date = split_by_dots
            .next()
            .ok_or(())?
            .parse::<i8>()
            .map_err(|_e| ())?;
        let month = split_by_dots
            .next()
            .ok_or(())?
            .parse::<i8>()
            .map_err(|_e| ())?;
        if let Some(year_segment) = split_by_dots.next().filter(|s| !s.is_empty()) {
            let year = year_segment.parse::<i16>().map_err(|_e| ())?;
            return Ok(Self::Ymd(year, month, date));
        };
        Ok(Self::Ym(month, date))
    }
}
impl AsDate for DateStructured {
    fn as_date(&self, now: Zoned) -> Result<Date, EventParseError> {
        match self {
            DateStructured::Ymd(year, month, day) => Ok(date(*year, *month, *day)),
            DateStructured::Ym(month, day) => {
                let current_year = now.year();
                let current_month = now.month();
                let current_day = now.day();
                if *month < current_month || *month == current_month && *day < current_day {
                    // That date has already passed this year, target next year instead
                    Ok(date(current_year + 1, *month, *day))
                } else {
                    Ok(date(current_year, *month, *day))
                }
            }
        }
    }
}

#[derive(Debug, PartialEq)]
pub enum DateUnit {
    Structured(DateStructured),
    Relative(DateRelative),
}
impl AsDate for DateUnit {
    fn as_date(&self, now: Zoned) -> Result<Date, EventParseError> {
        match self {
            DateUnit::Structured(structured) => structured.as_date(now),
            DateUnit::Relative(relative) => relative.as_date(now),
        }
    }
}

/// Tries to find a date from the supplied string.
/// The date can be expressed as
/// - a full gregorian calendar date in (d)d.(m)m.(yyy)y: 8.12.2000, 13.04.2004, 1.1.0
/// - next matching (d)d.(m)m. gregorian calendar date: 8.12., 13.04., 1.1.
///   - If the date is currently 01.06.2019, the strings above will be parsed as: 8.12.2019,
///     13.04.2020, 1.1.2020
/// - a relative date, such as:
///   - tomorrow
///   - yesterday
///   - ("next"/"last") (weekday)
///   - (not implemented yet) ("next"/"last") (context event)
///   - (not implemented yet) (weekday/"day") ("after"/"before") (context event)
pub fn find_date(s: &str) -> Option<(DateUnit, usize, usize)> {
    let mut start = 0;
    let mut past_words = vec![];
    let mut past_words_start_positions = vec![];
    for word in s.split([' ', ',']) {
        let end = start + word.len();
        past_words.push(word.to_owned());
        past_words_start_positions.push(start);

        if let Some((unit, words_matched)) = DateRelative::parse_multiword(&past_words) {
            start = past_words_start_positions[past_words_start_positions.len() - words_matched];
            return Some((DateUnit::Relative(unit), start, end));
        }
        if let Ok(unit) = word.parse::<DateRelative>() {
            return Some((DateUnit::Relative(unit), start, end));
        }
        if let Ok(unit) = word.parse::<DateStructured>() {
            return Some((DateUnit::Structured(unit), start, end));
        }

        start = end + 1;
    }
    None
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn find_date_trivial_month_date_a() {
        let (unit, start, end) = find_date("John's birthday 18.11.").expect("parse failed");
        assert_eq!(unit, DateUnit::Structured(DateStructured::Ym(11, 18)));
        assert_eq!(start, 16);
        assert_eq!(end, 22);
    }
    #[test]
    fn find_date_trivial_month_date_b() {
        let (unit, start, end) = find_date("Meet with Evelyn 1.12.").expect("parse failed");
        assert_eq!(unit, DateUnit::Structured(DateStructured::Ym(12, 1)));
        assert_eq!(start, 17);
        assert_eq!(end, 22);
    }
    #[test]
    fn find_date_trivial_month_date_c() {
        let (unit, start, end) = find_date("Meet with Evelyn 12.1.").expect("parse failed");
        assert_eq!(unit, DateUnit::Structured(DateStructured::Ym(1, 12)));
        assert_eq!(start, 17);
        assert_eq!(end, 22);
    }
    #[test]
    fn find_date_trivial_year_month_date() {
        let (unit, start, end) = find_date("John's birthday 18.11.2004").expect("parse failed");
        assert_eq!(
            unit,
            DateUnit::Structured(DateStructured::Ymd(2004, 11, 18))
        );
        assert_eq!(start, 16);
        assert_eq!(end, 26);
    }
    #[test]
    fn find_date_relative_a() {
        let (unit, start, end) = find_date("John's birthday tomorrow").expect("parse failed");
        assert_eq!(
            unit,
            DateUnit::Relative(DateRelative::Tomorrow(DateRelativeLanguage::English))
        );
        assert_eq!(start, 16);
        assert_eq!(end, 24);
    }
    #[test]
    fn find_date_relative_b() {
        let (unit, start, end) = find_date("John's birthday yesterday").expect("parse failed");
        assert_eq!(
            unit,
            DateUnit::Relative(DateRelative::Yesterday(DateRelativeLanguage::English))
        );
        assert_eq!(start, 16);
        assert_eq!(end, 25);
    }
    #[test]
    fn find_date_relative_overmorrow_a() {
        let (unit, start, end) = find_date("John's birthday overmorrow").expect("parse failed");
        assert_eq!(
            unit,
            DateUnit::Relative(DateRelative::Overmorrow(DateRelativeLanguage::English))
        );
        assert_eq!(start, 16);
        assert_eq!(end, 26);
    }
    #[test]
    fn find_date_relative_overmorrow_b() {
        let (unit, start, end) =
            find_date("John's birthday day after tomorrow").expect("parse failed");
        assert_eq!(
            unit,
            DateUnit::Relative(DateRelative::Overmorrow(DateRelativeLanguage::English))
        );
        assert_eq!(start, 16);
        assert_eq!(end, 34);
    }

    #[test]
    fn find_date_relative_weekday_a() {
        let (unit, start, end) = find_date("John's birthday next monday").expect("parse failed");
        assert_eq!(
            unit,
            DateUnit::Relative(DateRelative::NextWeekday(
                DateRelativeLanguage::English,
                DateRelativeWeekday::Monday
            ))
        );
        assert_eq!(start, 16);
        assert_eq!(end, 27);
    }
    #[test]
    fn find_date_relative_weekday_b() {
        let (unit, start, end) = find_date("John's birthday next wednesday").expect("parse failed");
        assert_eq!(
            unit,
            DateUnit::Relative(DateRelative::NextWeekday(
                DateRelativeLanguage::English,
                DateRelativeWeekday::Wednesday
            ))
        );
        assert_eq!(start, 16);
        assert_eq!(end, 30);
    }
    #[test]
    fn find_date_relative_weekday_c() {
        let (unit, start, end) =
            find_date("Marian synttärit ensi torstaina").expect("parse failed");
        assert_eq!(
            unit,
            DateUnit::Relative(DateRelative::NextWeekday(
                DateRelativeLanguage::Finnish,
                DateRelativeWeekday::Thurdsday
            ))
        );
        assert_eq!(start, 18);
        assert_eq!(end, 32);
    }

    #[test]
    fn find_date_whitespace_a() {
        let (unit, start, end) = find_date(" John's birthday tomorrow").expect("parse failed");
        assert_eq!(
            unit,
            DateUnit::Relative(DateRelative::Tomorrow(DateRelativeLanguage::English))
        );
        assert_eq!(start, 17);
        assert_eq!(end, 25);
    }
    #[test]
    fn find_date_whitespace_b() {
        let (unit, start, end) = find_date("  John's birthday tomorrow ").expect("parse failed");
        assert_eq!(
            unit,
            DateUnit::Relative(DateRelative::Tomorrow(DateRelativeLanguage::English))
        );
        assert_eq!(start, 18);
        assert_eq!(end, 26);
    }
    #[test]
    fn find_date_whitespace_c() {
        let (unit, start, end) = find_date("John's birthday  yesterday ").expect("parse failed");
        assert_eq!(
            unit,
            DateUnit::Relative(DateRelative::Yesterday(DateRelativeLanguage::English))
        );
        assert_eq!(start, 17);
        assert_eq!(end, 26);
    }
    #[test]
    fn find_date_whitespace_d() {
        let (unit, start, end) = find_date(" John's  birthday   tomorrow ").expect("parse failed");
        assert_eq!(
            unit,
            DateUnit::Relative(DateRelative::Tomorrow(DateRelativeLanguage::English))
        );
        assert_eq!(start, 20);
        assert_eq!(end, 28);
    }
}