whichtime_sys/parsers/ru/
weekday.rs1use crate::components::Component;
9use crate::context::ParsingContext;
10use crate::dictionaries::RelativeModifier;
11use crate::dictionaries::ru::{get_relative_modifier, get_weekday};
12use crate::error::Result;
13use crate::parsers::Parser;
14use crate::results::ParsedResult;
15use chrono::{Datelike, Duration};
16use fancy_regex::Regex;
17use std::sync::LazyLock;
18
19static PATTERN: LazyLock<Regex> = LazyLock::new(|| {
20 Regex::new(
21 r"(?ix)
22 (?<![a-zA-Zа-яА-Я])
23 (?:(?:в|во|на|к)\s+)?
24 (?:
25 (?P<prefix>этот|эта|это|эту|следующий|следующая|следующее|следующую|будущий|будущая|будущее|прошлый|прошлая|прошлое|прошлую|предыдущий|предыдущая|предыдущее|последний|последняя)\s+
26 )?
27 (?P<weekday>понедельник|понедельника|пн|вторник|вторника|вт|среда|среды|среду|ср|четверг|четверга|чт|пятница|пятницу|пятницы|пт|суббота|субботу|субботы|сб|воскресенье|воскресенья|вс|вск)
28 (?:\.|,)?
29 (?:
30 \s+
31 (?P<suffix>прошлый|прошлая|прошлое|прошлую|следующий|следующая|следующее|следующую)
32 )?
33 (?=\W|$)"
34 ).unwrap()
35});
36
37pub struct RUWeekdayParser;
39
40impl RUWeekdayParser {
41 pub fn new() -> Self {
42 Self
43 }
44}
45
46impl Default for RUWeekdayParser {
47 fn default() -> Self {
48 Self::new()
49 }
50}
51
52impl Parser for RUWeekdayParser {
53 fn name(&self) -> &'static str {
54 "RUWeekdayParser"
55 }
56
57 fn should_apply(&self, _context: &ParsingContext) -> bool {
58 true
59 }
60
61 fn parse(&self, context: &ParsingContext) -> Result<Vec<ParsedResult>> {
62 let mut results = Vec::new();
63 let ref_date = context.reference.instant;
64 let ref_weekday = ref_date.weekday().num_days_from_sunday() as i64;
65
66 let mut start = 0;
67 while start < context.text.len() {
68 let search_text = &context.text[start..];
69 let captures = match PATTERN.captures(search_text) {
70 Ok(Some(caps)) => caps,
71 Ok(None) => break,
72 Err(_) => break,
73 };
74
75 let full_match = match captures.get(0) {
76 Some(m) => m,
77 None => break,
78 };
79
80 let match_start = start + full_match.start();
81 let match_end = start + full_match.end();
82 let matched_text = full_match.as_str();
83
84 let weekday_str = captures
85 .name("weekday")
86 .map(|m| m.as_str().to_lowercase())
87 .unwrap_or_default();
88 let prefix_str = captures.name("prefix").map(|m| m.as_str().to_lowercase());
89 let suffix_str = captures.name("suffix").map(|m| m.as_str().to_lowercase());
90
91 let clean_wd = weekday_str.trim_end_matches('.').trim_end_matches(',');
92 let Some(weekday) = get_weekday(clean_wd) else {
93 start = match_end;
94 continue;
95 };
96
97 let target_weekday = weekday as i64;
98
99 let modifier = prefix_str
101 .as_ref()
102 .and_then(|s| get_relative_modifier(s))
103 .or_else(|| suffix_str.as_ref().and_then(|s| get_relative_modifier(s)));
104
105 let days_offset = match modifier {
107 Some(RelativeModifier::Next) => {
108 let diff = target_weekday - ref_weekday;
109 if diff <= 0 { diff + 7 } else { diff }
110 }
111 Some(RelativeModifier::Last) => {
112 let diff = target_weekday - ref_weekday;
113 if diff >= 0 { diff - 7 } else { diff }
114 }
115 Some(RelativeModifier::This) | None => {
116 let diff = target_weekday - ref_weekday;
118 if diff == 0 {
119 0
120 } else if diff > 0 {
121 if diff <= 3 { diff } else { diff - 7 }
122 } else if diff >= -3 {
123 diff
124 } else {
125 diff + 7
126 }
127 }
128 };
129
130 let target_date = ref_date + Duration::days(days_offset);
131
132 let mut components = context.create_components();
133 components.assign(Component::Year, target_date.year());
134 components.assign(Component::Month, target_date.month() as i32);
135 components.assign(Component::Day, target_date.day() as i32);
136 components.assign(Component::Weekday, target_weekday as i32);
137
138 let actual_start = matched_text
140 .find(|c: char| c.is_alphanumeric())
141 .unwrap_or(0);
142 let actual_end = matched_text
143 .rfind(|c: char| c.is_alphanumeric())
144 .map(|i| i + matched_text[i..].chars().next().map_or(1, char::len_utf8))
145 .unwrap_or(matched_text.len());
146
147 results.push(context.create_result(
148 match_start + actual_start,
149 match_start + actual_end,
150 components,
151 None,
152 ));
153
154 start = match_end;
155 }
156
157 Ok(results)
158 }
159}