1use crate::fast_path::{days_in_month, parse_time_str};
2use crate::locale::{
3 fold_diacritics, CompiledLocale, LocaleRegistry, RelativeAffix, RelativeSpec, TimeUnit,
4};
5use crate::settings::{PartOfDay, Period, PreferDatesFrom, Settings};
6use chrono::{Datelike, Duration, NaiveDate, NaiveDateTime, NaiveTime};
7
8#[derive(Debug, Clone)]
9pub struct RelativeMatch {
10 pub naive: NaiveDateTime,
11 pub period: Period,
12 pub locale: String,
13 pub has_time: bool,
14 pub parts: Vec<&'static str>,
15 pub part_of_day: Option<PartOfDay>,
16}
17
18pub fn apply_relative_offset(
20 base: NaiveDateTime,
21 sign: i8,
22 amount: f64,
23 unit: TimeUnit,
24) -> Option<NaiveDateTime> {
25 if !amount.is_finite() || amount < 0.0 || amount > 10_000_000.0 {
26 return None;
27 }
28 let signed = if sign < 0 { -amount } else { amount };
29 let dt = match unit {
30 TimeUnit::Second => {
31 let ms = (signed * 1000.0).round() as i64;
32 base.checked_add_signed(Duration::milliseconds(ms))?
33 }
34 TimeUnit::Minute => {
35 let ms = (signed * 60_000.0).round() as i64;
36 base.checked_add_signed(Duration::milliseconds(ms))?
37 }
38 TimeUnit::Hour => {
39 let ms = (signed * 3_600_000.0).round() as i64;
40 base.checked_add_signed(Duration::milliseconds(ms))?
41 }
42 TimeUnit::Day => {
43 if amount > 3_650_000.0 {
44 return None;
45 }
46 let ms = (signed * 86_400_000.0).round() as i64;
47 base.checked_add_signed(Duration::milliseconds(ms))?
48 }
49 TimeUnit::Week => {
50 if amount > 520_000.0 {
51 return None;
52 }
53 let ms = (signed * 7.0 * 86_400_000.0).round() as i64;
54 base.checked_add_signed(Duration::milliseconds(ms))?
55 }
56 TimeUnit::Fortnight => {
57 if amount > 260_000.0 {
58 return None;
59 }
60 let ms = (signed * 14.0 * 86_400_000.0).round() as i64;
61 base.checked_add_signed(Duration::milliseconds(ms))?
62 }
63 TimeUnit::Month => {
64 if amount > 120_000.0 {
65 return None;
66 }
67 add_months(base, signed.round() as i32)?
68 }
69 TimeUnit::Year => {
70 if amount > 9_999.0 {
71 return None;
72 }
73 add_months(base, (signed * 12.0).round() as i32)?
74 }
75 TimeUnit::Decade => {
76 if amount > 1_000.0 {
77 return None;
78 }
79 add_months(base, (signed * 120.0).round() as i32)?
80 }
81 TimeUnit::Century => {
82 if amount > 100.0 {
83 return None;
84 }
85 add_months(base, (signed * 1200.0).round() as i32)?
86 }
87 };
88 if !(1..=9999).contains(&dt.year()) {
89 return None;
90 }
91 Some(dt)
92}
93
94fn add_months(base: NaiveDateTime, delta_months: i32) -> Option<NaiveDateTime> {
95 let total_months = (base.year() * 12 + (base.month() as i32 - 1)) + delta_months;
96 let new_year = total_months.div_euclid(12);
97 let new_month = (total_months.rem_euclid(12) + 1) as u32;
98 let max_day = days_in_month(new_year, new_month);
99 let new_day = base.day().min(max_day);
100 let nd = NaiveDate::from_ymd_opt(new_year, new_month, new_day)?;
101 Some(nd.and_time(base.time()))
102}
103
104fn period_for_unit(unit: TimeUnit) -> Period {
105 match unit {
106 TimeUnit::Year | TimeUnit::Decade | TimeUnit::Century => Period::Year,
107 TimeUnit::Month => Period::Month,
108 TimeUnit::Week => Period::Week,
109 _ => Period::Day,
110 }
111}
112
113fn parts_for_relative(has_time: bool, unit: Option<TimeUnit>) -> Vec<&'static str> {
114 let time_unit = matches!(
115 unit,
116 Some(TimeUnit::Hour | TimeUnit::Minute | TimeUnit::Second)
117 );
118 if has_time || time_unit {
119 vec!["year", "month", "day", "time"]
120 } else {
121 vec!["year", "month", "day"]
122 }
123}
124
125fn time_for_hour_anchor(hour: u8, settings: &Settings) -> (NaiveTime, Option<PartOfDay>) {
126 match hour {
127 3 | 6 => (settings.parts_of_day.time_for(PartOfDay::EarlyMorning), Some(PartOfDay::EarlyMorning)),
128 9 => (settings.parts_of_day.time_for(PartOfDay::Morning), Some(PartOfDay::Morning)),
129 15 => (settings.parts_of_day.time_for(PartOfDay::Afternoon), Some(PartOfDay::Afternoon)),
130 18 => (settings.parts_of_day.time_for(PartOfDay::Evening), Some(PartOfDay::Evening)),
131 20 => (settings.parts_of_day.time_for(PartOfDay::Night), Some(PartOfDay::Night)),
132 12 => (NaiveTime::from_hms_opt(12, 0, 0).unwrap(), None),
133 0 => (NaiveTime::from_hms_opt(0, 0, 0).unwrap(), None),
134 h => (NaiveTime::from_hms_opt(h as u32, 0, 0).unwrap(), None),
135 }
136}
137
138fn select_relative_spec(specs: &[RelativeSpec], pref: PreferDatesFrom) -> RelativeSpec {
139 if specs.len() == 1 {
140 return specs[0];
141 }
142 match pref {
143 PreferDatesFrom::Past => specs
144 .iter()
145 .copied()
146 .find(|s| s.sign < 0)
147 .unwrap_or(specs[0]),
148 PreferDatesFrom::Future | PreferDatesFrom::CurrentPeriod => specs
149 .iter()
150 .copied()
151 .find(|s| s.sign > 0)
152 .unwrap_or(specs[0]),
153 }
154}
155
156fn lookup_exact_in_locale(
157 phrase: &str,
158 loc: &CompiledLocale,
159 normalize: bool,
160 pref: PreferDatesFrom,
161) -> Option<RelativeSpec> {
162 if let Some(specs) = loc.relative_exact.get(phrase) {
163 return Some(select_relative_spec(specs, pref));
164 }
165 if normalize {
166 let f = fold_diacritics(phrase);
167 if let Some(specs) = loc.folded_relative_exact.get(&f) {
168 return Some(select_relative_spec(specs, pref));
169 }
170 }
171 None
172}
173
174pub fn try_parse_relative(
176 normalized: &str,
177 candidate_ids: &[usize],
178 registry: &LocaleRegistry,
179 settings: &Settings,
180) -> Option<RelativeMatch> {
181 if settings.strict_parsing {
182 return None;
183 }
184
185 let base = settings.effective_base();
186 let folded_full = if settings.normalize {
187 fold_diacritics(normalized)
188 } else {
189 normalized.to_string()
190 };
191
192 if matches!(
194 if settings.normalize { folded_full.as_str() } else { normalized },
195 "half an hour ago" | "half hour ago" | "yarım saat önce" | "yarim saat once"
196 ) {
197 if let Some(dt) = apply_relative_offset(base, -1, 30.0, TimeUnit::Minute) {
198 return Some(RelativeMatch {
199 naive: dt,
200 period: Period::Day,
201 locale: if normalized.contains("saat") { "tr" } else { "en" }.to_string(),
202 has_time: false,
203 parts: vec!["year", "month", "day", "time"],
204 part_of_day: None,
205 });
206 }
207 }
208 if let Some(m) = try_compound_tod_idiom(normalized, &folded_full, candidate_ids, registry, base, settings) {
209 return Some(m);
210 }
211
212 if let Some(matches) = registry.exact_phrase_index.get(normalized) {
214 let mut matched_specs: Vec<(usize, RelativeSpec)> = Vec::new();
215 for &(lid, spec) in matches {
216 let lid_usize = lid as usize;
217 if candidate_ids.is_empty() || candidate_ids.contains(&lid_usize) {
218 matched_specs.push((lid_usize, spec));
219 }
220 }
221 if !matched_specs.is_empty() {
222 let specs_only: Vec<RelativeSpec> = matched_specs.iter().map(|(_, s)| *s).collect();
223 let chosen = select_relative_spec(&specs_only, settings.prefer_dates_from);
224 let chosen_lid = matched_specs
225 .iter()
226 .find(|(_, s)| *s == chosen)
227 .map(|(l, _)| *l)
228 .unwrap_or(matched_specs[0].0);
229 let dt = apply_relative_offset(base, chosen.sign, chosen.amount as f64, chosen.unit)?;
230 return Some(RelativeMatch {
231 naive: dt,
232 period: period_for_unit(chosen.unit),
233 locale: registry.locales[chosen_lid].code.clone(),
234 has_time: false,
235 parts: parts_for_relative(false, Some(chosen.unit)),
236 part_of_day: None,
237 });
238 }
239 }
240
241 if settings.normalize {
242 if let Some(matches) = registry.folded_exact_phrase_index.get(&folded_full) {
243 let mut matched_specs: Vec<(usize, RelativeSpec)> = Vec::new();
244 for &(lid, spec) in matches {
245 let lid_usize = lid as usize;
246 if candidate_ids.is_empty() || candidate_ids.contains(&lid_usize) {
247 matched_specs.push((lid_usize, spec));
248 }
249 }
250 if !matched_specs.is_empty() {
251 let specs_only: Vec<RelativeSpec> = matched_specs.iter().map(|(_, s)| *s).collect();
252 let chosen = select_relative_spec(&specs_only, settings.prefer_dates_from);
253 let chosen_lid = matched_specs
254 .iter()
255 .find(|(_, s)| *s == chosen)
256 .map(|(l, _)| *l)
257 .unwrap_or(matched_specs[0].0);
258 let dt = apply_relative_offset(base, chosen.sign, chosen.amount as f64, chosen.unit)?;
259 return Some(RelativeMatch {
260 naive: dt,
261 period: period_for_unit(chosen.unit),
262 locale: registry.locales[chosen_lid].code.clone(),
263 has_time: false,
264 parts: parts_for_relative(false, Some(chosen.unit)),
265 part_of_day: None,
266 });
267 }
268 }
269 }
270
271 let (phrase_no_time, extracted_time) = extract_trailing_or_leading_time(normalized);
273
274 for &lid in candidate_ids {
275 let loc = ®istry.locales[lid];
276
277 if let Some(t) = extracted_time {
279 let cleaned = strip_connector_words(phrase_no_time, loc);
280 if let Some(spec) = lookup_exact_in_locale(cleaned, loc, settings.normalize, settings.prefer_dates_from) {
281 let dt = apply_relative_offset(base, spec.sign, spec.amount as f64, spec.unit)?;
282 return Some(RelativeMatch {
283 naive: dt.date().and_time(t),
284 period: Period::Day,
285 locale: loc.code.clone(),
286 has_time: true,
287 parts: vec!["year", "month", "day", "time"],
288 part_of_day: None,
289 });
290 }
291 }
292
293 if extracted_time.is_none() {
295 if let Some((dt, pod)) = try_relative_plus_tod(normalized, loc, base, settings) {
296 return Some(RelativeMatch {
297 naive: dt,
298 period: Period::Day,
299 locale: loc.code.clone(),
300 has_time: true,
301 parts: vec!["year", "month", "day", "time"],
302 part_of_day: pod,
303 });
304 }
305 }
306
307 let target_str = if extracted_time.is_some() {
309 strip_connector_words(phrase_no_time, loc)
310 } else {
311 normalized
312 };
313
314 if let Some((spec_sign, amount, unit)) = try_affix_match(target_str, loc, settings.normalize) {
315 let mut dt = apply_relative_offset(base, spec_sign, amount, unit)?;
316 if let Some(t) = extracted_time {
317 dt = dt.date().and_time(t);
318 }
319 let has_t = extracted_time.is_some();
320 return Some(RelativeMatch {
321 naive: dt,
322 period: if has_t { Period::Day } else { period_for_unit(unit) },
323 locale: loc.code.clone(),
324 has_time: has_t,
325 parts: parts_for_relative(has_t, Some(unit)),
326 part_of_day: None,
327 });
328 }
329
330 if let Some((mut dt, period, has_time_unit)) =
332 try_compound_relative(target_str, loc, base, settings.normalize)
333 {
334 if let Some(t) = extracted_time {
335 dt = dt.date().and_time(t);
336 }
337 let has_t = extracted_time.is_some();
338 return Some(RelativeMatch {
339 naive: dt,
340 period: if has_t { Period::Day } else { period },
341 locale: loc.code.clone(),
342 has_time: has_t,
343 parts: if has_t || has_time_unit {
344 vec!["year", "month", "day", "time"]
345 } else {
346 vec!["year", "month", "day"]
347 },
348 part_of_day: None,
349 });
350 }
351
352 if let Some((mut dt, period, has_time_unit)) =
354 try_bare_duration_relative(target_str, loc, base, settings)
355 {
356 if let Some(t) = extracted_time {
357 dt = dt.date().and_time(t);
358 }
359 let has_t = extracted_time.is_some();
360 return Some(RelativeMatch {
361 naive: dt,
362 period: if has_t { Period::Day } else { period },
363 locale: loc.code.clone(),
364 has_time: has_t,
365 parts: if has_t || has_time_unit {
366 vec!["year", "month", "day", "time"]
367 } else {
368 vec!["year", "month", "day"]
369 },
370 part_of_day: None,
371 });
372 }
373
374 if let Some((mut dt, period)) =
376 try_relative_period_or_weekday(target_str, loc, base, settings.normalize)
377 {
378 if let Some(t) = extracted_time {
379 dt = dt.date().and_time(t);
380 }
381 let has_t = extracted_time.is_some();
382 return Some(RelativeMatch {
383 naive: dt,
384 period: if has_t { Period::Day } else { period },
385 locale: loc.code.clone(),
386 has_time: has_t,
387 parts: parts_for_relative(has_t, None),
388 part_of_day: None,
389 });
390 }
391 }
392
393 None
394}
395
396fn try_compound_tod_idiom(
397 normalized: &str,
398 folded: &str,
399 candidate_ids: &[usize],
400 registry: &LocaleRegistry,
401 base: NaiveDateTime,
402 settings: &Settings,
403) -> Option<RelativeMatch> {
404 let check = if settings.normalize { folded } else { normalized };
405 let (day_offset, hour, lang_code): (i64, u8, &str) = match check {
406 "tonight" | "this night" => (0, 20, "en"),
407 "last night" => (-1, 20, "en"),
408 "this morning" | "today morning" => (0, 9, "en"),
409 "this afternoon" | "today afternoon" => (0, 15, "en"),
410 "this evening" | "today evening" => (0, 18, "en"),
411 "yesterday morning" => (-1, 9, "en"),
412 "yesterday afternoon" => (-1, 15, "en"),
413 "yesterday evening" => (-1, 18, "en"),
414 "tomorrow morning" => (1, 9, "en"),
415 "tomorrow evening" => (1, 18, "en"),
416 "tomorrow night" => (1, 20, "en"),
417 "dün gece" | "dun gece" => (-1, 20, "tr"),
418 "dün akşam" | "dun aksam" => (-1, 18, "tr"),
419 "dün sabah" | "dun sabah" => (-1, 9, "tr"),
420 "bu akşam" | "bu aksam" => (0, 18, "tr"),
421 "bu sabah" => (0, 9, "tr"),
422 "bu gece" => (0, 20, "tr"),
423 "yarın sabah" | "yarin sabah" => (1, 9, "tr"),
424 "yarın akşam" | "yarin aksam" => (1, 18, "tr"),
425 "heute abend" => (0, 18, "de"),
426 "heute morgen" => (0, 9, "de"),
427 "gestern abend" => (-1, 18, "de"),
428 "heute nacht" => (0, 20, "de"),
429 "ce soir" => (0, 18, "fr"),
430 "ce matin" => (0, 9, "fr"),
431 "hier soir" => (-1, 18, "fr"),
432 "anoche" => (-1, 20, "es"),
433 "esta noche" => (0, 20, "es"),
434 "esta tarde" => (0, 15, "es"),
435 _ => return None,
436 };
437
438 if !candidate_ids.is_empty() {
439 let lang_allowed = candidate_ids
440 .iter()
441 .any(|&id| registry.locales[id].code == lang_code);
442 if !lang_allowed {
443 return None;
444 }
445 }
446
447 let target_date = (base + Duration::days(day_offset)).date();
448 let (nt, pod) = time_for_hour_anchor(hour, settings);
449 Some(RelativeMatch {
450 naive: target_date.and_time(nt),
451 period: Period::Day,
452 locale: lang_code.to_string(),
453 has_time: true,
454 parts: vec!["year", "month", "day", "time"],
455 part_of_day: pod,
456 })
457}
458
459fn split_tod_hour<'a>(
460 s: &'a str,
461 loc: &CompiledLocale,
462 normalize: bool,
463) -> Option<(&'a str, u8)> {
464 for (phrase, &hour) in &loc.time_of_day {
465 if let Some(rest) = s.strip_suffix(phrase.as_str()) {
466 if rest.is_empty() || rest.ends_with(' ') {
467 return Some((rest.trim_end(), hour));
468 }
469 }
470 }
471 if normalize {
472 let fs = fold_diacritics(s);
473 for (phrase, &hour) in &loc.folded_time_of_day {
474 if let Some(rest) = fs.strip_suffix(phrase.as_str()) {
475 if rest.is_empty() || rest.ends_with(' ') {
476 return Some((s[..rest.len().min(s.len())].trim_end(), hour));
477 }
478 }
479 }
480 for (phrase, &hour) in &loc.time_of_day {
481 if let Some(rest) = fs.strip_suffix(phrase.as_str()) {
482 if rest.is_empty() || rest.ends_with(' ') {
483 return Some((s[..rest.len().min(s.len())].trim_end(), hour));
484 }
485 }
486 }
487 }
488 None
489}
490
491fn try_relative_plus_tod(
492 normalized: &str,
493 loc: &CompiledLocale,
494 base: NaiveDateTime,
495 settings: &Settings,
496) -> Option<(NaiveDateTime, Option<PartOfDay>)> {
497 let (prefix_raw, hour) = split_tod_hour(normalized, loc, settings.normalize)?;
498 let (nt, pod) = time_for_hour_anchor(hour, settings);
499 if prefix_raw.is_empty() {
500 return Some((base.date().and_time(nt), pod));
501 }
502
503 let cleaned = strip_connector_words(prefix_raw, loc);
504 if let Some(spec) = lookup_exact_in_locale(
505 cleaned,
506 loc,
507 settings.normalize,
508 settings.prefer_dates_from,
509 ) {
510 let dt = apply_relative_offset(base, spec.sign, spec.amount as f64, spec.unit)?;
511 return Some((dt.date().and_time(nt), pod));
512 }
513
514 None
515}
516
517fn try_affix_match(s: &str, loc: &CompiledLocale, normalize: bool) -> Option<(i8, f64, TimeUnit)> {
519 let mut candidates: Vec<String> = Vec::with_capacity(3);
520 candidates.push(s.to_string());
521 if let Some(r) = replace_word_numbers_once(s, loc, normalize) {
522 candidates.push(r);
523 }
524 if normalize {
525 let fs = fold_diacritics(s);
526 if fs != s {
527 if let Some(r) = replace_word_numbers_once(&fs, loc, true) {
528 candidates.push(r);
529 }
530 candidates.push(fs);
531 }
532 }
533
534 let match_against = |cand: &str, affixes: &[RelativeAffix]| -> Option<(i8, f64, TimeUnit)> {
535 for affix in affixes {
536 let after_prefix = if affix.prefix.is_empty() {
537 cand
538 } else if let Some(rest) = cand.strip_prefix(&affix.prefix) {
539 rest
540 } else {
541 continue;
542 };
543
544 let middle = if affix.suffix.is_empty() {
545 after_prefix
546 } else if let Some(rest) = after_prefix.strip_suffix(&affix.suffix) {
547 rest
548 } else {
549 continue;
550 };
551
552 let num_str = middle.trim();
553 if let Some(val) = parse_positive_number(num_str) {
554 return Some((affix.sign, val, affix.unit));
555 }
556 }
557 None
558 };
559
560 for cand in &candidates {
561 if let Some(hit) = match_against(cand, &loc.relative_affix) {
562 return Some(hit);
563 }
564 }
565 if normalize && !loc.folded_relative_affix.is_empty() {
566 for cand in &candidates {
567 if let Some(hit) = match_against(cand, &loc.folded_relative_affix) {
568 return Some(hit);
569 }
570 }
571 }
572 None
573}
574
575fn parse_positive_number(s: &str) -> Option<f64> {
576 if s.is_empty() || s.len() > 12 {
577 return None;
578 }
579 let mut seen_sep = false;
580 let mut has_digit = false;
581 for b in s.bytes() {
582 if b.is_ascii_digit() {
583 has_digit = true;
584 } else if (b == b'.' || b == b',') && !seen_sep {
585 seen_sep = true;
586 } else {
587 return None;
588 }
589 }
590 if !has_digit {
591 return None;
592 }
593 if s.contains(',') {
594 s.replace(',', ".").parse::<f64>().ok()
595 } else {
596 s.parse::<f64>().ok()
597 }
598}
599
600fn replace_word_numbers_once(s: &str, loc: &CompiledLocale, normalize: bool) -> Option<String> {
601 if loc.word_numbers.is_empty() {
602 return None;
603 }
604 let mut changed = false;
605 let mut parts = Vec::new();
606 for tok in s.split_whitespace() {
607 if let Some(&n) = loc.word_numbers.get(tok) {
608 parts.push(n.to_string());
609 changed = true;
610 } else if normalize {
611 let ft = fold_diacritics(tok);
612 if let Some(&n) = loc.word_numbers.get(&ft) {
613 parts.push(n.to_string());
614 changed = true;
615 } else {
616 parts.push(tok.to_string());
617 }
618 } else {
619 parts.push(tok.to_string());
620 }
621 }
622 if changed {
623 Some(parts.join(" "))
624 } else {
625 None
626 }
627}
628
629fn try_compound_relative(
630 s: &str,
631 loc: &CompiledLocale,
632 base: NaiveDateTime,
633 normalize: bool,
634) -> Option<(NaiveDateTime, Period, bool)> {
635 let mut sign: Option<i8> = None;
636 let mut rest = s.trim().to_string();
637
638 let strip_marker = |text: &str, markers: &rustc_hash::FxHashSet<String>| -> Option<String> {
639 for w in markers {
640 if let Some(stripped) = text.strip_suffix(w.as_str()) {
641 if stripped.is_empty() || stripped.ends_with(' ') || !w.is_ascii() {
642 return Some(stripped.trim().to_string());
643 }
644 }
645 if let Some(stripped) = text.strip_prefix(w.as_str()) {
646 if stripped.is_empty() || stripped.starts_with(' ') || !w.is_ascii() {
647 return Some(stripped.trim().to_string());
648 }
649 }
650 }
651 None
652 };
653
654 if let Some(r) = strip_marker(&rest, &loc.ago) {
655 sign = Some(-1);
656 rest = r;
657 } else if normalize {
658 let f_rest = fold_diacritics(&rest);
659 if let Some(r) = strip_marker(&f_rest, &loc.folded_ago) {
660 sign = Some(-1);
661 rest = r;
662 } else if let Some(r) = strip_marker(&f_rest, &loc.ago) {
663 sign = Some(-1);
664 rest = r;
665 }
666 }
667
668 if sign.is_none() {
669 if let Some(r) = strip_marker(&rest, &loc.in_words) {
670 sign = Some(1);
671 rest = r;
672 } else if normalize {
673 let f_rest = fold_diacritics(&rest);
674 if let Some(r) = strip_marker(&f_rest, &loc.folded_in_words) {
675 sign = Some(1);
676 rest = r;
677 } else if let Some(r) = strip_marker(&f_rest, &loc.in_words) {
678 sign = Some(1);
679 rest = r;
680 }
681 }
682 }
683
684 let sign = sign?;
685 if rest.is_empty() {
686 return None;
687 }
688
689 apply_token_duration_pairs(&rest, loc, base, sign, normalize, true)
690}
691
692fn try_bare_duration_relative(
693 s: &str,
694 loc: &CompiledLocale,
695 base: NaiveDateTime,
696 settings: &Settings,
697) -> Option<(NaiveDateTime, Period, bool)> {
698 let sign = if settings.prefer_dates_from == PreferDatesFrom::Future {
699 1
700 } else {
701 -1
702 };
703 apply_token_duration_pairs(s, loc, base, sign, settings.normalize, false)
704}
705
706fn apply_token_duration_pairs(
707 rest: &str,
708 loc: &CompiledLocale,
709 base: NaiveDateTime,
710 sign: i8,
711 normalize: bool,
712 allow_single_char_attached_units: bool,
713) -> Option<(NaiveDateTime, Period, bool)> {
714 let lookup_unit = |tok: &str| -> Option<TimeUnit> {
715 if let Some(&u) = loc.units.get(tok) {
716 return Some(u);
717 }
718 if normalize {
719 let ft = fold_diacritics(tok);
720 if let Some(&u) = loc.units.get(&ft).or_else(|| loc.folded_units.get(&ft)) {
721 return Some(u);
722 }
723 }
724 None
725 };
726
727 let tokens: Vec<&str> = rest
728 .split(|c: char| c.is_whitespace() || c == ',' || c == ';')
729 .filter(|t| !t.is_empty())
730 .collect();
731
732 let mut pairs: Vec<(f64, TimeUnit)> = Vec::new();
733 let mut pending_num: Option<f64> = None;
734
735 for &tok in &tokens {
736 let clean = tok.trim_matches(|c: char| c == ',' || c == '.');
737 if clean.is_empty() {
738 continue;
739 }
740 if matches!(clean, "and" | "ve" | "und" | "et" | "y" | "e" | "of") || loc.skip.contains(clean)
741 {
742 continue;
743 }
744
745 if pending_num.is_none() && allow_single_char_attached_units {
746 if let Some((num, unit_str)) = split_attached_num_unit(clean) {
747 if let Some(u) = lookup_unit(unit_str) {
748 pairs.push((num, u));
749 continue;
750 }
751 }
752 }
753
754 if let Some(n) = parse_positive_number(clean) {
755 if pending_num.is_some() {
756 return None;
757 }
758 pending_num = Some(n);
759 } else if let Some(&wn) = loc.word_numbers.get(clean) {
760 if pending_num.is_some() {
761 return None;
762 }
763 pending_num = Some(wn as f64);
764 } else if let Some(u) = lookup_unit(clean) {
765 if !allow_single_char_attached_units && pending_num.is_none() {
766 return None;
767 }
768 if !allow_single_char_attached_units && clean.chars().count() < 2 {
769 return None;
770 }
771 let amt = pending_num.take().unwrap_or(1.0);
772 pairs.push((amt, u));
773 } else {
774 return None;
775 }
776 }
777
778 if pairs.is_empty() || pending_num.is_some() {
779 return None;
780 }
781
782 let mut dt = base;
783 let mut finest_period = Period::Year;
784 let mut has_time_unit = false;
785 for (amt, unit) in pairs {
786 if !allow_single_char_attached_units && unit == TimeUnit::Year && amt >= 1000.0 {
788 return None;
789 }
790 if matches!(unit, TimeUnit::Hour | TimeUnit::Minute | TimeUnit::Second) {
791 has_time_unit = true;
792 }
793 dt = apply_relative_offset(dt, sign, amt, unit)?;
794 let p = period_for_unit(unit);
795 let rank = |per: Period| match per {
796 Period::Year => 0,
797 Period::Month => 1,
798 Period::Week => 2,
799 Period::Day => 3,
800 Period::Time => 4,
801 };
802 if rank(p) > rank(finest_period) {
803 finest_period = p;
804 }
805 }
806
807 Some((dt, finest_period, has_time_unit))
808}
809
810fn split_attached_num_unit(s: &str) -> Option<(f64, &str)> {
811 let idx = s.find(|c: char| !c.is_ascii_digit() && c != '.' && c != ',')?;
812 if idx == 0 {
813 return None;
814 }
815 let num = parse_positive_number(&s[..idx])?;
816 let unit = &s[idx..];
817 if unit.is_empty() {
818 return None;
819 }
820 Some((num, unit))
821}
822
823fn try_relative_period_or_weekday(
824 s: &str,
825 loc: &CompiledLocale,
826 base: NaiveDateTime,
827 normalize: bool,
828) -> Option<(NaiveDateTime, Period)> {
829 let fs = if normalize {
830 fold_diacritics(s)
831 } else {
832 s.to_string()
833 };
834 let tokens: Vec<&str> = fs.split_whitespace().collect();
835 if tokens.len() != 2 {
836 return None;
837 }
838 let (modifier, target_tok) = (tokens[0], tokens[1]);
839 let dir: i8 = match modifier {
840 "last" | "previous" | "geçen" | "gecen" | "letzten" | "letzter" | "letzte" | "dernier"
841 | "dernière" | "pasado" | "pasada" | "прошлый" | "прошлая" => -1,
842 "next" | "gelecek" | "önümüzdeki" | "onumuzdeki" | "nächsten" | "nächster" | "nächste"
843 | "prochain" | "prochaine" | "próximo" | "proximo" | "следующий" => 1,
844 "this" | "bu" | "diesen" | "diese" | "ce" | "cette" | "este" | "esta" => 0,
845 _ => return None,
846 };
847
848 let unit_opt = loc.units.get(target_tok).copied().or_else(|| {
849 if normalize {
850 loc.folded_units.get(target_tok).copied()
851 } else {
852 None
853 }
854 });
855 if let Some(unit) = unit_opt {
856 let period = period_for_unit(unit);
857 if dir == 0 {
858 return Some((base, period));
859 }
860 return apply_relative_offset(base, dir, 1.0, unit).map(|dt| (dt, period));
861 }
862
863 let target_wd = loc.weekdays.get(target_tok).copied().or_else(|| {
864 if normalize {
865 loc.folded_weekdays.get(target_tok).copied()
866 } else {
867 None
868 }
869 })?;
870
871 let current_wd = base.weekday().num_days_from_monday() as i64;
872 let target = target_wd as i64;
873 let delta_days = if dir < 0 {
874 let mut diff = target - current_wd;
875 if diff >= 0 {
876 diff -= 7;
877 }
878 diff
879 } else if dir > 0 {
880 let mut diff = target - current_wd;
881 if diff <= 0 {
882 diff += 7;
883 }
884 diff
885 } else {
886 target - current_wd
887 };
888
889 base.checked_add_signed(Duration::days(delta_days))
890 .map(|dt| (dt, Period::Day))
891}
892
893pub fn extract_trailing_or_leading_time(s: &str) -> (&str, Option<NaiveTime>) {
895 let tokens: Vec<&str> = s.split_whitespace().collect();
896 if tokens.len() < 2 {
897 return (s, None);
898 }
899
900 if tokens.len() >= 3 {
901 let last2 = format!("{} {}", tokens[tokens.len() - 2], tokens[tokens.len() - 1]);
902 if let Some(t) = parse_time_str(&last2) {
903 let cut = s.len() - tokens[tokens.len() - 1].len() - tokens[tokens.len() - 2].len() - 1;
904 if cut < s.len() {
905 return (s[..cut].trim_end(), Some(t));
906 }
907 }
908 }
909
910 let last = tokens[tokens.len() - 1];
911 if last.contains(':')
912 || last.contains('h')
913 || last.ends_with("am")
914 || last.ends_with("pm")
915 || last.ends_with("a.m.")
916 || last.ends_with("p.m.")
917 {
918 if let Some(t) = parse_time_str(last) {
919 let cut = s.len() - last.len();
920 return (s[..cut].trim_end(), Some(t));
921 }
922 }
923
924 (s, None)
925}
926
927fn strip_connector_words<'a>(s: &'a str, loc: &CompiledLocale) -> &'a str {
928 let mut cur = s.trim();
929 loop {
930 let mut trimmed = false;
931 if let Some(sp) = cur.rfind(' ') {
932 let tail = &cur[sp + 1..];
933 if matches!(tail, "at" | "on" | "à" | "a" | "um" | "am" | "saat" | "las" | "в")
934 || loc.skip.contains(tail)
935 {
936 cur = cur[..sp].trim_end();
937 trimmed = true;
938 }
939 }
940 if !trimmed {
941 break;
942 }
943 }
944 cur
945}
946
947#[allow(dead_code)]
948fn _spec_unused(_s: RelativeSpec) {}