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