1use crate::fast_path::{days_in_month, parse_time_str, resolve_time_only_date};
2use crate::locale::{
3 fold_diacritics, CompiledLocale, LocaleRegistry, RelativeAffix, RelativeSpec, TimeUnit,
4};
5use crate::settings::{PartOfDay, Period, PreferDatesFrom, Settings};
6use chrono::{Datelike, Duration, NaiveDate, NaiveDateTime, NaiveTime};
7
8#[derive(Debug, Clone)]
9pub struct RelativeMatch {
10 pub naive: NaiveDateTime,
11 pub period: Period,
12 pub locale: String,
13 pub has_time: bool,
14 pub parts: Vec<&'static str>,
15 pub part_of_day: Option<PartOfDay>,
16}
17
18pub fn apply_relative_offset(
20 base: NaiveDateTime,
21 sign: i8,
22 amount: f64,
23 unit: TimeUnit,
24) -> Option<NaiveDateTime> {
25 if !amount.is_finite() || amount < 0.0 || amount > 10_000_000.0 {
26 return None;
27 }
28 let signed = if sign < 0 { -amount } else { amount };
29 let dt = match unit {
30 TimeUnit::Second => {
31 let ms = (signed * 1000.0).round() as i64;
32 base.checked_add_signed(Duration::milliseconds(ms))?
33 }
34 TimeUnit::Minute => {
35 let ms = (signed * 60_000.0).round() as i64;
36 base.checked_add_signed(Duration::milliseconds(ms))?
37 }
38 TimeUnit::Hour => {
39 let ms = (signed * 3_600_000.0).round() as i64;
40 base.checked_add_signed(Duration::milliseconds(ms))?
41 }
42 TimeUnit::Day => {
43 if amount > 3_650_000.0 {
44 return None;
45 }
46 let ms = (signed * 86_400_000.0).round() as i64;
47 base.checked_add_signed(Duration::milliseconds(ms))?
48 }
49 TimeUnit::Week => {
50 if amount > 520_000.0 {
51 return None;
52 }
53 let ms = (signed * 7.0 * 86_400_000.0).round() as i64;
54 base.checked_add_signed(Duration::milliseconds(ms))?
55 }
56 TimeUnit::Fortnight => {
57 if amount > 260_000.0 {
58 return None;
59 }
60 let ms = (signed * 14.0 * 86_400_000.0).round() as i64;
61 base.checked_add_signed(Duration::milliseconds(ms))?
62 }
63 TimeUnit::Month => {
64 if amount > 120_000.0 {
65 return None;
66 }
67 add_months(base, signed.round() as i32)?
68 }
69 TimeUnit::Year => {
70 if amount > 9_999.0 {
71 return None;
72 }
73 add_months(base, (signed * 12.0).round() as i32)?
74 }
75 TimeUnit::Decade => {
76 if amount > 1_000.0 {
77 return None;
78 }
79 add_months(base, (signed * 120.0).round() as i32)?
80 }
81 TimeUnit::Century => {
82 if amount > 100.0 {
83 return None;
84 }
85 add_months(base, (signed * 1200.0).round() as i32)?
86 }
87 };
88 if !(1..=9999).contains(&dt.year()) {
89 return None;
90 }
91 Some(dt)
92}
93
94fn add_months(base: NaiveDateTime, delta_months: i32) -> Option<NaiveDateTime> {
95 let total_months = (base.year() * 12 + (base.month() as i32 - 1)) + delta_months;
96 let new_year = total_months.div_euclid(12);
97 let new_month = (total_months.rem_euclid(12) + 1) as u32;
98 let max_day = days_in_month(new_year, new_month);
99 let new_day = base.day().min(max_day);
100 let nd = NaiveDate::from_ymd_opt(new_year, new_month, new_day)?;
101 Some(nd.and_time(base.time()))
102}
103
104fn period_for_unit(unit: TimeUnit) -> Period {
105 match unit {
106 TimeUnit::Year | TimeUnit::Decade | TimeUnit::Century => Period::Year,
107 TimeUnit::Month => Period::Month,
108 TimeUnit::Week => Period::Week,
109 _ => Period::Day,
110 }
111}
112
113fn parts_for_relative(has_time: bool, unit: Option<TimeUnit>) -> Vec<&'static str> {
114 let time_unit = matches!(
115 unit,
116 Some(TimeUnit::Hour | TimeUnit::Minute | TimeUnit::Second)
117 );
118 if has_time || time_unit {
119 vec!["year", "month", "day", "time"]
120 } else {
121 vec!["year", "month", "day"]
122 }
123}
124
125fn time_for_hour_anchor(hour: u8, settings: &Settings) -> (NaiveTime, Option<PartOfDay>) {
126 match hour {
127 3 | 6 => (settings.parts_of_day.time_for(PartOfDay::EarlyMorning), Some(PartOfDay::EarlyMorning)),
128 9 => (settings.parts_of_day.time_for(PartOfDay::Morning), Some(PartOfDay::Morning)),
129 15 => (settings.parts_of_day.time_for(PartOfDay::Afternoon), Some(PartOfDay::Afternoon)),
130 18 => (settings.parts_of_day.time_for(PartOfDay::Evening), Some(PartOfDay::Evening)),
131 20 => (settings.parts_of_day.time_for(PartOfDay::Night), Some(PartOfDay::Night)),
132 12 => (NaiveTime::from_hms_opt(12, 0, 0).unwrap(), None),
133 0 => (NaiveTime::from_hms_opt(0, 0, 0).unwrap(), None),
134 h => (NaiveTime::from_hms_opt(h as u32, 0, 0).unwrap(), None),
135 }
136}
137
138fn select_relative_spec(specs: &[RelativeSpec], pref: PreferDatesFrom) -> RelativeSpec {
139 if specs.len() == 1 {
140 return specs[0];
141 }
142 match pref {
143 PreferDatesFrom::Past => specs
144 .iter()
145 .copied()
146 .find(|s| s.sign < 0)
147 .unwrap_or(specs[0]),
148 PreferDatesFrom::Future | PreferDatesFrom::CurrentPeriod => specs
149 .iter()
150 .copied()
151 .find(|s| s.sign > 0)
152 .unwrap_or(specs[0]),
153 }
154}
155
156fn lookup_exact_in_locale(
157 phrase: &str,
158 loc: &CompiledLocale,
159 normalize: bool,
160 pref: PreferDatesFrom,
161) -> Option<RelativeSpec> {
162 if let Some(specs) = loc.relative_exact.get(phrase) {
163 return Some(select_relative_spec(specs, pref));
164 }
165 if normalize {
166 let f = fold_diacritics(phrase);
167 if let Some(specs) = loc.folded_relative_exact.get(&f) {
168 return Some(select_relative_spec(specs, pref));
169 }
170 }
171 None
172}
173
174pub fn try_parse_relative(
176 normalized: &str,
177 candidate_ids: &[usize],
178 registry: &LocaleRegistry,
179 settings: &Settings,
180) -> Option<RelativeMatch> {
181 if settings.strict_parsing {
182 return None;
183 }
184
185 let base = settings.effective_base();
186 let trimmed_article = normalized.strip_prefix("the ").unwrap_or(normalized);
187 let folded_full = if settings.normalize {
188 fold_diacritics(trimmed_article)
189 } else {
190 trimmed_article.to_string()
191 };
192
193 if let Some(m) = try_conversational_clock_or_fraction(trimmed_article, settings) {
195 return Some(m);
196 }
197 if let Some(m) = try_compound_tod_idiom(trimmed_article, &folded_full, candidate_ids, registry, base, settings) {
198 return Some(m);
199 }
200
201 if let Some(matches) = registry.exact_phrase_index.get(trimmed_article) {
203 let mut matched_specs: Vec<(usize, RelativeSpec)> = Vec::new();
204 if settings.use_given_language_order && !candidate_ids.is_empty() {
205 for &cid in candidate_ids {
206 for &(lid, spec) in matches {
207 if lid as usize == cid {
208 matched_specs.push((cid, spec));
209 }
210 }
211 }
212 } else {
213 for &(lid, spec) in matches {
214 let lid_usize = lid as usize;
215 if candidate_ids.is_empty() || candidate_ids.contains(&lid_usize) {
216 matched_specs.push((lid_usize, spec));
217 }
218 }
219 }
220 if !matched_specs.is_empty() {
221 let specs_only: Vec<RelativeSpec> = if settings.use_given_language_order && !candidate_ids.is_empty() {
222 let first_lid = matched_specs[0].0;
223 matched_specs
224 .iter()
225 .filter(|(l, _)| *l == first_lid)
226 .map(|(_, s)| *s)
227 .collect()
228 } else {
229 matched_specs.iter().map(|(_, s)| *s).collect()
230 };
231 let chosen = select_relative_spec(&specs_only, settings.prefer_dates_from);
232 let chosen_lid = matched_specs
233 .iter()
234 .find(|(_, s)| *s == chosen)
235 .map(|(l, _)| *l)
236 .unwrap_or(matched_specs[0].0);
237 let dt = apply_relative_offset(base, chosen.sign, chosen.amount as f64, chosen.unit)?;
238 return Some(RelativeMatch {
239 naive: dt,
240 period: period_for_unit(chosen.unit),
241 locale: registry.locales[chosen_lid].code.clone(),
242 has_time: false,
243 parts: parts_for_relative(false, Some(chosen.unit)),
244 part_of_day: None,
245 });
246 }
247 }
248
249 if settings.normalize {
250 if let Some(matches) = registry.folded_exact_phrase_index.get(&folded_full) {
251 let mut matched_specs: Vec<(usize, RelativeSpec)> = Vec::new();
252 if settings.use_given_language_order && !candidate_ids.is_empty() {
253 for &cid in candidate_ids {
254 for &(lid, spec) in matches {
255 if lid as usize == cid {
256 matched_specs.push((cid, spec));
257 }
258 }
259 }
260 } else {
261 for &(lid, spec) in matches {
262 let lid_usize = lid as usize;
263 if candidate_ids.is_empty() || candidate_ids.contains(&lid_usize) {
264 matched_specs.push((lid_usize, spec));
265 }
266 }
267 }
268 if !matched_specs.is_empty() {
269 let specs_only: Vec<RelativeSpec> = if settings.use_given_language_order && !candidate_ids.is_empty() {
270 let first_lid = matched_specs[0].0;
271 matched_specs
272 .iter()
273 .filter(|(l, _)| *l == first_lid)
274 .map(|(_, s)| *s)
275 .collect()
276 } else {
277 matched_specs.iter().map(|(_, s)| *s).collect()
278 };
279 let chosen = select_relative_spec(&specs_only, settings.prefer_dates_from);
280 let chosen_lid = matched_specs
281 .iter()
282 .find(|(_, s)| *s == chosen)
283 .map(|(l, _)| *l)
284 .unwrap_or(matched_specs[0].0);
285 let dt = apply_relative_offset(base, chosen.sign, chosen.amount as f64, chosen.unit)?;
286 return Some(RelativeMatch {
287 naive: dt,
288 period: period_for_unit(chosen.unit),
289 locale: registry.locales[chosen_lid].code.clone(),
290 has_time: false,
291 parts: parts_for_relative(false, Some(chosen.unit)),
292 part_of_day: None,
293 });
294 }
295 }
296 }
297
298 let (phrase_no_time, extracted_time) = extract_trailing_or_leading_time(normalized);
300
301 for &lid in candidate_ids {
302 let loc = ®istry.locales[lid];
303
304 if let Some(t) = extracted_time {
306 let cleaned = strip_connector_words(phrase_no_time, loc);
307 if let Some(spec) = lookup_exact_in_locale(cleaned, loc, settings.normalize, settings.prefer_dates_from) {
308 let dt = apply_relative_offset(base, spec.sign, spec.amount as f64, spec.unit)?;
309 return Some(RelativeMatch {
310 naive: dt.date().and_time(t),
311 period: Period::Day,
312 locale: loc.code.clone(),
313 has_time: true,
314 parts: vec!["year", "month", "day", "time"],
315 part_of_day: None,
316 });
317 }
318 }
319
320 if extracted_time.is_none() {
322 if let Some((dt, pod)) = try_relative_plus_tod(normalized, loc, base, settings) {
323 return Some(RelativeMatch {
324 naive: dt,
325 period: Period::Day,
326 locale: loc.code.clone(),
327 has_time: true,
328 parts: vec!["year", "month", "day", "time"],
329 part_of_day: pod,
330 });
331 }
332 }
333
334 let target_str = if extracted_time.is_some() {
336 strip_connector_words(phrase_no_time, loc)
337 } else {
338 normalized
339 };
340
341 if let Some((spec_sign, amount, unit)) = try_affix_match(target_str, loc, settings.normalize) {
342 let mut dt = apply_relative_offset(base, spec_sign, amount, unit)?;
343 if let Some(t) = extracted_time {
344 dt = dt.date().and_time(t);
345 }
346 let has_t = extracted_time.is_some();
347 return Some(RelativeMatch {
348 naive: dt,
349 period: if has_t { Period::Day } else { period_for_unit(unit) },
350 locale: loc.code.clone(),
351 has_time: has_t,
352 parts: parts_for_relative(has_t, Some(unit)),
353 part_of_day: None,
354 });
355 }
356
357 if let Some((mut dt, period, has_time_unit)) =
359 try_compound_relative(target_str, loc, base, settings.normalize)
360 {
361 if let Some(t) = extracted_time {
362 dt = dt.date().and_time(t);
363 }
364 let has_t = extracted_time.is_some();
365 return Some(RelativeMatch {
366 naive: dt,
367 period: if has_t { Period::Day } else { period },
368 locale: loc.code.clone(),
369 has_time: has_t,
370 parts: if has_t || has_time_unit {
371 vec!["year", "month", "day", "time"]
372 } else {
373 vec!["year", "month", "day"]
374 },
375 part_of_day: None,
376 });
377 }
378
379 if let Some((mut dt, period, has_time_unit)) =
381 try_bare_duration_relative(target_str, loc, base, settings)
382 {
383 if let Some(t) = extracted_time {
384 dt = dt.date().and_time(t);
385 }
386 let has_t = extracted_time.is_some();
387 return Some(RelativeMatch {
388 naive: dt,
389 period: if has_t { Period::Day } else { period },
390 locale: loc.code.clone(),
391 has_time: has_t,
392 parts: if has_t || has_time_unit {
393 vec!["year", "month", "day", "time"]
394 } else {
395 vec!["year", "month", "day"]
396 },
397 part_of_day: None,
398 });
399 }
400
401 if let Some((mut dt, period)) =
403 try_relative_period_or_weekday(target_str, loc, base, settings.normalize)
404 {
405 if let Some(t) = extracted_time {
406 dt = dt.date().and_time(t);
407 }
408 let has_t = extracted_time.is_some();
409 return Some(RelativeMatch {
410 naive: dt,
411 period: if has_t { Period::Day } else { period },
412 locale: loc.code.clone(),
413 has_time: has_t,
414 parts: parts_for_relative(has_t, None),
415 part_of_day: None,
416 });
417 }
418 }
419
420 None
421}
422
423fn try_compound_tod_idiom(
424 normalized: &str,
425 folded: &str,
426 candidate_ids: &[usize],
427 registry: &LocaleRegistry,
428 base: NaiveDateTime,
429 settings: &Settings,
430) -> Option<RelativeMatch> {
431 let check = if settings.normalize { folded } else { normalized };
432 let (day_offset, hour, lang_code): (i64, u8, &str) = match check {
433 "tonight" | "this night" => (0, 20, "en"),
434 "last night" => (-1, 20, "en"),
435 "this morning" | "today morning" => (0, 9, "en"),
436 "this afternoon" | "today afternoon" => (0, 15, "en"),
437 "this evening" | "today evening" => (0, 18, "en"),
438 "day before yesterday" => {
439 let dt = base - Duration::days(2);
440 return Some(RelativeMatch {
441 naive: dt,
442 period: Period::Day,
443 locale: "en".to_string(),
444 has_time: false,
445 parts: vec!["year", "month", "day"],
446 part_of_day: None,
447 });
448 }
449 "day after tomorrow" => {
450 let dt = base + Duration::days(2);
451 return Some(RelativeMatch {
452 naive: dt,
453 period: Period::Day,
454 locale: "en".to_string(),
455 has_time: false,
456 parts: vec!["year", "month", "day"],
457 part_of_day: None,
458 });
459 }
460 "yesterday morning" => (-1, 9, "en"),
461 "yesterday afternoon" => (-1, 15, "en"),
462 "yesterday evening" => (-1, 18, "en"),
463 "tomorrow morning" => (1, 9, "en"),
464 "tomorrow evening" => (1, 18, "en"),
465 "tomorrow night" => (1, 20, "en"),
466 "dün gece" | "dun gece" => (-1, 20, "tr"),
467 "dün akşam" | "dun aksam" => (-1, 18, "tr"),
468 "dün sabah" | "dun sabah" => (-1, 9, "tr"),
469 "bu akşam" | "bu aksam" => (0, 18, "tr"),
470 "bu sabah" => (0, 9, "tr"),
471 "bu gece" => (0, 20, "tr"),
472 "yarın sabah" | "yarin sabah" => (1, 9, "tr"),
473 "yarın akşam" | "yarin aksam" => (1, 18, "tr"),
474 "heute abend" => (0, 18, "de"),
475 "heute morgen" => (0, 9, "de"),
476 "gestern abend" => (-1, 18, "de"),
477 "heute nacht" => (0, 20, "de"),
478 "ce soir" => (0, 18, "fr"),
479 "ce matin" => (0, 9, "fr"),
480 "hier soir" => (-1, 18, "fr"),
481 "anoche" => (-1, 20, "es"),
482 "esta noche" => (0, 20, "es"),
483 "esta tarde" => (0, 15, "es"),
484 _ => return None,
485 };
486
487 if !candidate_ids.is_empty() {
488 let lang_allowed = candidate_ids
489 .iter()
490 .any(|&id| registry.locales[id].code == lang_code);
491 if !lang_allowed {
492 return None;
493 }
494 }
495
496 let target_date = (base + Duration::days(day_offset)).date();
497 let (nt, pod) = time_for_hour_anchor(hour, settings);
498 Some(RelativeMatch {
499 naive: target_date.and_time(nt),
500 period: Period::Day,
501 locale: lang_code.to_string(),
502 has_time: true,
503 parts: vec!["year", "month", "day", "time"],
504 part_of_day: pod,
505 })
506}
507
508fn split_tod_hour<'a>(
509 s: &'a str,
510 loc: &CompiledLocale,
511 normalize: bool,
512) -> Option<(&'a str, u8)> {
513 for (phrase, &hour) in &loc.time_of_day {
514 if let Some(rest) = s.strip_suffix(phrase.as_str()) {
515 if rest.is_empty() || rest.ends_with(' ') {
516 return Some((rest.trim_end(), hour));
517 }
518 }
519 }
520 if normalize {
521 let fs = fold_diacritics(s);
522 for (phrase, &hour) in &loc.folded_time_of_day {
523 if let Some(rest) = fs.strip_suffix(phrase.as_str()) {
524 if rest.is_empty() || rest.ends_with(' ') {
525 return Some((s[..rest.len().min(s.len())].trim_end(), hour));
526 }
527 }
528 }
529 for (phrase, &hour) in &loc.time_of_day {
530 if let Some(rest) = fs.strip_suffix(phrase.as_str()) {
531 if rest.is_empty() || rest.ends_with(' ') {
532 return Some((s[..rest.len().min(s.len())].trim_end(), hour));
533 }
534 }
535 }
536 }
537 None
538}
539
540fn try_relative_plus_tod(
541 normalized: &str,
542 loc: &CompiledLocale,
543 base: NaiveDateTime,
544 settings: &Settings,
545) -> Option<(NaiveDateTime, Option<PartOfDay>)> {
546 let (prefix_raw, hour) = split_tod_hour(normalized, loc, settings.normalize)?;
547 let (nt, pod) = time_for_hour_anchor(hour, settings);
548 if prefix_raw.is_empty() {
549 return Some((base.date().and_time(nt), pod));
550 }
551
552 let cleaned = strip_connector_words(prefix_raw, loc);
553 if let Some(spec) = lookup_exact_in_locale(
554 cleaned,
555 loc,
556 settings.normalize,
557 settings.prefer_dates_from,
558 ) {
559 let dt = apply_relative_offset(base, spec.sign, spec.amount as f64, spec.unit)?;
560 return Some((dt.date().and_time(nt), pod));
561 }
562
563 None
564}
565
566fn try_affix_match(s: &str, loc: &CompiledLocale, normalize: bool) -> Option<(i8, f64, TimeUnit)> {
568 let mut candidates: Vec<String> = Vec::with_capacity(3);
569 candidates.push(s.to_string());
570 if let Some(r) = replace_word_numbers_once(s, loc, normalize) {
571 candidates.push(r);
572 }
573 if normalize {
574 let fs = fold_diacritics(s);
575 if fs != s {
576 if let Some(r) = replace_word_numbers_once(&fs, loc, true) {
577 candidates.push(r);
578 }
579 candidates.push(fs);
580 }
581 }
582
583 let match_against = |cand: &str, affixes: &[RelativeAffix]| -> Option<(i8, f64, TimeUnit)> {
584 for affix in affixes {
585 let after_prefix = if affix.prefix.is_empty() {
586 cand
587 } else if let Some(rest) = cand.strip_prefix(&affix.prefix) {
588 rest
589 } else {
590 continue;
591 };
592
593 let middle = if affix.suffix.is_empty() {
594 after_prefix
595 } else if let Some(rest) = after_prefix.strip_suffix(&affix.suffix) {
596 rest
597 } else {
598 continue;
599 };
600
601 let num_str = middle.trim();
602 if let Some(val) = parse_positive_number(num_str) {
603 return Some((affix.sign, val, affix.unit));
604 }
605 }
606 None
607 };
608
609 for cand in &candidates {
610 if let Some(hit) = match_against(cand, &loc.relative_affix) {
611 return Some(hit);
612 }
613 }
614 if normalize && !loc.folded_relative_affix.is_empty() {
615 for cand in &candidates {
616 if let Some(hit) = match_against(cand, &loc.folded_relative_affix) {
617 return Some(hit);
618 }
619 }
620 }
621 None
622}
623
624fn parse_positive_number(s: &str) -> Option<f64> {
625 if s.is_empty() || s.len() > 12 {
626 return None;
627 }
628 let mut seen_sep = false;
629 let mut has_digit = false;
630 for b in s.bytes() {
631 if b.is_ascii_digit() {
632 has_digit = true;
633 } else if (b == b'.' || b == b',') && !seen_sep {
634 seen_sep = true;
635 } else {
636 return None;
637 }
638 }
639 if !has_digit {
640 return None;
641 }
642 if s.contains(',') {
643 s.replace(',', ".").parse::<f64>().ok()
644 } else {
645 s.parse::<f64>().ok()
646 }
647}
648
649fn replace_word_numbers_once(s: &str, loc: &CompiledLocale, normalize: bool) -> Option<String> {
650 if loc.word_numbers.is_empty() {
651 return None;
652 }
653 let mut changed = false;
654 let mut parts = Vec::new();
655 for tok in s.split_whitespace() {
656 if let Some(&n) = loc.word_numbers.get(tok) {
657 parts.push(n.to_string());
658 changed = true;
659 } else if normalize {
660 let ft = fold_diacritics(tok);
661 if let Some(&n) = loc.word_numbers.get(&ft) {
662 parts.push(n.to_string());
663 changed = true;
664 } else {
665 parts.push(tok.to_string());
666 }
667 } else {
668 parts.push(tok.to_string());
669 }
670 }
671 if changed {
672 Some(parts.join(" "))
673 } else {
674 None
675 }
676}
677
678fn try_compound_relative(
679 s: &str,
680 loc: &CompiledLocale,
681 base: NaiveDateTime,
682 normalize: bool,
683) -> Option<(NaiveDateTime, Period, bool)> {
684 let mut sign: Option<i8> = None;
685 let mut rest = s.trim().to_string();
686
687 let strip_marker = |text: &str, markers: &rustc_hash::FxHashSet<String>| -> Option<String> {
688 for w in markers {
689 if let Some(stripped) = text.strip_suffix(w.as_str()) {
690 if stripped.is_empty() || stripped.ends_with(' ') || !w.is_ascii() {
691 return Some(stripped.trim().to_string());
692 }
693 }
694 if let Some(stripped) = text.strip_prefix(w.as_str()) {
695 if stripped.is_empty() || stripped.starts_with(' ') || !w.is_ascii() {
696 return Some(stripped.trim().to_string());
697 }
698 }
699 }
700 None
701 };
702
703 if let Some(r) = strip_marker(&rest, &loc.ago) {
704 sign = Some(-1);
705 rest = r;
706 } else if normalize {
707 let f_rest = fold_diacritics(&rest);
708 if let Some(r) = strip_marker(&f_rest, &loc.folded_ago) {
709 sign = Some(-1);
710 rest = r;
711 } else if let Some(r) = strip_marker(&f_rest, &loc.ago) {
712 sign = Some(-1);
713 rest = r;
714 }
715 }
716
717 if sign.is_none() {
718 if let Some(r) = strip_marker(&rest, &loc.in_words) {
719 sign = Some(1);
720 rest = r;
721 } else if normalize {
722 let f_rest = fold_diacritics(&rest);
723 if let Some(r) = strip_marker(&f_rest, &loc.folded_in_words) {
724 sign = Some(1);
725 rest = r;
726 } else if let Some(r) = strip_marker(&f_rest, &loc.in_words) {
727 sign = Some(1);
728 rest = r;
729 }
730 }
731 }
732
733 let sign = sign?;
734 if rest.is_empty() {
735 return None;
736 }
737
738 apply_token_duration_pairs(&rest, loc, base, sign, normalize, true)
739}
740
741fn try_bare_duration_relative(
742 s: &str,
743 loc: &CompiledLocale,
744 base: NaiveDateTime,
745 settings: &Settings,
746) -> Option<(NaiveDateTime, Period, bool)> {
747 let sign = if settings.prefer_dates_from == PreferDatesFrom::Future {
748 1
749 } else {
750 -1
751 };
752 apply_token_duration_pairs(s, loc, base, sign, settings.normalize, false)
753}
754
755fn apply_token_duration_pairs(
756 rest: &str,
757 loc: &CompiledLocale,
758 base: NaiveDateTime,
759 sign: i8,
760 normalize: bool,
761 allow_single_char_attached_units: bool,
762) -> Option<(NaiveDateTime, Period, bool)> {
763 let lookup_unit = |tok: &str| -> Option<TimeUnit> {
764 if let Some(&u) = loc.units.get(tok) {
765 return Some(u);
766 }
767 if normalize {
768 let ft = fold_diacritics(tok);
769 if let Some(&u) = loc.units.get(&ft).or_else(|| loc.folded_units.get(&ft)) {
770 return Some(u);
771 }
772 }
773 None
774 };
775
776 let tokens: Vec<&str> = rest
777 .split(|c: char| c.is_whitespace() || c == ',' || c == ';')
778 .filter(|t| !t.is_empty())
779 .collect();
780
781 let mut pairs: Vec<(f64, TimeUnit)> = Vec::new();
782 let mut pending_num: Option<f64> = None;
783
784 for &tok in &tokens {
785 let clean = tok.trim_matches(|c: char| c == ',' || c == '.');
786 if clean.is_empty() {
787 continue;
788 }
789 if matches!(clean, "and" | "ve" | "und" | "et" | "y" | "e" | "of") || loc.skip.contains(clean)
790 {
791 continue;
792 }
793
794 if pending_num.is_none() && allow_single_char_attached_units {
795 if let Some((num, unit_str)) = split_attached_num_unit(clean) {
796 if let Some(u) = lookup_unit(unit_str) {
797 pairs.push((num, u));
798 continue;
799 }
800 }
801 }
802
803 if let Some(n) = parse_positive_number(clean) {
804 if pending_num.is_some() {
805 return None;
806 }
807 pending_num = Some(n);
808 } else if let Some(&wn) = loc.word_numbers.get(clean) {
809 if pending_num.is_some() {
810 return None;
811 }
812 pending_num = Some(wn as f64);
813 } else if let Some(u) = lookup_unit(clean) {
814 if !allow_single_char_attached_units && pending_num.is_none() {
815 return None;
816 }
817 if !allow_single_char_attached_units && clean.chars().count() < 2 {
818 return None;
819 }
820 let amt = pending_num.take().unwrap_or(1.0);
821 pairs.push((amt, u));
822 } else {
823 return None;
824 }
825 }
826
827 if pairs.is_empty() || pending_num.is_some() {
828 return None;
829 }
830
831 let mut dt = base;
832 let mut finest_period = Period::Year;
833 let mut has_time_unit = false;
834 for (amt, unit) in pairs {
835 if !allow_single_char_attached_units && unit == TimeUnit::Year && amt >= 1000.0 {
837 return None;
838 }
839 if matches!(unit, TimeUnit::Hour | TimeUnit::Minute | TimeUnit::Second) {
840 has_time_unit = true;
841 }
842 dt = apply_relative_offset(dt, sign, amt, unit)?;
843 let p = period_for_unit(unit);
844 let rank = |per: Period| match per {
845 Period::Year => 0,
846 Period::Month => 1,
847 Period::Week => 2,
848 Period::Day => 3,
849 Period::Time => 4,
850 };
851 if rank(p) > rank(finest_period) {
852 finest_period = p;
853 }
854 }
855
856 Some((dt, finest_period, has_time_unit))
857}
858
859fn split_attached_num_unit(s: &str) -> Option<(f64, &str)> {
860 let idx = s.find(|c: char| !c.is_ascii_digit() && c != '.' && c != ',')?;
861 if idx == 0 {
862 return None;
863 }
864 let num = parse_positive_number(&s[..idx])?;
865 let unit = &s[idx..];
866 if unit.is_empty() {
867 return None;
868 }
869 Some((num, unit))
870}
871
872fn try_relative_period_or_weekday(
873 s: &str,
874 loc: &CompiledLocale,
875 base: NaiveDateTime,
876 normalize: bool,
877) -> Option<(NaiveDateTime, Period)> {
878 let fs = if normalize {
879 fold_diacritics(s)
880 } else {
881 s.to_string()
882 };
883 let tokens: Vec<&str> = fs.split_whitespace().collect();
884 if tokens.len() != 2 {
885 return None;
886 }
887 let (modifier, target_tok) = (tokens[0], tokens[1]);
888 let dir: i8 = match modifier {
889 "last" | "previous" | "geçen" | "gecen" | "letzten" | "letzter" | "letzte" | "dernier"
890 | "dernière" | "pasado" | "pasada" | "прошлый" | "прошлая" => -1,
891 "next" | "gelecek" | "önümüzdeki" | "onumuzdeki" | "nächsten" | "nächster" | "nächste"
892 | "prochain" | "prochaine" | "próximo" | "proximo" | "следующий" => 1,
893 "this" | "bu" | "diesen" | "diese" | "ce" | "cette" | "este" | "esta" => 0,
894 _ => return None,
895 };
896
897 let unit_opt = loc.units.get(target_tok).copied().or_else(|| {
898 if normalize {
899 loc.folded_units.get(target_tok).copied()
900 } else {
901 None
902 }
903 });
904 if let Some(unit) = unit_opt {
905 let period = period_for_unit(unit);
906 if dir == 0 {
907 return Some((base, period));
908 }
909 return apply_relative_offset(base, dir, 1.0, unit).map(|dt| (dt, period));
910 }
911
912 let target_wd = loc.weekdays.get(target_tok).copied().or_else(|| {
913 if normalize {
914 loc.folded_weekdays.get(target_tok).copied()
915 } else {
916 None
917 }
918 })?;
919
920 let current_wd = base.weekday().num_days_from_monday() as i64;
921 let target = target_wd as i64;
922 let delta_days = if dir < 0 {
923 let mut diff = target - current_wd;
924 if diff >= 0 {
925 diff -= 7;
926 }
927 diff
928 } else if dir > 0 {
929 let mut diff = target - current_wd;
930 if diff <= 0 {
931 diff += 7;
932 }
933 diff
934 } else {
935 target - current_wd
936 };
937
938 base.checked_add_signed(Duration::days(delta_days))
939 .map(|dt| (dt.date().and_hms_opt(0, 0, 0).unwrap_or(dt), Period::Day))
940}
941
942pub fn try_conversational_clock_or_fraction(
945 normalized: &str,
946 settings: &Settings,
947) -> Option<RelativeMatch> {
948 let base = settings.effective_base();
949 let s = if settings.normalize {
950 fold_diacritics(normalized)
951 } else {
952 normalized.to_string()
953 };
954 let s = s.trim();
955
956 if matches!(
957 s,
958 "half an hour ago" | "half hour ago" | "yarım saat önce" | "yarim saat once"
959 ) {
960 let dt = apply_relative_offset(base, -1, 30.0, TimeUnit::Minute)?;
961 return Some(RelativeMatch {
962 naive: dt,
963 period: Period::Day,
964 locale: if s.contains("saat") { "tr" } else { "en" }.to_string(),
965 has_time: false,
966 parts: vec!["year", "month", "day", "time"],
967 part_of_day: None,
968 });
969 }
970 if matches!(
971 s,
972 "in half an hour" | "in half hour" | "yarım saat sonra" | "yarim saat sonra"
973 ) {
974 let dt = apply_relative_offset(base, 1, 30.0, TimeUnit::Minute)?;
975 return Some(RelativeMatch {
976 naive: dt,
977 period: Period::Day,
978 locale: if s.contains("saat") { "tr" } else { "en" }.to_string(),
979 has_time: false,
980 parts: vec!["year", "month", "day", "time"],
981 part_of_day: None,
982 });
983 }
984 if matches!(s, "half a day ago") {
985 let dt = apply_relative_offset(base, -1, 12.0, TimeUnit::Hour)?;
986 return Some(RelativeMatch {
987 naive: dt,
988 period: Period::Day,
989 locale: "en".to_string(),
990 has_time: false,
991 parts: vec!["year", "month", "day", "time"],
992 part_of_day: None,
993 });
994 }
995
996 if let Some(m) = try_fractional_duration(s, base) {
997 return Some(m);
998 }
999 if let Some(m) = try_conversational_clock(s, settings) {
1000 return Some(m);
1001 }
1002 None
1003}
1004
1005fn parse_small_num_or_word(tok: &str) -> Option<f64> {
1006 if let Ok(v) = tok.parse::<f64>() {
1007 if v.is_finite() && v >= 0.0 {
1008 return Some(v);
1009 }
1010 }
1011 match tok {
1012 "a" | "an" | "one" | "bir" | "ein" | "eine" | "un" | "une" | "uno" | "una" => Some(1.0),
1013 "two" | "iki" | "zwei" | "deux" | "dos" => Some(2.0),
1014 "three" | "üç" | "uc" | "drei" | "trois" | "tres" => Some(3.0),
1015 "four" | "dört" | "dort" | "vier" | "quatre" | "cuatro" => Some(4.0),
1016 "five" | "beş" | "bes" | "fünf" | "funf" | "cinq" | "cinco" => Some(5.0),
1017 "six" | "altı" | "alti" | "sechs" | "seis" => Some(6.0),
1018 "seven" | "yedi" | "sieben" | "sept" | "siete" => Some(7.0),
1019 "eight" | "sekiz" | "acht" | "huit" | "ocho" => Some(8.0),
1020 "nine" | "dokuz" | "neun" | "neuf" | "nueve" => Some(9.0),
1021 "ten" | "on" | "zehn" | "dix" | "diez" => Some(10.0),
1022 "eleven" | "on bir" => Some(11.0),
1023 "twelve" | "on iki" => Some(12.0),
1024 _ => None,
1025 }
1026}
1027
1028fn parse_unit_token(tok: &str) -> Option<TimeUnit> {
1029 match tok {
1030 "second" | "seconds" | "sec" | "secs" | "saniye" | "sekunde" | "sekunden" => Some(TimeUnit::Second),
1031 "minute" | "minutes" | "min" | "mins" | "dakika" | "dk" => Some(TimeUnit::Minute),
1032 "hour" | "hours" | "hr" | "hrs" | "saat" | "stunde" | "stunden" => Some(TimeUnit::Hour),
1033 "day" | "days" | "gün" | "gun" | "tag" | "tage" | "tagen" => Some(TimeUnit::Day),
1034 "week" | "weeks" | "hafta" | "woche" | "wochen" => Some(TimeUnit::Week),
1035 "month" | "months" | "ay" | "monat" | "monate" | "monaten" => Some(TimeUnit::Month),
1036 "year" | "years" | "yıl" | "yil" | "sene" | "jahr" | "jahre" | "jahren" => Some(TimeUnit::Year),
1037 _ => None,
1038 }
1039}
1040
1041fn apply_fractional_offset(base: NaiveDateTime, sign: i8, whole_and_half: f64, unit: TimeUnit) -> Option<NaiveDateTime> {
1042 match unit {
1043 TimeUnit::Month => {
1044 let days = (whole_and_half * 30.0).round();
1045 apply_relative_offset(base, sign, days, TimeUnit::Day)
1046 }
1047 TimeUnit::Year => {
1048 let months = (whole_and_half * 12.0).round();
1049 apply_relative_offset(base, sign, months, TimeUnit::Month)
1050 }
1051 _ => apply_relative_offset(base, sign, whole_and_half, unit),
1052 }
1053}
1054
1055fn try_fractional_duration(s: &str, base: NaiveDateTime) -> Option<RelativeMatch> {
1056 let (sign_en, core_en): (i8, &str) = if let Some(rest) = s.strip_prefix("in ") {
1058 (1, rest.trim())
1059 } else if let Some(rest) = s.strip_suffix(" ago") {
1060 (-1, rest.trim())
1061 } else if let Some(rest) = s.strip_suffix(" from now") {
1062 (1, rest.trim())
1063 } else {
1064 (0, s)
1065 };
1066 if sign_en != 0 {
1067 if let Some((left, right)) = core_en.split_once(" and a half ") {
1068 if let (Some(n), Some(unit)) = (parse_small_num_or_word(left.trim()), parse_unit_token(right.trim())) {
1069 let dt = apply_fractional_offset(base, sign_en, n + 0.5, unit)?;
1070 return Some(RelativeMatch {
1071 naive: dt,
1072 period: period_for_unit(unit),
1073 locale: "en".to_string(),
1074 has_time: false,
1075 parts: parts_for_relative(false, Some(unit)),
1076 part_of_day: None,
1077 });
1078 }
1079 }
1080 }
1081
1082 let (sign_tr, core_tr): (i8, &str) = if let Some(rest) = s.strip_suffix(" once").or_else(|| s.strip_suffix(" önce")) {
1084 (-1, rest.trim())
1085 } else if let Some(rest) = s.strip_suffix(" sonra") {
1086 (1, rest.trim())
1087 } else {
1088 (0, "")
1089 };
1090 if sign_tr != 0 {
1091 if let Some((left, right)) = core_tr.split_once(" bucuk ").or_else(|| core_tr.split_once(" buçuk ")) {
1092 if let (Some(n), Some(unit)) = (parse_small_num_or_word(left.trim()), parse_unit_token(right.trim())) {
1093 let dt = apply_fractional_offset(base, sign_tr, n + 0.5, unit)?;
1094 return Some(RelativeMatch {
1095 naive: dt,
1096 period: period_for_unit(unit),
1097 locale: "tr".to_string(),
1098 has_time: false,
1099 parts: parts_for_relative(false, Some(unit)),
1100 part_of_day: None,
1101 });
1102 }
1103 }
1104 }
1105
1106 let (sign_de, core_de): (i8, &str) = if let Some(rest) = s.strip_prefix("vor ") {
1108 (-1, rest.trim())
1109 } else if let Some(rest) = s.strip_prefix("in ") {
1110 (1, rest.trim())
1111 } else {
1112 (0, "")
1113 };
1114 if sign_de != 0 {
1115 for kw in ["eineinhalb ", "anderthalb "] {
1116 if let Some(unit_str) = core_de.strip_prefix(kw) {
1117 if let Some(unit) = parse_unit_token(unit_str.trim()) {
1118 let dt = apply_fractional_offset(base, sign_de, 1.5, unit)?;
1119 return Some(RelativeMatch {
1120 naive: dt,
1121 period: period_for_unit(unit),
1122 locale: "de".to_string(),
1123 has_time: false,
1124 parts: parts_for_relative(false, Some(unit)),
1125 part_of_day: None,
1126 });
1127 }
1128 }
1129 }
1130 }
1131
1132 None
1133}
1134
1135fn parse_clock_hour_spec(raw: &str) -> Option<u32> {
1136 let mut t = raw.trim().trim_end_matches('.');
1137 let mut is_pm = false;
1138 let mut is_am = false;
1139 for suf in ["p.m.", "p.m", "pm"] {
1140 if let Some(rest) = t.strip_suffix(suf) {
1141 t = rest.trim();
1142 is_pm = true;
1143 break;
1144 }
1145 }
1146 if !is_pm {
1147 for suf in ["a.m.", "a.m", "am"] {
1148 if let Some(rest) = t.strip_suffix(suf) {
1149 t = rest.trim();
1150 is_am = true;
1151 break;
1152 }
1153 }
1154 }
1155 let val = parse_small_num_or_word(t)?;
1156 let mut h = val as u32;
1157 if (h as f64 - val).abs() > 1e-6 || h > 23 {
1158 return None;
1159 }
1160 if is_pm {
1161 if h == 0 || h > 12 {
1162 return None;
1163 }
1164 if h < 12 {
1165 h += 12;
1166 }
1167 } else if is_am {
1168 if h == 0 || h > 12 {
1169 return None;
1170 }
1171 if h == 12 {
1172 h = 0;
1173 }
1174 }
1175 Some(h)
1176}
1177
1178fn try_conversational_clock(s: &str, settings: &Settings) -> Option<RelativeMatch> {
1179 let trimmed = s.strip_prefix("a ").unwrap_or(s);
1181 let en_clock: Option<(u32, u32)> = if let Some(rest) = trimmed.strip_prefix("quarter past ") {
1182 parse_clock_hour_spec(rest).map(|h| (h, 15))
1183 } else if let Some(rest) = trimmed.strip_prefix("quarter to ") {
1184 parse_clock_hour_spec(rest).map(|h| (if h == 0 { 23 } else { h - 1 }, 45))
1185 } else if let Some(rest) = trimmed.strip_prefix("half past ") {
1186 parse_clock_hour_spec(rest).map(|h| (h, 30))
1187 } else {
1188 None
1189 };
1190 if let Some((hh, mm)) = en_clock {
1191 let nt = NaiveTime::from_hms_opt(hh, mm, 0)?;
1192 let nd = resolve_time_only_date(nt, settings);
1193 return Some(RelativeMatch {
1194 naive: nd.and_time(nt),
1195 period: Period::Day,
1196 locale: "en".to_string(),
1197 has_time: true,
1198 parts: vec!["time"],
1199 part_of_day: None,
1200 });
1201 }
1202
1203 let tr_s = s.strip_prefix("saat ").unwrap_or(s).trim();
1205 let tr_clock: Option<(u32, u32)> = if let Some(rest) = tr_s.strip_suffix(" bucuk").or_else(|| tr_s.strip_suffix(" buçuk")) {
1206 parse_clock_hour_spec(rest).map(|h| (h, 30))
1207 } else if let Some(rest) = tr_s.strip_suffix(" ceyrek gece").or_else(|| tr_s.strip_suffix(" çeyrek geçe")) {
1208 let base_h = rest.trim().split(['\'', '’']).next().unwrap_or("").trim();
1209 parse_clock_hour_spec(base_h).map(|h| (h, 15))
1210 } else if let Some(rest) = tr_s.strip_suffix(" ceyrek kala").or_else(|| tr_s.strip_suffix(" çeyrek kala")) {
1211 let base_h = rest.trim().split(['\'', '’']).next().unwrap_or("").trim();
1212 parse_clock_hour_spec(base_h).map(|h| (if h == 0 { 23 } else { h - 1 }, 45))
1213 } else {
1214 None
1215 };
1216 if let Some((hh, mm)) = tr_clock {
1217 let nt = NaiveTime::from_hms_opt(hh, mm, 0)?;
1218 let nd = resolve_time_only_date(nt, settings);
1219 return Some(RelativeMatch {
1220 naive: nd.and_time(nt),
1221 period: Period::Day,
1222 locale: "tr".to_string(),
1223 has_time: true,
1224 parts: vec!["time"],
1225 part_of_day: None,
1226 });
1227 }
1228
1229 None
1230}
1231
1232pub fn extract_trailing_or_leading_time(s: &str) -> (&str, Option<NaiveTime>) {
1234 let tokens: Vec<&str> = s.split_whitespace().collect();
1235 if tokens.len() < 2 {
1236 return (s, None);
1237 }
1238
1239 if tokens.len() >= 3 {
1240 let last2 = format!("{} {}", tokens[tokens.len() - 2], tokens[tokens.len() - 1]);
1241 if let Some(t) = parse_time_str(&last2) {
1242 let cut = s.len() - tokens[tokens.len() - 1].len() - tokens[tokens.len() - 2].len() - 1;
1243 if cut < s.len() {
1244 return (s[..cut].trim_end(), Some(t));
1245 }
1246 }
1247 }
1248
1249 let last = tokens[tokens.len() - 1];
1250 if last.contains(':')
1251 || last.contains('h')
1252 || last.ends_with("am")
1253 || last.ends_with("pm")
1254 || last.ends_with("a.m.")
1255 || last.ends_with("p.m.")
1256 {
1257 if let Some(t) = parse_time_str(last) {
1258 let cut = s.len() - last.len();
1259 return (s[..cut].trim_end(), Some(t));
1260 }
1261 }
1262
1263 (s, None)
1264}
1265
1266fn strip_connector_words<'a>(s: &'a str, loc: &CompiledLocale) -> &'a str {
1267 let mut cur = s.trim();
1268 loop {
1269 let mut trimmed = false;
1270 if let Some(sp) = cur.rfind(' ') {
1271 let tail = &cur[sp + 1..];
1272 if matches!(tail, "at" | "on" | "à" | "a" | "um" | "am" | "saat" | "las" | "в")
1273 || loc.skip.contains(tail)
1274 {
1275 cur = cur[..sp].trim_end();
1276 trimmed = true;
1277 }
1278 }
1279 if !trimmed {
1280 break;
1281 }
1282 }
1283 cur
1284}
1285
1286#[allow(dead_code)]
1287fn _spec_unused(_s: RelativeSpec) {}