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
104#[inline]
105fn is_time_unit(unit: TimeUnit) -> bool {
106 matches!(unit, TimeUnit::Hour | TimeUnit::Minute | TimeUnit::Second)
107}
108
109fn period_for_unit(unit: TimeUnit) -> Period {
110 match unit {
111 TimeUnit::Year | TimeUnit::Decade | TimeUnit::Century => Period::Year,
112 TimeUnit::Month => Period::Month,
113 TimeUnit::Week => Period::Week,
114 _ => Period::Day,
115 }
116}
117
118fn parts_for_relative(has_time: bool, unit: Option<TimeUnit>) -> Vec<&'static str> {
119 let time_unit = matches!(
120 unit,
121 Some(TimeUnit::Hour | TimeUnit::Minute | TimeUnit::Second)
122 );
123 if has_time || time_unit {
124 vec!["year", "month", "day", "time"]
125 } else {
126 vec!["year", "month", "day"]
127 }
128}
129
130fn time_for_hour_anchor(hour: u8, settings: &Settings) -> (NaiveTime, Option<PartOfDay>) {
131 match hour {
132 3 | 6 => (settings.parts_of_day.time_for(PartOfDay::EarlyMorning), Some(PartOfDay::EarlyMorning)),
133 9 => (settings.parts_of_day.time_for(PartOfDay::Morning), Some(PartOfDay::Morning)),
134 15 => (settings.parts_of_day.time_for(PartOfDay::Afternoon), Some(PartOfDay::Afternoon)),
135 18 => (settings.parts_of_day.time_for(PartOfDay::Evening), Some(PartOfDay::Evening)),
136 20 => (settings.parts_of_day.time_for(PartOfDay::Night), Some(PartOfDay::Night)),
137 12 => (NaiveTime::from_hms_opt(12, 0, 0).unwrap(), None),
138 0 => (NaiveTime::from_hms_opt(0, 0, 0).unwrap(), None),
139 h => (NaiveTime::from_hms_opt(h as u32, 0, 0).unwrap(), None),
140 }
141}
142
143fn select_relative_spec(specs: &[RelativeSpec], pref: PreferDatesFrom) -> RelativeSpec {
144 if specs.len() == 1 {
145 return specs[0];
146 }
147 match pref {
148 PreferDatesFrom::Past => specs
149 .iter()
150 .copied()
151 .find(|s| s.sign < 0)
152 .unwrap_or(specs[0]),
153 PreferDatesFrom::Future | PreferDatesFrom::CurrentPeriod => specs
154 .iter()
155 .copied()
156 .find(|s| s.sign > 0)
157 .unwrap_or(specs[0]),
158 }
159}
160
161fn lookup_exact_in_locale(
162 phrase: &str,
163 loc: &CompiledLocale,
164 normalize: bool,
165 pref: PreferDatesFrom,
166) -> Option<RelativeSpec> {
167 if let Some(specs) = loc.relative_exact.get(phrase) {
168 return Some(select_relative_spec(specs, pref));
169 }
170 if normalize {
171 let f = fold_diacritics(phrase);
172 if let Some(specs) = loc.folded_relative_exact.get(&f) {
173 return Some(select_relative_spec(specs, pref));
174 }
175 }
176 None
177}
178
179fn strip_approx_prefix(s: &str) -> String {
180 let mut cur = s.trim();
181 for _ in 0..2 {
182 cur = cur.trim_start_matches(['~', '≈']).trim_start();
183 let mut matched = false;
184 for p in [
185 "approximately ",
186 "approx. ",
187 "approx ",
188 "about ",
189 "around ",
190 "roughly ",
191 "nearly ",
192 "almost ",
193 "circa ",
194 "ca. ",
195 "environ ",
196 "etwa ",
197 "ungefähr ",
198 "ungefahr ",
199 "ongeveer ",
200 "około ",
201 "okolo ",
202 "около ",
203 "yaklaşık ",
204 "yaklasik ",
205 "sekitar ",
206 "약 ",
207 "約",
208 ] {
209 if let Some(rest) = cur.strip_prefix(p) {
210 let r = rest.trim_start();
211 if !r.is_empty() {
212 cur = r;
213 matched = true;
214 break;
215 }
216 }
217 }
218 if !matched {
219 break;
220 }
221 }
222 let out = cur.to_string();
223 for (pat, rep) in [
224 ("vor etwa ", "vor "),
225 ("vor ungefähr ", "vor "),
226 ("vor ungefahr ", "vor "),
227 ("il y a environ ", "il y a "),
228 ("há cerca de ", "há "),
229 ("ha cerca de ", "ha "),
230 ("hace aproximadamente ", "hace "),
231 ("hace unos ", "hace "),
232 ] {
233 if let Some(idx) = out.find(pat) {
234 let mut s_new = String::with_capacity(out.len());
235 s_new.push_str(&out[..idx]);
236 s_new.push_str(rep);
237 s_new.push_str(&out[idx + pat.len()..]);
238 return s_new;
239 }
240 }
241 out
242}
243
244pub fn try_parse_relative(
246 normalized: &str,
247 candidate_ids: &[usize],
248 registry: &LocaleRegistry,
249 settings: &Settings,
250) -> Option<RelativeMatch> {
251 if settings.strict_parsing {
252 return None;
253 }
254
255 let base = settings.effective_base();
256 let trimmed_article = normalized.strip_prefix("the ").unwrap_or(normalized);
257 let approx_stripped = strip_approx_prefix(trimmed_article);
258 let eff = approx_stripped.trim();
259 let folded_full = if settings.normalize {
260 fold_diacritics(eff)
261 } else {
262 eff.to_string()
263 };
264
265 if let Some(m) = try_conversational_clock_or_fraction(eff, settings) {
267 return Some(m);
268 }
269 if let Some(m) = try_compound_tod_idiom(eff, &folded_full, candidate_ids, registry, base, settings) {
270 return Some(m);
271 }
272
273 if let Some(matches) = registry.exact_phrase_index.get(eff) {
275 let mut matched_specs: Vec<(usize, RelativeSpec)> = Vec::new();
276 if settings.use_given_language_order && !candidate_ids.is_empty() {
277 for &cid in candidate_ids {
278 for &(lid, spec) in matches {
279 if lid as usize == cid {
280 matched_specs.push((cid, spec));
281 }
282 }
283 }
284 } else {
285 for &(lid, spec) in matches {
286 let lid_usize = lid as usize;
287 if candidate_ids.is_empty() || candidate_ids.contains(&lid_usize) {
288 matched_specs.push((lid_usize, spec));
289 }
290 }
291 }
292 if !matched_specs.is_empty() {
293 let specs_only: Vec<RelativeSpec> = if settings.use_given_language_order && !candidate_ids.is_empty() {
294 let first_lid = matched_specs[0].0;
295 matched_specs
296 .iter()
297 .filter(|(l, _)| *l == first_lid)
298 .map(|(_, s)| *s)
299 .collect()
300 } else {
301 matched_specs.iter().map(|(_, s)| *s).collect()
302 };
303 let chosen = select_relative_spec(&specs_only, settings.prefer_dates_from);
304 let chosen_lid = matched_specs
305 .iter()
306 .find(|(_, s)| *s == chosen)
307 .map(|(l, _)| *l)
308 .unwrap_or(matched_specs[0].0);
309 let dt = apply_relative_offset(base, chosen.sign, chosen.amount as f64, chosen.unit)?;
310 let has_t = is_time_unit(chosen.unit);
311 return Some(RelativeMatch {
312 naive: dt,
313 period: period_for_unit(chosen.unit),
314 locale: registry.locales[chosen_lid].code.clone(),
315 has_time: has_t,
316 parts: parts_for_relative(has_t, Some(chosen.unit)),
317 part_of_day: None,
318 });
319 }
320 }
321
322 if settings.normalize {
323 if let Some(matches) = registry.folded_exact_phrase_index.get(&folded_full) {
324 let mut matched_specs: Vec<(usize, RelativeSpec)> = Vec::new();
325 if settings.use_given_language_order && !candidate_ids.is_empty() {
326 for &cid in candidate_ids {
327 for &(lid, spec) in matches {
328 if lid as usize == cid {
329 matched_specs.push((cid, spec));
330 }
331 }
332 }
333 } else {
334 for &(lid, spec) in matches {
335 let lid_usize = lid as usize;
336 if candidate_ids.is_empty() || candidate_ids.contains(&lid_usize) {
337 matched_specs.push((lid_usize, spec));
338 }
339 }
340 }
341 if !matched_specs.is_empty() {
342 let specs_only: Vec<RelativeSpec> = if settings.use_given_language_order && !candidate_ids.is_empty() {
343 let first_lid = matched_specs[0].0;
344 matched_specs
345 .iter()
346 .filter(|(l, _)| *l == first_lid)
347 .map(|(_, s)| *s)
348 .collect()
349 } else {
350 matched_specs.iter().map(|(_, s)| *s).collect()
351 };
352 let chosen = select_relative_spec(&specs_only, settings.prefer_dates_from);
353 let chosen_lid = matched_specs
354 .iter()
355 .find(|(_, s)| *s == chosen)
356 .map(|(l, _)| *l)
357 .unwrap_or(matched_specs[0].0);
358 let dt = apply_relative_offset(base, chosen.sign, chosen.amount as f64, chosen.unit)?;
359 let has_t = is_time_unit(chosen.unit);
360 return Some(RelativeMatch {
361 naive: dt,
362 period: period_for_unit(chosen.unit),
363 locale: registry.locales[chosen_lid].code.clone(),
364 has_time: has_t,
365 parts: parts_for_relative(has_t, Some(chosen.unit)),
366 part_of_day: None,
367 });
368 }
369 }
370 }
371
372 let (phrase_no_time, extracted_time) = extract_trailing_or_leading_time(eff);
374
375 for &lid in candidate_ids {
376 let loc = ®istry.locales[lid];
377
378 if let Some(t) = extracted_time {
380 let cleaned = strip_connector_words(phrase_no_time, loc);
381 if let Some(spec) = lookup_exact_in_locale(cleaned, loc, settings.normalize, settings.prefer_dates_from) {
382 let dt = apply_relative_offset(base, spec.sign, spec.amount as f64, spec.unit)?;
383 return Some(RelativeMatch {
384 naive: dt.date().and_time(t),
385 period: Period::Day,
386 locale: loc.code.clone(),
387 has_time: true,
388 parts: vec!["year", "month", "day", "time"],
389 part_of_day: None,
390 });
391 }
392 }
393
394 if extracted_time.is_none() {
396 if let Some((dt, pod)) = try_relative_plus_tod(eff, loc, base, settings) {
397 return Some(RelativeMatch {
398 naive: dt,
399 period: Period::Day,
400 locale: loc.code.clone(),
401 has_time: true,
402 parts: vec!["year", "month", "day", "time"],
403 part_of_day: pod,
404 });
405 }
406 }
407
408 let target_str = if extracted_time.is_some() {
410 strip_connector_words(phrase_no_time, loc)
411 } else {
412 eff
413 };
414
415 if let Some((spec_sign, amount, unit)) = try_affix_match(
416 target_str,
417 loc,
418 settings.normalize,
419 settings.prefer_dates_from,
420 ) {
421 let mut dt = apply_relative_offset(base, spec_sign, amount, unit)?;
422 if let Some(t) = extracted_time {
423 dt = dt.date().and_time(t);
424 }
425 let explicit_t = extracted_time.is_some();
426 let has_t = explicit_t || is_time_unit(unit);
427 return Some(RelativeMatch {
428 naive: dt,
429 period: if explicit_t { Period::Day } else { period_for_unit(unit) },
430 locale: loc.code.clone(),
431 has_time: has_t,
432 parts: parts_for_relative(has_t, Some(unit)),
433 part_of_day: None,
434 });
435 }
436
437 if let Some((mut dt, period, has_time_unit)) =
439 try_compound_relative(target_str, loc, base, settings.normalize)
440 {
441 if let Some(t) = extracted_time {
442 dt = dt.date().and_time(t);
443 }
444 let explicit_t = extracted_time.is_some();
445 let has_t = explicit_t || has_time_unit;
446 return Some(RelativeMatch {
447 naive: dt,
448 period: if explicit_t { Period::Day } else { period },
449 locale: loc.code.clone(),
450 has_time: has_t,
451 parts: if has_t {
452 vec!["year", "month", "day", "time"]
453 } else {
454 vec!["year", "month", "day"]
455 },
456 part_of_day: None,
457 });
458 }
459
460 if let Some((mut dt, period, has_time_unit)) =
462 try_bare_duration_relative(target_str, loc, base, settings)
463 {
464 if let Some(t) = extracted_time {
465 dt = dt.date().and_time(t);
466 }
467 let explicit_t = extracted_time.is_some();
468 let has_t = explicit_t || has_time_unit;
469 return Some(RelativeMatch {
470 naive: dt,
471 period: if explicit_t { Period::Day } else { period },
472 locale: loc.code.clone(),
473 has_time: has_t,
474 parts: if has_t {
475 vec!["year", "month", "day", "time"]
476 } else {
477 vec!["year", "month", "day"]
478 },
479 part_of_day: None,
480 });
481 }
482
483 if let Some((mut dt, period)) =
485 try_relative_period_or_weekday(target_str, loc, base, settings.normalize)
486 {
487 if let Some(t) = extracted_time {
488 dt = dt.date().and_time(t);
489 }
490 let has_t = extracted_time.is_some();
491 return Some(RelativeMatch {
492 naive: dt,
493 period: if has_t { Period::Day } else { period },
494 locale: loc.code.clone(),
495 has_time: has_t,
496 parts: parts_for_relative(has_t, None),
497 part_of_day: None,
498 });
499 }
500 }
501
502 None
503}
504
505fn try_compound_tod_idiom(
506 normalized: &str,
507 folded: &str,
508 candidate_ids: &[usize],
509 registry: &LocaleRegistry,
510 base: NaiveDateTime,
511 settings: &Settings,
512) -> Option<RelativeMatch> {
513 let check = if settings.normalize { folded } else { normalized };
514 let (day_offset, hour, lang_code): (i64, u8, &str) = match check {
515 "tonight" | "this night" => (0, 20, "en"),
516 "last night" => (-1, 20, "en"),
517 "this morning" | "today morning" => (0, 9, "en"),
518 "this afternoon" | "today afternoon" => (0, 15, "en"),
519 "this evening" | "today evening" => (0, 18, "en"),
520 "day before yesterday" => {
521 let dt = base - Duration::days(2);
522 return Some(RelativeMatch {
523 naive: dt,
524 period: Period::Day,
525 locale: "en".to_string(),
526 has_time: false,
527 parts: vec!["year", "month", "day"],
528 part_of_day: None,
529 });
530 }
531 "day after tomorrow" => {
532 let dt = base + Duration::days(2);
533 return Some(RelativeMatch {
534 naive: dt,
535 period: Period::Day,
536 locale: "en".to_string(),
537 has_time: false,
538 parts: vec!["year", "month", "day"],
539 part_of_day: None,
540 });
541 }
542 "yesterday morning" => (-1, 9, "en"),
543 "yesterday afternoon" => (-1, 15, "en"),
544 "yesterday evening" => (-1, 18, "en"),
545 "tomorrow morning" => (1, 9, "en"),
546 "tomorrow evening" => (1, 18, "en"),
547 "tomorrow night" => (1, 20, "en"),
548 "dün gece" | "dun gece" => (-1, 20, "tr"),
549 "dün akşam" | "dun aksam" => (-1, 18, "tr"),
550 "dün sabah" | "dun sabah" => (-1, 9, "tr"),
551 "bu akşam" | "bu aksam" => (0, 18, "tr"),
552 "bu sabah" => (0, 9, "tr"),
553 "bu gece" => (0, 20, "tr"),
554 "yarın sabah" | "yarin sabah" => (1, 9, "tr"),
555 "yarın akşam" | "yarin aksam" => (1, 18, "tr"),
556 "heute abend" => (0, 18, "de"),
557 "heute morgen" => (0, 9, "de"),
558 "gestern abend" => (-1, 18, "de"),
559 "heute nacht" => (0, 20, "de"),
560 "ce soir" => (0, 18, "fr"),
561 "ce matin" => (0, 9, "fr"),
562 "hier soir" => (-1, 18, "fr"),
563 "anoche" => (-1, 20, "es"),
564 "esta noche" => (0, 20, "es"),
565 "esta tarde" => (0, 15, "es"),
566 _ => return None,
567 };
568
569 if !candidate_ids.is_empty() {
570 let lang_allowed = candidate_ids
571 .iter()
572 .any(|&id| registry.locales[id].code == lang_code);
573 if !lang_allowed {
574 return None;
575 }
576 }
577
578 let target_date = (base + Duration::days(day_offset)).date();
579 let (nt, pod) = time_for_hour_anchor(hour, settings);
580 Some(RelativeMatch {
581 naive: target_date.and_time(nt),
582 period: Period::Day,
583 locale: lang_code.to_string(),
584 has_time: true,
585 parts: vec!["year", "month", "day", "time"],
586 part_of_day: pod,
587 })
588}
589
590fn split_tod_hour<'a>(
591 s: &'a str,
592 loc: &CompiledLocale,
593 normalize: bool,
594) -> Option<(&'a str, u8)> {
595 let mut best: Option<(&'a str, u8, usize)> = None;
596 for (phrase, &hour) in &loc.time_of_day {
597 if let Some(rest) = s.strip_suffix(phrase.as_str()) {
598 if (rest.is_empty() || rest.ends_with(' '))
599 && best.map_or(true, |(_, _, bl)| phrase.len() > bl)
600 {
601 best = Some((rest.trim_end(), hour, phrase.len()));
602 }
603 }
604 }
605 if let Some((prefix, hour, _)) = best {
606 return Some((prefix, hour));
607 }
608 if normalize {
609 let fs = fold_diacritics(s);
610 let total_words = s.split_whitespace().count();
611 let mut best_folded: Option<(usize, u8, usize)> = None;
612 for (phrase, &hour) in loc.folded_time_of_day.iter().chain(loc.time_of_day.iter()) {
613 if let Some(rest) = fs.strip_suffix(phrase.as_str()) {
614 if rest.is_empty() || rest.ends_with(' ') {
615 let p_words = phrase.split_whitespace().count();
616 if p_words <= total_words
617 && fs.split_whitespace().count() == total_words
618 && best_folded.map_or(true, |(_, _, bl)| phrase.len() > bl)
619 {
620 best_folded = Some((total_words - p_words, hour, phrase.len()));
621 }
622 }
623 }
624 }
625 if let Some((keep_words, hour, _)) = best_folded {
626 if keep_words == 0 {
627 return Some(("", hour));
628 }
629 let mut count = 0usize;
630 let mut in_word = false;
631 for (idx, ch) in s.char_indices() {
632 if ch.is_whitespace() {
633 if in_word {
634 count += 1;
635 if count == keep_words {
636 return Some((s[..idx].trim_end(), hour));
637 }
638 in_word = false;
639 }
640 } else {
641 in_word = true;
642 }
643 }
644 }
645 }
646 None
647}
648
649fn try_relative_plus_tod(
650 normalized: &str,
651 loc: &CompiledLocale,
652 base: NaiveDateTime,
653 settings: &Settings,
654) -> Option<(NaiveDateTime, Option<PartOfDay>)> {
655 let (prefix_raw, hour) = split_tod_hour(normalized, loc, settings.normalize)?;
656 let (nt, pod) = time_for_hour_anchor(hour, settings);
657 if prefix_raw.is_empty() {
658 return Some((base.date().and_time(nt), pod));
659 }
660
661 let cleaned = strip_connector_words(prefix_raw, loc);
662 if let Some(spec) = lookup_exact_in_locale(
663 cleaned,
664 loc,
665 settings.normalize,
666 settings.prefer_dates_from,
667 ) {
668 let dt = apply_relative_offset(base, spec.sign, spec.amount as f64, spec.unit)?;
669 return Some((dt.date().and_time(nt), pod));
670 }
671
672 if let Some((dt, _period)) =
673 try_relative_period_or_weekday(cleaned, loc, base, settings.normalize)
674 {
675 return Some((dt.date().and_time(nt), pod));
676 }
677
678 None
679}
680
681fn try_affix_match(
683 s: &str,
684 loc: &CompiledLocale,
685 normalize: bool,
686 pref: PreferDatesFrom,
687) -> Option<(i8, f64, TimeUnit)> {
688 let mut candidates: Vec<String> = Vec::with_capacity(3);
689 candidates.push(s.to_string());
690 if let Some(r) = replace_word_numbers_once(s, loc, normalize) {
691 candidates.push(r);
692 }
693 if normalize {
694 let fs = fold_diacritics(s);
695 if fs != s {
696 if let Some(r) = replace_word_numbers_once(&fs, loc, true) {
697 candidates.push(r);
698 }
699 candidates.push(fs);
700 }
701 }
702
703 let lookup_word_num = |ns: &str| -> Option<f64> {
704 if let Some(&n) = loc.word_numbers.get(ns) {
705 return Some(n as f64);
706 }
707 if normalize {
708 let fns = fold_diacritics(ns);
709 if let Some(&n) = loc.word_numbers.get(&fns) {
710 return Some(n as f64);
711 }
712 }
713 None
714 };
715
716 let want_future = !matches!(pref, PreferDatesFrom::Past);
717
718 let match_against = |cand: &str, affixes: &[RelativeAffix]| -> Option<(i8, f64, TimeUnit)> {
719 let mut fallback: Option<(i8, f64, TimeUnit)> = None;
720 for affix in affixes {
721 let after_prefix = if affix.prefix.is_empty() {
722 cand
723 } else if let Some(rest) = cand.strip_prefix(&affix.prefix) {
724 rest
725 } else {
726 continue;
727 };
728
729 let middle = if affix.suffix.is_empty() {
730 after_prefix
731 } else if let Some(rest) = after_prefix.strip_suffix(&affix.suffix) {
732 rest
733 } else {
734 continue;
735 };
736
737 let num_str = middle.trim();
738 if let Some(val) = parse_positive_number(num_str).or_else(|| lookup_word_num(num_str)) {
739 let is_pref = (affix.sign > 0) == want_future;
740 if is_pref {
741 return Some((affix.sign, val, affix.unit));
742 }
743 if fallback.is_none() {
744 fallback = Some((affix.sign, val, affix.unit));
745 }
746 }
747 }
748 fallback
749 };
750
751 for cand in &candidates {
752 if let Some(hit) = match_against(cand, &loc.relative_affix) {
753 return Some(hit);
754 }
755 }
756 if normalize && !loc.folded_relative_affix.is_empty() {
757 for cand in &candidates {
758 if let Some(hit) = match_against(cand, &loc.folded_relative_affix) {
759 return Some(hit);
760 }
761 }
762 }
763 None
764}
765
766fn parse_positive_number(s: &str) -> Option<f64> {
767 if s.is_empty() || s.len() > 12 {
768 return None;
769 }
770 let mut seen_sep = false;
771 let mut has_digit = false;
772 for b in s.bytes() {
773 if b.is_ascii_digit() {
774 has_digit = true;
775 } else if (b == b'.' || b == b',') && !seen_sep {
776 seen_sep = true;
777 } else {
778 return None;
779 }
780 }
781 if !has_digit {
782 return None;
783 }
784 if s.contains(',') {
785 s.replace(',', ".").parse::<f64>().ok()
786 } else {
787 s.parse::<f64>().ok()
788 }
789}
790
791fn replace_word_numbers_once(s: &str, loc: &CompiledLocale, normalize: bool) -> Option<String> {
792 if loc.word_numbers.is_empty() {
793 return None;
794 }
795 let mut changed = false;
796 let mut parts = Vec::new();
797 for tok in s.split_whitespace() {
798 if let Some(&n) = loc.word_numbers.get(tok) {
799 parts.push(n.to_string());
800 changed = true;
801 } else if normalize {
802 let ft = fold_diacritics(tok);
803 if let Some(&n) = loc.word_numbers.get(&ft) {
804 parts.push(n.to_string());
805 changed = true;
806 } else {
807 parts.push(tok.to_string());
808 }
809 } else {
810 parts.push(tok.to_string());
811 }
812 }
813 if changed {
814 Some(parts.join(" "))
815 } else {
816 None
817 }
818}
819
820fn try_compound_relative(
821 s: &str,
822 loc: &CompiledLocale,
823 base: NaiveDateTime,
824 normalize: bool,
825) -> Option<(NaiveDateTime, Period, bool)> {
826 let mut sign: Option<i8> = None;
827 let mut rest = s.trim().to_string();
828
829 let strip_marker = |text: &str, markers: &rustc_hash::FxHashSet<String>| -> Option<String> {
830 let mut sorted: Vec<&str> = markers.iter().map(|s| s.as_str()).collect();
831 sorted.sort_unstable_by(|a, b| b.len().cmp(&a.len()));
832 for w in sorted {
833 if let Some(stripped) = text.strip_suffix(w) {
834 if stripped.is_empty() || stripped.ends_with(' ') || !w.is_ascii() {
835 return Some(stripped.trim().to_string());
836 }
837 }
838 if let Some(stripped) = text.strip_prefix(w) {
839 if stripped.is_empty() || stripped.starts_with(' ') || !w.is_ascii() {
840 return Some(stripped.trim().to_string());
841 }
842 }
843 }
844 None
845 };
846
847 if let Some(r) = strip_marker(&rest, &loc.ago) {
848 sign = Some(-1);
849 rest = r;
850 } else if normalize {
851 let f_rest = fold_diacritics(&rest);
852 if let Some(r) = strip_marker(&f_rest, &loc.folded_ago) {
853 sign = Some(-1);
854 rest = r;
855 } else if let Some(r) = strip_marker(&f_rest, &loc.ago) {
856 sign = Some(-1);
857 rest = r;
858 }
859 }
860
861 if sign.is_none() {
862 if let Some(r) = strip_marker(&rest, &loc.in_words) {
863 sign = Some(1);
864 rest = r;
865 } else if normalize {
866 let f_rest = fold_diacritics(&rest);
867 if let Some(r) = strip_marker(&f_rest, &loc.folded_in_words) {
868 sign = Some(1);
869 rest = r;
870 } else if let Some(r) = strip_marker(&f_rest, &loc.in_words) {
871 sign = Some(1);
872 rest = r;
873 }
874 }
875 }
876
877 let sign = sign?;
878 if rest.is_empty() {
879 return None;
880 }
881
882 apply_token_duration_pairs(&rest, loc, base, sign, normalize, true)
883}
884
885fn try_bare_duration_relative(
886 s: &str,
887 loc: &CompiledLocale,
888 base: NaiveDateTime,
889 settings: &Settings,
890) -> Option<(NaiveDateTime, Period, bool)> {
891 let sign = if settings.prefer_dates_from == PreferDatesFrom::Future {
892 1
893 } else {
894 -1
895 };
896 apply_token_duration_pairs(s, loc, base, sign, settings.normalize, false)
897}
898
899fn apply_token_duration_pairs(
900 rest: &str,
901 loc: &CompiledLocale,
902 base: NaiveDateTime,
903 sign: i8,
904 normalize: bool,
905 allow_single_char_attached_units: bool,
906) -> Option<(NaiveDateTime, Period, bool)> {
907 let lookup_unit = |tok: &str| -> Option<TimeUnit> {
908 if let Some(&u) = loc.units.get(tok) {
909 return Some(u);
910 }
911 if normalize {
912 let ft = fold_diacritics(tok);
913 if let Some(&u) = loc.units.get(&ft).or_else(|| loc.folded_units.get(&ft)) {
914 return Some(u);
915 }
916 }
917 None
918 };
919
920 let tokens: Vec<&str> = rest
921 .split(|c: char| c.is_whitespace() || c == ',' || c == ';')
922 .filter(|t| !t.is_empty())
923 .collect();
924
925 let mut pairs: Vec<(f64, TimeUnit)> = Vec::new();
926 let mut pending_num: Option<f64> = None;
927
928 for &tok in &tokens {
929 let clean = tok.trim_matches(|c: char| c == ',' || c == '.');
930 if clean.is_empty() {
931 continue;
932 }
933 if matches!(clean, "and" | "ve" | "und" | "et" | "y" | "e" | "of") || loc.skip.contains(clean)
934 {
935 continue;
936 }
937
938 if pending_num.is_none() && allow_single_char_attached_units {
939 if let Some(multi) = split_all_attached_num_units(clean) {
940 if multi.len() >= 2 {
941 let mut all_ok = true;
942 let mut resolved = Vec::with_capacity(multi.len());
943 for (num, unit_str) in multi {
944 if let Some(u) = lookup_unit(unit_str) {
945 resolved.push((num, u));
946 } else {
947 all_ok = false;
948 break;
949 }
950 }
951 if all_ok {
952 pairs.extend(resolved);
953 continue;
954 }
955 }
956 }
957 if let Some((num, unit_str)) = split_attached_num_unit(clean) {
958 if let Some(u) = lookup_unit(unit_str) {
959 pairs.push((num, u));
960 continue;
961 }
962 }
963 }
964
965 if let Some(n) = parse_positive_number(clean) {
966 if pending_num.is_some() {
967 return None;
968 }
969 pending_num = Some(n);
970 } else if let Some(&wn) = loc.word_numbers.get(clean) {
971 if pending_num.is_some() {
972 return None;
973 }
974 pending_num = Some(wn as f64);
975 } else if let Some(u) = lookup_unit(clean) {
976 if !allow_single_char_attached_units && pending_num.is_none() {
977 return None;
978 }
979 if !allow_single_char_attached_units && clean.chars().count() < 2 {
980 return None;
981 }
982 let amt = pending_num.take().unwrap_or(1.0);
983 pairs.push((amt, u));
984 } else {
985 return None;
986 }
987 }
988
989 if pairs.is_empty() || pending_num.is_some() {
990 return None;
991 }
992
993 let mut dt = base;
994 let mut finest_period = Period::Year;
995 let mut has_time_unit = false;
996 for (amt, unit) in pairs {
997 if !allow_single_char_attached_units && unit == TimeUnit::Year && amt >= 1000.0 {
999 return None;
1000 }
1001 if matches!(unit, TimeUnit::Hour | TimeUnit::Minute | TimeUnit::Second) {
1002 has_time_unit = true;
1003 }
1004 dt = apply_relative_offset(dt, sign, amt, unit)?;
1005 let p = period_for_unit(unit);
1006 let rank = |per: Period| match per {
1007 Period::Year => 0,
1008 Period::Month => 1,
1009 Period::Week => 2,
1010 Period::Day => 3,
1011 Period::Time => 4,
1012 };
1013 if rank(p) > rank(finest_period) {
1014 finest_period = p;
1015 }
1016 }
1017
1018 Some((dt, finest_period, has_time_unit))
1019}
1020
1021fn split_attached_num_unit(s: &str) -> Option<(f64, &str)> {
1022 let idx = s.find(|c: char| !c.is_ascii_digit() && c != '.' && c != ',')?;
1023 if idx == 0 {
1024 return None;
1025 }
1026 let num = parse_positive_number(&s[..idx])?;
1027 let unit = &s[idx..];
1028 if unit.is_empty() {
1029 return None;
1030 }
1031 Some((num, unit))
1032}
1033
1034fn split_all_attached_num_units(s: &str) -> Option<Vec<(f64, &str)>> {
1035 let mut out = Vec::new();
1036 let mut pos = 0usize;
1037 while pos < s.len() {
1038 let rest = &s[pos..];
1039 let mut num_end = 0usize;
1040 let mut seen_sep = false;
1041 for (i, ch) in rest.char_indices() {
1042 if ch.is_ascii_digit() {
1043 num_end = i + 1;
1044 } else if (ch == '.' || ch == ',') && !seen_sep && num_end > 0 {
1045 seen_sep = true;
1046 num_end = i + 1;
1047 } else {
1048 break;
1049 }
1050 }
1051 if num_end == 0 {
1052 return None;
1053 }
1054 let num = parse_positive_number(&rest[..num_end])?;
1055 pos += num_end;
1056 let after_num = &s[pos..];
1057 if after_num.is_empty() {
1058 return None;
1059 }
1060 let unit_end = after_num
1061 .find(|c: char| c.is_ascii_digit())
1062 .unwrap_or(after_num.len());
1063 let unit_raw = &after_num[..unit_end];
1064 let unit = unit_raw.trim_end_matches(['と', '和', '및']);
1065 if unit.is_empty() {
1066 return None;
1067 }
1068 out.push((num, unit));
1069 pos += unit_end;
1070 }
1071 if out.is_empty() {
1072 None
1073 } else {
1074 Some(out)
1075 }
1076}
1077
1078fn classify_relative_modifier(tok: &str) -> Option<i8> {
1079 match tok {
1080 "last" | "previous" | "past" | "geçen" | "gecen" | "önceki" | "onceki" | "letzten"
1081 | "letzter" | "letzte" | "vergangenen" | "dernier" | "dernière" | "derniere"
1082 | "pasado" | "pasada" | "passado" | "passada" | "darrer" | "darrera" | "trecut"
1083 | "trecută" | "trecuta" | "múlt" | "mult" | "előző" | "elozo" | "scorso" | "scorsa"
1084 | "vorige" | "afgelopen" | "zeszły" | "zeszła" | "zeszly" | "zeszla" | "poprzedni"
1085 | "прошлый" | "прошлая" | "минулий" | "минула" | "миналата" | "minuly" | "minulý"
1086 | "minulá" | "prejšnji" | "prejsnji" | "prethodni" | "prethodna" | "претходни"
1087 | "претходна" | "förra" | "forra" | "sidste" | "forrige" | "viime" | "praėjęs"
1088 | "praeitas" | "pagājušais" | "eelmine" | "síðasti" | "sidasti" | "diwethaf" | "joan"
1089 | "aurreko" | "pasat" | "περασμένο" | "περασμένη" | "שעבר" | "שעברה" | "lalu"
1090 | "yang lalu" | "trước" | "truoc" | "iliyopita" | "verlede" | "pasinta"
1091 | "antaŭa" | "nakaraang" | "keçən" | "kecen" | "o'tgan" | "өткен" | "otken"
1092 | "지난" => Some(-1),
1093 "next" | "coming" | "following" | "gelecek" | "önümüzdeki" | "onumuzdeki" | "sonraki"
1094 | "nächsten" | "nächster" | "nächste" | "nachsten" | "nachster" | "nachste"
1095 | "kommenden" | "prochain" | "prochaine" | "próximo" | "próxima" | "proximo"
1096 | "proxima" | "siguiente" | "vinent" | "următorul" | "urmatorul" | "următoarea"
1097 | "jövő" | "jovo" | "következő" | "kovetkezo" | "prossimo" | "prossima" | "volgende"
1098 | "komende" | "przyszły" | "przyszła" | "przyszly" | "przyszla" | "następny"
1099 | "nastepny" | "следующий" | "следующая" | "наступний" | "наступна" | "следващ"
1100 | "příští" | "pristi" | "budúci" | "buduci" | "naslednji" | "sljedeći" | "sljedeci"
1101 | "следећи" | "следећа" | "nästa" | "nasta" | "næste" | "naeste" | "neste" | "ensi"
1102 | "kitas" | "nākamais" | "järgmine" | "næsti" | "naesti" | "nesaf" | "hurrengo"
1103 | "vindeiro" | "επόμενο" | "επόμενη" | "הבא" | "הבאה" | "depan" | "berikutnya"
1104 | "tới" | "toi" | "sau" | "ijayo" | "venonta" | "susunod" | "gələn"
1105 | "gelen" | "keyingi" | "келесі" | "kelesi" | "다음" => Some(1),
1106 "this" | "bu" | "diesen" | "dieser" | "diese" | "ce" | "cette" | "cet" | "este"
1107 | "esta" | "aquest" | "aquesta" | "acest" | "această" | "aceasta" | "ez" | "ebben"
1108 | "questo" | "questa" | "deze" | "dit" | "ten" | "ta" | "этот" | "эта" | "цей"
1109 | "ця" | "този" | "tento" | "táto" | "ovaj" | "ova" | "овај" | "ова"
1110 | "denna" | "denne" | "tämä" | "tama" | "šis" | "šī" | "see" | "þessi" | "hwn"
1111 | "hau" | "αυτό" | "αυτή" | "הזה" | "הזאת" | "ini" | "này" | "nay"
1112 | "hii" | "hierdie" | "ĉi" | "itong" | "ushbu" | "осы" | "osy" | "이번" => Some(0),
1113 _ => None,
1114 }
1115}
1116
1117fn try_cjk_relative_weekday(s: &str, base: NaiveDateTime) -> Option<(NaiveDateTime, Period)> {
1118 let (dir, rest): (i8, &str) = if let Some(r) = s.strip_prefix("先週の").or_else(|| s.strip_prefix("先週")) {
1121 (-1, r)
1122 } else if let Some(r) = s.strip_prefix("来週の").or_else(|| s.strip_prefix("来週")) {
1123 (1, r)
1124 } else if let Some(r) = s.strip_prefix("今週の").or_else(|| s.strip_prefix("今週")) {
1125 (0, r)
1126 } else if let Some(r) = s.strip_prefix("上星期").or_else(|| s.strip_prefix("上周")) {
1127 (-1, r)
1128 } else if let Some(r) = s.strip_prefix("下星期").or_else(|| s.strip_prefix("下周")) {
1129 (1, r)
1130 } else if let Some(r) = s
1131 .strip_prefix("本星期")
1132 .or_else(|| s.strip_prefix("本周"))
1133 .or_else(|| s.strip_prefix("这星期"))
1134 .or_else(|| s.strip_prefix("这周"))
1135 {
1136 (0, r)
1137 } else {
1138 return None;
1139 };
1140
1141 let target_wd: i64 = match rest.trim() {
1142 "一" | "月" | "月曜" | "月曜日" => 0,
1143 "二" | "火" | "火曜" | "火曜日" => 1,
1144 "三" | "水" | "水曜" | "水曜日" => 2,
1145 "四" | "木" | "木曜" | "木曜日" => 3,
1146 "五" | "金" | "金曜" | "金曜日" => 4,
1147 "六" | "土" | "土曜" | "土曜日" => 5,
1148 "日" | "天" | "日曜" | "日曜日" => 6,
1149 _ => return None,
1150 };
1151
1152 let current_wd = base.weekday().num_days_from_monday() as i64;
1153 let delta_days = compute_weekday_delta(dir, current_wd, target_wd);
1154 base.checked_add_signed(Duration::days(delta_days))
1155 .map(|dt| (dt.date().and_hms_opt(0, 0, 0).unwrap_or(dt), Period::Day))
1156}
1157
1158#[inline]
1159fn compute_weekday_delta(dir: i8, current_wd: i64, target_wd: i64) -> i64 {
1160 if dir < 0 {
1161 let mut diff = target_wd - current_wd;
1162 if diff >= 0 {
1163 diff -= 7;
1164 }
1165 diff
1166 } else if dir > 0 {
1167 let mut diff = target_wd - current_wd;
1168 if diff <= 0 {
1169 diff += 7;
1170 }
1171 diff
1172 } else {
1173 target_wd - current_wd
1174 }
1175}
1176
1177fn try_relative_period_or_weekday(
1178 s: &str,
1179 loc: &CompiledLocale,
1180 base: NaiveDateTime,
1181 normalize: bool,
1182) -> Option<(NaiveDateTime, Period)> {
1183 if let Some(cjk) = try_cjk_relative_weekday(s.trim(), base) {
1184 return Some(cjk);
1185 }
1186
1187 let fs = if normalize {
1188 fold_diacritics(s)
1189 } else {
1190 s.to_string()
1191 };
1192 let mut tokens: Vec<&str> = fs.split_whitespace().collect();
1193 if tokens.len() == 3 && matches!(tokens[0], "el" | "la" | "le" | "w" | "в" | "am") {
1194 tokens.remove(0);
1195 }
1196 if tokens.len() != 2 {
1197 return None;
1198 }
1199
1200 let (dir, target_tok) = if let Some(d) = classify_relative_modifier(tokens[0]) {
1201 (d, tokens[1])
1202 } else if let Some(d) = classify_relative_modifier(tokens[1]) {
1203 (d, tokens[0])
1204 } else {
1205 return None;
1206 };
1207
1208 let unit_opt = loc.units.get(target_tok).copied().or_else(|| {
1209 if normalize {
1210 loc.folded_units.get(target_tok).copied()
1211 } else {
1212 None
1213 }
1214 });
1215 if let Some(unit) = unit_opt {
1216 let period = period_for_unit(unit);
1217 if dir == 0 {
1218 return Some((base, period));
1219 }
1220 return apply_relative_offset(base, dir, 1.0, unit).map(|dt| (dt, period));
1221 }
1222
1223 let target_wd = loc
1224 .weekdays
1225 .get(target_tok)
1226 .copied()
1227 .or_else(|| {
1228 if normalize {
1229 loc.folded_weekdays.get(target_tok).copied()
1230 } else {
1231 None
1232 }
1233 })
1234 .or_else(|| {
1235 target_tok
1236 .strip_suffix("-feira")
1237 .and_then(|stem| loc.weekdays.get(stem).copied())
1238 })?;
1239
1240 let current_wd = base.weekday().num_days_from_monday() as i64;
1241 let delta_days = compute_weekday_delta(dir, current_wd, target_wd as i64);
1242
1243 base.checked_add_signed(Duration::days(delta_days))
1244 .map(|dt| (dt.date().and_hms_opt(0, 0, 0).unwrap_or(dt), Period::Day))
1245}
1246
1247pub fn try_conversational_clock_or_fraction(
1250 normalized: &str,
1251 settings: &Settings,
1252) -> Option<RelativeMatch> {
1253 let base = settings.effective_base();
1254 let s = if settings.normalize {
1255 fold_diacritics(normalized)
1256 } else {
1257 normalized.to_string()
1258 };
1259 let s = s.trim();
1260
1261 if matches!(
1262 s,
1263 "just now"
1264 | "right now"
1265 | "hemen simdi"
1266 | "hemen şimdi"
1267 | "az once"
1268 | "az önce"
1269 | "gerade eben"
1270 | "a l'instant"
1271 | "à l'instant"
1272 | "ahora mismo"
1273 ) {
1274 let locale = if s.contains("simdi")
1275 || s.contains("şimdi")
1276 || s.contains("once")
1277 || s.contains("önce")
1278 {
1279 "tr"
1280 } else if s == "gerade eben" {
1281 "de"
1282 } else if s.contains("instant") {
1283 "fr"
1284 } else if s == "ahora mismo" {
1285 "es"
1286 } else {
1287 "en"
1288 };
1289 return Some(RelativeMatch {
1290 naive: base,
1291 period: Period::Day,
1292 locale: locale.to_string(),
1293 has_time: true,
1294 parts: vec!["year", "month", "day", "time"],
1295 part_of_day: None,
1296 });
1297 }
1298
1299 if matches!(
1300 s,
1301 "half an hour ago" | "half hour ago" | "yarım saat önce" | "yarim saat once"
1302 ) {
1303 let dt = apply_relative_offset(base, -1, 30.0, TimeUnit::Minute)?;
1304 return Some(RelativeMatch {
1305 naive: dt,
1306 period: Period::Day,
1307 locale: if s.contains("saat") { "tr" } else { "en" }.to_string(),
1308 has_time: true,
1309 parts: vec!["year", "month", "day", "time"],
1310 part_of_day: None,
1311 });
1312 }
1313 if matches!(
1314 s,
1315 "in half an hour" | "in half hour" | "yarım saat sonra" | "yarim saat sonra"
1316 ) {
1317 let dt = apply_relative_offset(base, 1, 30.0, TimeUnit::Minute)?;
1318 return Some(RelativeMatch {
1319 naive: dt,
1320 period: Period::Day,
1321 locale: if s.contains("saat") { "tr" } else { "en" }.to_string(),
1322 has_time: true,
1323 parts: vec!["year", "month", "day", "time"],
1324 part_of_day: None,
1325 });
1326 }
1327 if matches!(s, "half a day ago") {
1328 let dt = apply_relative_offset(base, -1, 12.0, TimeUnit::Hour)?;
1329 return Some(RelativeMatch {
1330 naive: dt,
1331 period: Period::Day,
1332 locale: "en".to_string(),
1333 has_time: true,
1334 parts: vec!["year", "month", "day", "time"],
1335 part_of_day: None,
1336 });
1337 }
1338
1339 let half_spec: Option<(i8, f64, TimeUnit, &'static str)> = match s {
1341 "через полчаса" => Some((1, 30.0, TimeUnit::Minute, "ru")),
1342 "полчаса назад" => Some((-1, 30.0, TimeUnit::Minute, "ru")),
1343 "через полгода" => Some((1, 6.0, TimeUnit::Month, "ru")),
1344 "полгода назад" => Some((-1, 6.0, TimeUnit::Month, "ru")),
1345 "через полдня" => Some((1, 12.0, TimeUnit::Hour, "ru")),
1346 "полдня назад" => Some((-1, 12.0, TimeUnit::Hour, "ru")),
1347 "半小时前" | "半小時前" => Some((-1, 30.0, TimeUnit::Minute, "zh")),
1348 "半時間前" => Some((-1, 30.0, TimeUnit::Minute, "ja")),
1349 "半小时后" | "半小時後" | "半小时後" => Some((1, 30.0, TimeUnit::Minute, "zh")),
1350 "半年前" => Some((-1, 6.0, TimeUnit::Month, "zh")),
1351 "半年后" | "半年後" => Some((1, 6.0, TimeUnit::Month, "zh")),
1352 "半天前" => Some((-1, 12.0, TimeUnit::Hour, "zh")),
1353 "半天后" | "半天後" => Some((1, 12.0, TimeUnit::Hour, "zh")),
1354 _ => None,
1355 };
1356 if let Some((sign, amt, unit, loc_code)) = half_spec {
1357 let dt = apply_relative_offset(base, sign, amt, unit)?;
1358 let has_t = is_time_unit(unit);
1359 return Some(RelativeMatch {
1360 naive: dt,
1361 period: period_for_unit(unit),
1362 locale: loc_code.to_string(),
1363 has_time: has_t,
1364 parts: parts_for_relative(has_t, Some(unit)),
1365 part_of_day: None,
1366 });
1367 }
1368
1369 let ar_pair: Option<(i8, &str)> = if let Some(rest) = s.strip_prefix("منذ ") {
1371 Some((-1, rest.trim()))
1372 } else if let Some(rest) = s.strip_prefix("قبل ") {
1373 Some((-1, rest.trim()))
1374 } else if let Some(rest) = s.strip_prefix("بعد ") {
1375 Some((1, rest.trim()))
1376 } else if let Some(rest) = s.strip_prefix("خلال ") {
1377 Some((1, rest.trim()))
1378 } else {
1379 None
1380 };
1381 if let Some((sign, noun)) = ar_pair {
1382 let ar_unit: Option<(f64, TimeUnit)> = match noun {
1383 "ثانيتين" | "ثانيتان" => Some((2.0, TimeUnit::Second)),
1384 "دقيقتين" | "دقيقتان" => Some((2.0, TimeUnit::Minute)),
1385 "ساعتين" | "ساعتان" => Some((2.0, TimeUnit::Hour)),
1386 "يومين" | "يومان" => Some((2.0, TimeUnit::Day)),
1387 "اسبوعين" | "أسبوعين" | "اسبوعان" | "أسبوعان" => Some((2.0, TimeUnit::Week)),
1388 "شهرين" | "شهران" => Some((2.0, TimeUnit::Month)),
1389 "سنتين" | "عامين" | "سنتان" | "عامان" => Some((2.0, TimeUnit::Year)),
1390 "ثانية" => Some((1.0, TimeUnit::Second)),
1391 "دقيقة" => Some((1.0, TimeUnit::Minute)),
1392 "ساعة" => Some((1.0, TimeUnit::Hour)),
1393 "يوم" => Some((1.0, TimeUnit::Day)),
1394 "اسبوع" | "أسبوع" => Some((1.0, TimeUnit::Week)),
1395 "شهر" => Some((1.0, TimeUnit::Month)),
1396 "سنة" | "عام" => Some((1.0, TimeUnit::Year)),
1397 _ => None,
1398 };
1399 if let Some((amt, unit)) = ar_unit {
1400 let dt = apply_relative_offset(base, sign, amt, unit)?;
1401 let has_t = is_time_unit(unit);
1402 return Some(RelativeMatch {
1403 naive: dt,
1404 period: period_for_unit(unit),
1405 locale: "ar".to_string(),
1406 has_time: has_t,
1407 parts: parts_for_relative(has_t, Some(unit)),
1408 part_of_day: None,
1409 });
1410 }
1411 }
1412
1413 let he_pair: Option<(i8, &str)> = if let Some(rest) = s.strip_prefix("לפני ") {
1415 Some((-1, rest.trim()))
1416 } else if let Some(rest) = s.strip_prefix("בעוד ").or_else(|| s.strip_prefix("עוד ")) {
1417 Some((1, rest.trim()))
1418 } else {
1419 None
1420 };
1421 if let Some((sign, noun)) = he_pair {
1422 let he_unit: Option<(f64, TimeUnit)> = match noun {
1423 "דקתיים" => Some((2.0, TimeUnit::Minute)),
1424 "שעתיים" => Some((2.0, TimeUnit::Hour)),
1425 "יומיים" => Some((2.0, TimeUnit::Day)),
1426 "שבועיים" => Some((2.0, TimeUnit::Week)),
1427 "חודשיים" => Some((2.0, TimeUnit::Month)),
1428 "שנתיים" => Some((2.0, TimeUnit::Year)),
1429 _ => None,
1430 };
1431 if let Some((amt, unit)) = he_unit {
1432 let dt = apply_relative_offset(base, sign, amt, unit)?;
1433 let has_t = is_time_unit(unit);
1434 return Some(RelativeMatch {
1435 naive: dt,
1436 period: period_for_unit(unit),
1437 locale: "he".to_string(),
1438 has_time: has_t,
1439 parts: parts_for_relative(has_t, Some(unit)),
1440 part_of_day: None,
1441 });
1442 }
1443 }
1444
1445 if let Some(m) = try_fractional_duration(s, base) {
1446 return Some(m);
1447 }
1448 if let Some(m) = try_conversational_clock(s, settings) {
1449 return Some(m);
1450 }
1451 None
1452}
1453
1454fn parse_small_num_or_word(tok: &str) -> Option<f64> {
1455 if let Ok(v) = tok.parse::<f64>() {
1456 if v.is_finite() && v >= 0.0 {
1457 return Some(v);
1458 }
1459 }
1460 match tok {
1461 "a" | "an" | "one" | "bir" | "ein" | "eine" | "un" | "une" | "uno" | "una" => Some(1.0),
1462 "two" | "iki" | "zwei" | "deux" | "dos" => Some(2.0),
1463 "three" | "üç" | "uc" | "drei" | "trois" | "tres" => Some(3.0),
1464 "four" | "dört" | "dort" | "vier" | "quatre" | "cuatro" => Some(4.0),
1465 "five" | "beş" | "bes" | "fünf" | "funf" | "cinq" | "cinco" => Some(5.0),
1466 "six" | "altı" | "alti" | "sechs" | "seis" => Some(6.0),
1467 "seven" | "yedi" | "sieben" | "sept" | "siete" => Some(7.0),
1468 "eight" | "sekiz" | "acht" | "huit" | "ocho" => Some(8.0),
1469 "nine" | "dokuz" | "neun" | "neuf" | "nueve" => Some(9.0),
1470 "ten" | "on" | "zehn" | "dix" | "diez" => Some(10.0),
1471 "eleven" | "on bir" => Some(11.0),
1472 "twelve" | "on iki" => Some(12.0),
1473 _ => None,
1474 }
1475}
1476
1477fn parse_unit_token(tok: &str) -> Option<TimeUnit> {
1478 match tok {
1479 "second" | "seconds" | "sec" | "secs" | "saniye" | "sekunde" | "sekunden" => Some(TimeUnit::Second),
1480 "minute" | "minutes" | "min" | "mins" | "dakika" | "dk" => Some(TimeUnit::Minute),
1481 "hour" | "hours" | "hr" | "hrs" | "saat" | "stunde" | "stunden" => Some(TimeUnit::Hour),
1482 "day" | "days" | "gün" | "gun" | "tag" | "tage" | "tagen" => Some(TimeUnit::Day),
1483 "week" | "weeks" | "hafta" | "woche" | "wochen" => Some(TimeUnit::Week),
1484 "month" | "months" | "ay" | "monat" | "monate" | "monaten" => Some(TimeUnit::Month),
1485 "year" | "years" | "yıl" | "yil" | "sene" | "jahr" | "jahre" | "jahren" => Some(TimeUnit::Year),
1486 _ => None,
1487 }
1488}
1489
1490fn apply_fractional_offset(base: NaiveDateTime, sign: i8, whole_and_half: f64, unit: TimeUnit) -> Option<NaiveDateTime> {
1491 match unit {
1492 TimeUnit::Month => {
1493 let days = (whole_and_half * 30.0).round();
1494 apply_relative_offset(base, sign, days, TimeUnit::Day)
1495 }
1496 TimeUnit::Year => {
1497 let months = (whole_and_half * 12.0).round();
1498 apply_relative_offset(base, sign, months, TimeUnit::Month)
1499 }
1500 _ => apply_relative_offset(base, sign, whole_and_half, unit),
1501 }
1502}
1503
1504fn try_fractional_duration(s: &str, base: NaiveDateTime) -> Option<RelativeMatch> {
1505 let (sign_en, core_en): (i8, &str) = if let Some(rest) = s.strip_prefix("in ") {
1507 (1, rest.trim())
1508 } else if let Some(rest) = s.strip_suffix(" ago") {
1509 (-1, rest.trim())
1510 } else if let Some(rest) = s.strip_suffix(" from now") {
1511 (1, rest.trim())
1512 } else {
1513 (0, s)
1514 };
1515 if sign_en != 0 {
1516 if let Some((left, right)) = core_en.split_once(" and a half ") {
1517 if let (Some(n), Some(unit)) = (parse_small_num_or_word(left.trim()), parse_unit_token(right.trim())) {
1518 let dt = apply_fractional_offset(base, sign_en, n + 0.5, unit)?;
1519 let has_t = is_time_unit(unit);
1520 return Some(RelativeMatch {
1521 naive: dt,
1522 period: period_for_unit(unit),
1523 locale: "en".to_string(),
1524 has_time: has_t,
1525 parts: parts_for_relative(has_t, Some(unit)),
1526 part_of_day: None,
1527 });
1528 }
1529 }
1530 }
1531
1532 let (sign_tr, core_tr): (i8, &str) = if let Some(rest) = s.strip_suffix(" once").or_else(|| s.strip_suffix(" önce")) {
1534 (-1, rest.trim())
1535 } else if let Some(rest) = s.strip_suffix(" sonra") {
1536 (1, rest.trim())
1537 } else {
1538 (0, "")
1539 };
1540 if sign_tr != 0 {
1541 if let Some((left, right)) = core_tr.split_once(" bucuk ").or_else(|| core_tr.split_once(" buçuk ")) {
1542 if let (Some(n), Some(unit)) = (parse_small_num_or_word(left.trim()), parse_unit_token(right.trim())) {
1543 let dt = apply_fractional_offset(base, sign_tr, n + 0.5, unit)?;
1544 let has_t = is_time_unit(unit);
1545 return Some(RelativeMatch {
1546 naive: dt,
1547 period: period_for_unit(unit),
1548 locale: "tr".to_string(),
1549 has_time: has_t,
1550 parts: parts_for_relative(has_t, Some(unit)),
1551 part_of_day: None,
1552 });
1553 }
1554 }
1555 }
1556
1557 let (sign_de, core_de): (i8, &str) = if let Some(rest) = s.strip_prefix("vor ") {
1559 (-1, rest.trim())
1560 } else if let Some(rest) = s.strip_prefix("in ") {
1561 (1, rest.trim())
1562 } else {
1563 (0, "")
1564 };
1565 if sign_de != 0 {
1566 for kw in ["eineinhalb ", "anderthalb "] {
1567 if let Some(unit_str) = core_de.strip_prefix(kw) {
1568 if let Some(unit) = parse_unit_token(unit_str.trim()) {
1569 let dt = apply_fractional_offset(base, sign_de, 1.5, unit)?;
1570 let has_t = is_time_unit(unit);
1571 return Some(RelativeMatch {
1572 naive: dt,
1573 period: period_for_unit(unit),
1574 locale: "de".to_string(),
1575 has_time: has_t,
1576 parts: parts_for_relative(has_t, Some(unit)),
1577 part_of_day: None,
1578 });
1579 }
1580 }
1581 }
1582 }
1583
1584 None
1585}
1586
1587fn parse_clock_hour_spec(raw: &str) -> Option<u32> {
1588 let mut t = raw.trim().trim_end_matches('.');
1589 let mut is_pm = false;
1590 let mut is_am = false;
1591 for suf in ["p.m.", "p.m", "pm"] {
1592 if let Some(rest) = t.strip_suffix(suf) {
1593 t = rest.trim();
1594 is_pm = true;
1595 break;
1596 }
1597 }
1598 if !is_pm {
1599 for suf in ["a.m.", "a.m", "am"] {
1600 if let Some(rest) = t.strip_suffix(suf) {
1601 t = rest.trim();
1602 is_am = true;
1603 break;
1604 }
1605 }
1606 }
1607 let val = parse_small_num_or_word(t)?;
1608 let mut h = val as u32;
1609 if (h as f64 - val).abs() > 1e-6 || h > 23 {
1610 return None;
1611 }
1612 if is_pm {
1613 if h == 0 || h > 12 {
1614 return None;
1615 }
1616 if h < 12 {
1617 h += 12;
1618 }
1619 } else if is_am {
1620 if h == 0 || h > 12 {
1621 return None;
1622 }
1623 if h == 12 {
1624 h = 0;
1625 }
1626 }
1627 Some(h)
1628}
1629
1630fn try_conversational_clock(s: &str, settings: &Settings) -> Option<RelativeMatch> {
1631 let noon_midnight: Option<(u32, u32)> = match s {
1633 "12 noon" | "12:00 noon" | "12 pm noon" | "12 p.m. noon" => Some((12, 0)),
1634 "12 midnight" | "12:00 midnight" | "12 am midnight" | "12 a.m. midnight" => Some((0, 0)),
1635 _ => None,
1636 };
1637 if let Some((hh, mm)) = noon_midnight {
1638 let nt = NaiveTime::from_hms_opt(hh, mm, 0)?;
1639 let nd = resolve_time_only_date(nt, settings);
1640 return Some(RelativeMatch {
1641 naive: nd.and_time(nt),
1642 period: Period::Day,
1643 locale: "en".to_string(),
1644 has_time: true,
1645 parts: vec!["time"],
1646 part_of_day: None,
1647 });
1648 }
1649
1650 let trimmed = s.strip_prefix("a ").unwrap_or(s);
1652 let en_clock: Option<(u32, u32)> = if let Some(rest) = trimmed.strip_prefix("quarter past ") {
1653 parse_clock_hour_spec(rest).map(|h| (h, 15))
1654 } else if let Some(rest) = trimmed.strip_prefix("quarter to ") {
1655 parse_clock_hour_spec(rest).map(|h| (if h == 0 { 23 } else { h - 1 }, 45))
1656 } else if let Some(rest) = trimmed.strip_prefix("half past ") {
1657 parse_clock_hour_spec(rest).map(|h| (h, 30))
1658 } else {
1659 None
1660 };
1661 if let Some((hh, mm)) = en_clock {
1662 let nt = NaiveTime::from_hms_opt(hh, mm, 0)?;
1663 let nd = resolve_time_only_date(nt, settings);
1664 return Some(RelativeMatch {
1665 naive: nd.and_time(nt),
1666 period: Period::Day,
1667 locale: "en".to_string(),
1668 has_time: true,
1669 parts: vec!["time"],
1670 part_of_day: None,
1671 });
1672 }
1673
1674 let tr_s = s.strip_prefix("saat ").unwrap_or(s).trim();
1676 let tr_clock: Option<(u32, u32)> = if let Some(rest) = tr_s.strip_suffix(" bucuk").or_else(|| tr_s.strip_suffix(" buçuk")) {
1677 parse_clock_hour_spec(rest).map(|h| (h, 30))
1678 } else if let Some(rest) = tr_s.strip_suffix(" ceyrek gece").or_else(|| tr_s.strip_suffix(" çeyrek geçe")) {
1679 let base_h = rest.trim().split(['\'', '’']).next().unwrap_or("").trim();
1680 parse_clock_hour_spec(base_h).map(|h| (h, 15))
1681 } else if let Some(rest) = tr_s.strip_suffix(" ceyrek kala").or_else(|| tr_s.strip_suffix(" çeyrek kala")) {
1682 let base_h = rest.trim().split(['\'', '’']).next().unwrap_or("").trim();
1683 parse_clock_hour_spec(base_h).map(|h| (if h == 0 { 23 } else { h - 1 }, 45))
1684 } else {
1685 None
1686 };
1687 if let Some((hh, mm)) = tr_clock {
1688 let nt = NaiveTime::from_hms_opt(hh, mm, 0)?;
1689 let nd = resolve_time_only_date(nt, settings);
1690 return Some(RelativeMatch {
1691 naive: nd.and_time(nt),
1692 period: Period::Day,
1693 locale: "tr".to_string(),
1694 has_time: true,
1695 parts: vec!["time"],
1696 part_of_day: None,
1697 });
1698 }
1699
1700 None
1701}
1702
1703pub fn extract_trailing_or_leading_time(s: &str) -> (&str, Option<NaiveTime>) {
1706 let mut ranges: Vec<(usize, usize)> = Vec::new();
1708 let mut in_tok = false;
1709 let mut tok_start = 0usize;
1710 for (idx, ch) in s.char_indices() {
1711 if ch.is_whitespace() {
1712 if in_tok {
1713 ranges.push((tok_start, idx));
1714 in_tok = false;
1715 }
1716 } else if !in_tok {
1717 tok_start = idx;
1718 in_tok = true;
1719 }
1720 }
1721 if in_tok {
1722 ranges.push((tok_start, s.len()));
1723 }
1724
1725 if ranges.len() >= 3 {
1727 let max_k = (ranges.len() - 1).min(4);
1728 for k in (2..=max_k).rev() {
1729 let cut = ranges[ranges.len() - k].0;
1730 let cand = s[cut..].trim();
1731 if let Some(t) = parse_time_str(cand) {
1732 return (s[..cut].trim_end(), Some(t));
1733 }
1734 }
1735 }
1736
1737 if ranges.len() >= 2 {
1739 let (last_s, last_e) = ranges[ranges.len() - 1];
1740 let last = &s[last_s..last_e];
1741 if last.contains(':')
1742 || last.contains('h')
1743 || last.contains('시')
1744 || last.contains('時')
1745 || last.contains('时')
1746 || last.contains('点')
1747 || last.ends_with("am")
1748 || last.ends_with("pm")
1749 || last.ends_with("a.m.")
1750 || last.ends_with("p.m.")
1751 {
1752 if let Some(t) = parse_time_str(last) {
1753 return (s[..last_s].trim_end(), Some(t));
1754 }
1755 }
1756
1757 if ranges.len() >= 3 {
1758 let (prev_s, prev_e) = ranges[ranges.len() - 2];
1759 let prev = &s[prev_s..prev_e];
1760 if matches!(
1761 prev,
1762 "at" | "um" | "à" | "saat" | "alle" | "kl" | "klo" | "las" | "às" | "в" | "o" | "om"
1763 ) && (1..=2).contains(&last.len())
1764 && last.bytes().all(|b| b.is_ascii_digit())
1765 {
1766 if let Ok(h) = last.parse::<u32>() {
1767 if h <= 23 {
1768 if let Some(t) = NaiveTime::from_hms_opt(h, 0, 0) {
1769 return (s[..prev_s].trim_end(), Some(t));
1770 }
1771 }
1772 }
1773 }
1774 }
1775 }
1776
1777 if let Some((left, right)) = s.rsplit_once('の') {
1779 if let Some(t) = parse_time_str(right.trim()) {
1780 let prefix = left.trim_end();
1781 if !prefix.is_empty() {
1782 return (prefix, Some(t));
1783 }
1784 }
1785 }
1786 if s.contains(':') || s.contains('時') || s.contains('点') || s.contains('시') {
1787 for marker in ["午前", "午後", "上午", "下午", "오전", "오후"] {
1788 if let Some(pos) = s.rfind(marker) {
1789 if pos > 0 {
1790 if let Some(t) = parse_time_str(&s[pos..]) {
1791 let prefix = s[..pos].trim_end_matches(|c: char| c.is_whitespace() || c == 'の');
1792 if !prefix.is_empty() {
1793 return (prefix, Some(t));
1794 }
1795 }
1796 }
1797 }
1798 }
1799 let mut prev_non_ascii = false;
1800 for (idx, ch) in s.char_indices() {
1801 if idx > 0 && ch.is_ascii_digit() && prev_non_ascii {
1802 if let Some(t) = parse_time_str(&s[idx..]) {
1803 let prefix = s[..idx].trim_end_matches(|c: char| c.is_whitespace() || c == 'の');
1804 if !prefix.is_empty() {
1805 return (prefix, Some(t));
1806 }
1807 }
1808 }
1809 prev_non_ascii = !ch.is_ascii() && !ch.is_whitespace() && ch != 'の';
1810 }
1811 }
1812
1813 (s, None)
1814}
1815
1816fn strip_connector_words<'a>(s: &'a str, loc: &CompiledLocale) -> &'a str {
1817 let mut cur = s.trim();
1818 loop {
1819 let mut trimmed = false;
1820 if let Some(stripped) = cur.strip_suffix('の') {
1821 if !stripped.is_empty() {
1822 cur = stripped.trim_end();
1823 trimmed = true;
1824 }
1825 } else if let Some(sp) = cur.rfind(' ') {
1826 let tail = &cur[sp + 1..];
1827 if matches!(
1828 tail,
1829 "at" | "on" | "à" | "a" | "um" | "am" | "saat" | "las" | "às" | "в" | "о"
1830 | "o" | "om" | "alle" | "kl" | "klo" | "la" | "pukul" | "lúc" | "στις"
1831 | "בשעה" | "الساعة"
1832 ) || loc.skip.contains(tail)
1833 {
1834 cur = cur[..sp].trim_end();
1835 trimmed = true;
1836 }
1837 }
1838 if !trimmed {
1839 break;
1840 }
1841 }
1842 cur
1843}
1844
1845#[allow(dead_code)]
1846fn _spec_unused(_s: RelativeSpec) {}