1use crate::relative::apply_relative_offset;
2use crate::locale::TimeUnit;
3use crate::settings::{Settings, StartOfWeek};
4use chrono::{Datelike, Duration, NaiveDateTime};
5use regex::Regex;
6use std::sync::OnceLock;
7
8#[derive(Debug, Clone)]
9pub struct TimeSpanMatch {
10 pub span_type: &'static str,
11 pub direction: &'static str,
12 pub number: Option<u32>,
13 pub matched_text: String,
14 pub start_pos: usize,
15 pub end_pos: usize,
16}
17
18struct CompiledSpanPattern {
19 regex: Regex,
20 span_type: &'static str,
21 direction: &'static str,
22 has_num: bool,
23}
24
25static SPAN_PATTERNS: OnceLock<Vec<CompiledSpanPattern>> = OnceLock::new();
26
27fn patterns() -> &'static [CompiledSpanPattern] {
28 SPAN_PATTERNS.get_or_init(|| {
29 let specs = [
30 (r"(?i)\b(?:for\s+the\s+|during\s+the\s+|in\s+the\s+)?(?:past|last|previous)\s+month\b", "month", "past", false),
32 (r"(?i)\b(?:for\s+the\s+|during\s+the\s+|in\s+the\s+)?(?:past|last|previous)\s+week\b", "week", "past", false),
33 (r"(?i)\b(?:for\s+the\s+|during\s+the\s+|in\s+the\s+)?(?:past|last|previous)\s+(\d+)\s+days?\b", "days", "past", true),
34 (r"(?i)\b(?:for\s+the\s+|during\s+the\s+|in\s+the\s+)?(?:past|last|previous)\s+(\d+)\s+weeks?\b", "weeks", "past", true),
35 (r"(?i)\b(?:for\s+the\s+|during\s+the\s+|in\s+the\s+)?(?:past|last|previous)\s+(\d+)\s+months?\b", "months", "past", true),
36 (r"(?i)\b(?:for\s+the\s+|during\s+the\s+|in\s+the\s+)?(?:next|coming|following)\s+month\b", "month", "future", false),
37 (r"(?i)\b(?:for\s+the\s+|during\s+the\s+|in\s+the\s+)?(?:next|coming|following)\s+week\b", "week", "future", false),
38 (r"(?i)\b(?:for\s+the\s+|during\s+the\s+|in\s+the\s+)?(?:next|coming|following)\s+(\d+)\s+days?\b", "days", "future", true),
39 (r"(?i)\b(?:for\s+the\s+|during\s+the\s+|in\s+the\s+)?(?:next|coming|following)\s+(\d+)\s+weeks?\b", "weeks", "future", true),
40 (r"(?i)\b(?:for\s+the\s+|during\s+the\s+|in\s+the\s+)?(?:next|coming|following)\s+(\d+)\s+months?\b", "months", "future", true),
41 (r"(?i)\b(?:geçen|gecen|önceki|onceki)\s+ay\b", "month", "past", false),
43 (r"(?i)\b(?:geçen|gecen|önceki|onceki)\s+hafta\b", "week", "past", false),
44 (r"(?i)\b(?:son|geçen|gecen)\s+(\d+)\s+(?:gün|gun)\b", "days", "past", true),
45 (r"(?i)\b(?:son|geçen|gecen)\s+(\d+)\s+hafta\b", "weeks", "past", true),
46 (r"(?i)\b(?:son|geçen|gecen)\s+(\d+)\s+ay\b", "months", "past", true),
47 (r"(?i)\b(?:gelecek|önümüzdeki|onumuzdeki|sonraki)\s+ay\b", "month", "future", false),
48 (r"(?i)\b(?:gelecek|önümüzdeki|onumuzdeki|sonraki)\s+hafta\b", "week", "future", false),
49 (r"(?i)\b(?:gelecek|önümüzdeki|onumuzdeki|sonraki)\s+(\d+)\s+(?:gün|gun)\b", "days", "future", true),
50 (r"(?i)\b(?:gelecek|önümüzdeki|onumuzdeki|sonraki)\s+(\d+)\s+hafta\b", "weeks", "future", true),
51 (r"(?i)\b(?:gelecek|önümüzdeki|onumuzdeki|sonraki)\s+(\d+)\s+ay\b", "months", "future", true),
52 (r"(?i)\b(?:letzten?|vergangenen?)\s+monat\b", "month", "past", false),
54 (r"(?i)\bletzte\s+woche\b", "week", "past", false),
55 (r"(?i)\b(?:letzten?|vergangenen?)\s+(\d+)\s+tage?n?\b", "days", "past", true),
56 (r"(?i)\b(?:letzten?|vergangenen?)\s+(\d+)\s+wochen?\b", "weeks", "past", true),
57 (r"(?i)\b(?:letzten?|vergangenen?)\s+(\d+)\s+monate?n?\b", "months", "past", true),
58 (r"(?i)\b(?:nächsten?|naechsten?|kommenden?)\s+monat\b", "month", "future", false),
59 (r"(?i)\b(?:nächste|naechste|kommende)\s+woche\b", "week", "future", false),
60 (r"(?i)\b(?:nächsten?|naechsten?|kommenden?)\s+(\d+)\s+tage?n?\b", "days", "future", true),
61 (r"(?i)\b(?:nächsten?|naechsten?|kommenden?)\s+(\d+)\s+wochen?\b", "weeks", "future", true),
62 (r"(?i)\b(?:nächsten?|naechsten?|kommenden?)\s+(\d+)\s+monate?n?\b", "months", "future", true),
63 (r"(?i)\b(?:mois\s+dernier|dernier\s+mois)\b", "month", "past", false),
65 (r"(?i)\b(?:semaine\s+dernière|semaine\s+derniere|dernière\s+semaine)\b", "week", "past", false),
66 (r"(?i)\b(?:(\d+)\s+derniers?\s+jours|derniers?\s+(\d+)\s+jours)\b", "days", "past", true),
67 (r"(?i)\b(?:(\d+)\s+dernières?\s+semaines|(\d+)\s+dernieres?\s+semaines)\b", "weeks", "past", true),
68 (r"(?i)\b(?:(\d+)\s+derniers?\s+mois)\b", "months", "past", true),
69 (r"(?i)\b(?:mois\s+prochain|prochain\s+mois)\b", "month", "future", false),
70 (r"(?i)\b(?:semaine\s+prochaine|prochaine\s+semaine)\b", "week", "future", false),
71 (r"(?i)\b(\d+)\s+prochains?\s+jours\b", "days", "future", true),
72 (r"(?i)\b(\d+)\s+prochaines?\s+semaines\b", "weeks", "future", true),
73 (r"(?i)\b(\d+)\s+prochains?\s+mois\b", "months", "future", true),
74 (r"(?i)\b(?:mes\s+pasado|último\s+mes|ultimo\s+mes)\b", "month", "past", false),
76 (r"(?i)\b(?:semana\s+pasada|última\s+semana|ultima\s+semana)\b", "week", "past", false),
77 (r"(?i)\b(?:últimos|ultimos|pasados)\s+(\d+)\s+(?:días|dias)\b", "days", "past", true),
78 (r"(?i)\b(?:últimas|ultimas|pasadas)\s+(\d+)\s+semanas\b", "weeks", "past", true),
79 (r"(?i)\b(?:últimos|ultimos|pasados)\s+(\d+)\s+meses\b", "months", "past", true),
80 (r"(?i)\b(?:próximo|proximo)\s+mes\b", "month", "future", false),
81 (r"(?i)\b(?:próxima|proxima)\s+semana\b", "week", "future", false),
82 (r"(?i)\b(?:próximos|proximos|siguientes)\s+(\d+)\s+(?:días|dias)\b", "days", "future", true),
83 (r"(?i)\b(?:próximas|proximas|siguientes)\s+(\d+)\s+semanas\b", "weeks", "future", true),
84 (r"(?i)\b(?:próximos|proximos|siguientes)\s+(\d+)\s+meses\b", "months", "future", true),
85 (r"(?i)\b(?:mese\s+scorso|ultimo\s+mese)\b", "month", "past", false),
87 (r"(?i)\b(?:settimana\s+scorsa|ultima\s+settimana)\b", "week", "past", false),
88 (r"(?i)\b(?:ultimi|scorsi)\s+(\d+)\s+giorni?\b", "days", "past", true),
89 (r"(?i)\b(?:ultime|scorse)\s+(\d+)\s+settimane?\b", "weeks", "past", true),
90 (r"(?i)\b(?:ultimi|scorsi)\s+(\d+)\s+mesi\b", "months", "past", true),
91 (r"(?i)\bprossimo\s+mese\b", "month", "future", false),
92 (r"(?i)\bprossima\s+settimana\b", "week", "future", false),
93 (r"(?i)\bprossimi\s+(\d+)\s+giorni?\b", "days", "future", true),
94 (r"(?i)\bprossime\s+(\d+)\s+settimane?\b", "weeks", "future", true),
95 (r"(?i)\bprossimi\s+(\d+)\s+mesi\b", "months", "future", true),
96 (r"(?i)\b(?:mês\s+passado|mes\s+passado|último\s+mês)\b", "month", "past", false),
98 (r"(?i)\b(?:semana\s+passada|última\s+semana)\b", "week", "past", false),
99 (r"(?i)\b(?:últimos|ultimos|passados)\s+(\d+)\s+dias?\b", "days", "past", true),
100 (r"(?i)\b(?:últimas|ultimas|passadas)\s+(\d+)\s+semanas\b", "weeks", "past", true),
101 (r"(?i)\b(?:últimos|ultimos|passados)\s+(\d+)\s+meses\b", "months", "past", true),
102 (r"(?i)\b(?:próximo|proximo)\s+(?:mês|mes)\b", "month", "future", false),
103 (r"(?i)\b(?:próxima|proxima)\s+semana\b", "week", "future", false),
104 (r"(?i)\b(?:próximos|proximos)\s+(\d+)\s+dias?\b", "days", "future", true),
105 (r"(?i)\b(?:próximas|proximas)\s+(\d+)\s+semanas\b", "weeks", "future", true),
106 (r"(?i)\b(?:próximos|proximos)\s+(\d+)\s+meses\b", "months", "future", true),
107 (r"(?i)\b(?:vorige|afgelopen)\s+maand\b", "month", "past", false),
109 (r"(?i)\b(?:vorige|afgelopen)\s+week\b", "week", "past", false),
110 (r"(?i)\b(?:afgelopen|laatste)\s+(\d+)\s+dag(?:en)?\b", "days", "past", true),
111 (r"(?i)\b(?:afgelopen|laatste)\s+(\d+)\s+we(?:ek|ken)\b", "weeks", "past", true),
112 (r"(?i)\b(?:afgelopen|laatste)\s+(\d+)\s+maand(?:en)?\b", "months", "past", true),
113 (r"(?i)\bkomende\s+maand\b", "month", "future", false),
114 (r"(?i)\bvolgende\s+week\b", "week", "future", false),
115 (r"(?i)\bkomende\s+(\d+)\s+dag(?:en)?\b", "days", "future", true),
116 (r"(?i)\bkomende\s+(\d+)\s+we(?:ek|ken)\b", "weeks", "future", true),
117 (r"(?i)\bkomende\s+(\d+)\s+maand(?:en)?\b", "months", "future", true),
118 (r"(?i)\b(?:ostatni|zeszły|poprzedni)\s+miesiąc\b", "month", "past", false),
120 (r"(?i)\b(?:ostatni|zeszły|poprzedni)\s+tydzień\b", "week", "past", false),
121 (r"(?i)\bostatni(?:e|ch)\s+(\d+)\s+(?:dni|dzień)\b", "days", "past", true),
122 (r"(?i)\bostatni(?:e|ch)\s+(\d+)\s+tygodni(?:e|a)?\b", "weeks", "past", true),
123 (r"(?i)\bostatni(?:e|ch)\s+(\d+)\s+miesi(?:ące|ęcy)\b", "months", "past", true),
124 (r"(?i)\bnastępny\s+miesiąc\b", "month", "future", false),
125 (r"(?i)\bnastępny\s+tydzień\b", "week", "future", false),
126 (r"(?i)\bnastępne\s+(\d+)\s+(?:dni|dzień)\b", "days", "future", true),
127 (r"(?i)(?:прошлый|последний)\s+месяц", "month", "past", false),
129 (r"(?i)(?:прошлая|последняя)\s+неделя", "week", "past", false),
130 (r"(?i)(?:последние|прошлые)\s+(\d+)\s+(?:дня|дней|день)", "days", "past", true),
131 (r"(?i)(?:последние|прошлые)\s+(\d+)\s+(?:недели|недель|неделю)", "weeks", "past", true),
132 (r"(?i)(?:последние|прошлые)\s+(\d+)\s+(?:месяца|месяцев|месяц)", "months", "past", true),
133 (r"(?i)следующий\s+месяц", "month", "future", false),
134 (r"(?i)следующая\s+неделя", "week", "future", false),
135 (r"(?i)следующие\s+(\d+)\s+(?:дня|дней|день)", "days", "future", true),
136 (r"(?:先月|上个月|上個月|지난달|지난\s*달)", "month", "past", false),
138 (r"(?:先週|上周|上週|지난주|지난\s*주)", "week", "past", false),
139 (r"(?:来月|下个月|下個月|다음달|다음\s*달)", "month", "future", false),
140 (r"(?:来週|下周|下週|다음주|다음\s*주)", "week", "future", false),
141 (r"(?:過去|过去|지난)\s*(\d+)\s*(?:日間?|天|일)", "days", "past", true),
142 (r"(?:過去|过去|지난)\s*(\d+)\s*(?:週間?|周|週|주)", "weeks", "past", true),
143 (r"(?:今後|未来|앞으로|다음)\s*(\d+)\s*(?:日間?|天|일)", "days", "future", true),
144 ];
145 specs
146 .into_iter()
147 .map(|(pat, span_type, direction, has_num)| CompiledSpanPattern {
148 regex: Regex::new(pat).expect("valid static span regex"),
149 span_type,
150 direction,
151 has_num,
152 })
153 .collect()
154 })
155}
156
157pub fn detect_time_span(text: &str) -> Option<TimeSpanMatch> {
159 if let Some(m) = detect_time_span_inner(text, text, None) {
160 return Some(m);
161 }
162 if let Some((norm, segs)) = replace_span_word_numbers(text) {
163 return detect_time_span_inner(&norm, text, Some(&segs));
164 }
165 None
166}
167
168struct SpanSeg {
169 scan_start: usize,
170 scan_end: usize,
171 orig_start: usize,
172 orig_end: usize,
173}
174
175fn map_scan_span_to_orig(full_start: usize, full_end: usize, orig: &str, segs: &[SpanSeg]) -> (usize, usize) {
176 let mut orig_start = None;
177 let mut orig_end = None;
178 for seg in segs {
179 if seg.scan_end > full_start && orig_start.is_none() {
180 orig_start = Some(if full_start <= seg.scan_start {
181 seg.orig_start
182 } else {
183 let delta = full_start - seg.scan_start;
184 let max_d = seg.orig_end - seg.orig_start;
185 if seg.orig_end - seg.orig_start == seg.scan_end - seg.scan_start && delta <= max_d {
186 seg.orig_start + delta
187 } else {
188 seg.orig_start
189 }
190 });
191 }
192 if seg.scan_start < full_end {
193 orig_end = Some(if full_end >= seg.scan_end {
194 seg.orig_end
195 } else {
196 let delta = full_end - seg.scan_start;
197 let max_d = seg.orig_end - seg.orig_start;
198 if seg.orig_end - seg.orig_start == seg.scan_end - seg.scan_start && delta <= max_d {
199 seg.orig_start + delta
200 } else {
201 seg.orig_end
202 }
203 });
204 }
205 }
206 let s = orig_start.unwrap_or(0).min(orig.len());
207 let e = orig_end.unwrap_or(orig.len()).clamp(s, orig.len());
208 (s, e)
209}
210
211fn detect_time_span_inner(scan: &str, orig: &str, segs: Option<&[SpanSeg]>) -> Option<TimeSpanMatch> {
212 for pat in patterns() {
213 if let Some(caps) = pat.regex.captures(scan) {
214 let full = caps.get(0)?;
215 let number = if pat.has_num {
216 let num_str = caps.iter().skip(1).flatten().next()?.as_str();
217 match num_str.parse::<u32>() {
218 Ok(n) => Some(n),
219 Err(_) => continue,
220 }
221 } else {
222 None
223 };
224 let (start_pos, end_pos, matched_text) = match segs {
225 None => (full.start(), full.end(), full.as_str().to_string()),
226 Some(map) => {
227 let (s, e) = map_scan_span_to_orig(full.start(), full.end(), orig, map);
228 let mt = orig.get(s..e).unwrap_or(full.as_str()).to_string();
229 (s, e, mt)
230 }
231 };
232 return Some(TimeSpanMatch {
233 span_type: pat.span_type,
234 direction: pat.direction,
235 number,
236 matched_text,
237 start_pos,
238 end_pos,
239 });
240 }
241 }
242 None
243}
244
245fn replace_span_word_numbers(text: &str) -> Option<(String, Vec<SpanSeg>)> {
246 let mut toks: Vec<(usize, usize, &str)> = Vec::new();
247 let mut start: Option<usize> = None;
248 for (idx, ch) in text.char_indices() {
249 if ch.is_whitespace() {
250 if let Some(s) = start.take() {
251 toks.push((s, idx, &text[s..idx]));
252 }
253 } else if start.is_none() {
254 start = Some(idx);
255 }
256 }
257 if let Some(s) = start {
258 toks.push((s, text.len(), &text[s..]));
259 }
260 if toks.is_empty() {
261 return None;
262 }
263
264 let reg = crate::locale::LocaleRegistry::global();
265 let cand_locs: Vec<&crate::locale::CompiledLocale> = ["en", "tr", "de", "fr", "es", "it", "pt", "nl", "pl", "ru"]
266 .iter()
267 .filter_map(|c| reg.resolve_lang_id(c).map(|id| ®.locales[id]))
268 .collect();
269 let lowers: Vec<String> = toks
270 .iter()
271 .map(|(_, _, raw)| crate::locale::normalize_digits_and_lower(raw))
272 .collect();
273 let lower_refs: Vec<&str> = lowers.iter().map(String::as_str).collect();
274
275 let mut scan = String::with_capacity(text.len());
276 let mut segs: Vec<SpanSeg> = Vec::with_capacity(toks.len() * 2);
277 let mut changed = false;
278 let mut cursor = 0usize;
279 let mut ti = 0usize;
280
281 while ti < toks.len() {
282 let (tok_start, tok_end, _) = toks[ti];
283 if tok_start > cursor {
284 let ss = scan.len();
285 scan.push_str(&text[cursor..tok_start]);
286 segs.push(SpanSeg {
287 scan_start: ss,
288 scan_end: scan.len(),
289 orig_start: cursor,
290 orig_end: tok_start,
291 });
292 }
293
294 let mut best: Option<(u32, usize)> = None;
295 for loc in &cand_locs {
296 if let Some((val, used)) = crate::numerals::parse_cardinal_slice(&lower_refs[ti..], loc, true) {
297 if lower_refs[ti] == "a" && used == 1 {
299 continue;
300 }
301 if best.is_none_or(|(_, bu)| used > bu) {
302 best = Some((val, used));
303 }
304 }
305 }
306
307 if let Some((val, used)) = best {
308 let group_end = toks[ti + used - 1].1;
309 let ss = scan.len();
310 scan.push_str(&val.to_string());
311 segs.push(SpanSeg {
312 scan_start: ss,
313 scan_end: scan.len(),
314 orig_start: tok_start,
315 orig_end: group_end,
316 });
317 cursor = group_end;
318 ti += used;
319 changed = true;
320 } else {
321 let ss = scan.len();
322 scan.push_str(&text[tok_start..tok_end]);
323 segs.push(SpanSeg {
324 scan_start: ss,
325 scan_end: scan.len(),
326 orig_start: tok_start,
327 orig_end: tok_end,
328 });
329 cursor = tok_end;
330 ti += 1;
331 }
332 }
333 if cursor < text.len() {
334 let ss = scan.len();
335 scan.push_str(&text[cursor..]);
336 segs.push(SpanSeg {
337 scan_start: ss,
338 scan_end: scan.len(),
339 orig_start: cursor,
340 orig_end: text.len(),
341 });
342 }
343
344 if changed {
345 Some((scan, segs))
346 } else {
347 None
348 }
349}
350
351fn week_start(date: NaiveDateTime, start_of_week: StartOfWeek) -> NaiveDateTime {
352 let mut days_back = date.weekday().num_days_from_monday() as i64;
353 if start_of_week != StartOfWeek::Monday {
354 days_back = (days_back + 1) % 7;
355 }
356 date - Duration::days(days_back)
357}
358
359pub fn generate_time_span(
361 span_type: &str,
362 direction: &str,
363 number: u32,
364 base_date: NaiveDateTime,
365 settings: &Settings,
366) -> Option<(NaiveDateTime, NaiveDateTime)> {
367 let past = match direction {
368 "past" => true,
369 "future" => false,
370 _ => return None,
371 };
372 if span_type == "week" {
373 let ws = week_start(base_date, settings.default_start_of_week);
374 let (s_dt, e_dt) = if past {
375 (ws.checked_sub_signed(Duration::days(7))?, ws.checked_sub_signed(Duration::days(1))?)
376 } else {
377 let start = ws.checked_add_signed(Duration::days(7))?;
378 (start, start.checked_add_signed(Duration::days(6))?)
379 };
380 if !(1..=9999).contains(&s_dt.year()) || !(1..=9999).contains(&e_dt.year()) {
381 return None;
382 }
383 return Some((s_dt, e_dt));
384 }
385
386 let sign: i8 = if past { -1 } else { 1 };
387 let other = match span_type {
388 "month" => apply_relative_offset(
389 base_date,
390 sign,
391 settings.default_days_in_month as f64,
392 TimeUnit::Day,
393 )?,
394 "months" => apply_relative_offset(base_date, sign, number as f64, TimeUnit::Month)?,
395 "day" | "days" => apply_relative_offset(base_date, sign, number as f64, TimeUnit::Day)?,
396 "weeks" => apply_relative_offset(base_date, sign, number as f64, TimeUnit::Week)?,
397 "year" | "years" => apply_relative_offset(base_date, sign, number as f64, TimeUnit::Year)?,
398 _ => return None,
399 };
400 if !(1..=9999).contains(&other.year()) || !(1..=9999).contains(&base_date.year()) {
401 return None;
402 }
403
404 if past {
405 Some((other, base_date))
406 } else {
407 Some((base_date, other))
408 }
409}