Skip to main content

dateoxide_core/
relative.rs

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
18/// Calendar-accurate offset addition (matches dateutil.relativedelta semantics for months/years).
19pub 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
174/// Try parsing a normalized lowercase string as a relative date across candidate locales.
175pub fn try_parse_relative(
176    normalized: &str,
177    candidate_ids: &[usize],
178    registry: &LocaleRegistry,
179    settings: &Settings,
180) -> Option<RelativeMatch> {
181    if settings.strict_parsing {
182        return None;
183    }
184
185    let base = settings.effective_base();
186    let trimmed_article = normalized.strip_prefix("the ").unwrap_or(normalized);
187    let folded_full = if settings.normalize {
188        fold_diacritics(trimmed_article)
189    } else {
190        trimmed_article.to_string()
191    };
192
193    // 0. Special compound day + time-of-day idioms, half/fractional durations & conversational clocks
194    if let Some(m) = try_conversational_clock_or_fraction(trimmed_article, settings) {
195        return Some(m);
196    }
197    if let Some(m) = try_compound_tod_idiom(trimmed_article, &folded_full, candidate_ids, registry, base, settings) {
198        return Some(m);
199    }
200
201    // 1. O(1) Global Exact Relative Phrase lookup ("yesterday", "bugün", "yarın", "demain", "今日", "कल", "غدا")
202    if let Some(matches) = registry.exact_phrase_index.get(trimmed_article) {
203        let mut matched_specs: Vec<(usize, RelativeSpec)> = Vec::new();
204        if settings.use_given_language_order && !candidate_ids.is_empty() {
205            for &cid in candidate_ids {
206                for &(lid, spec) in matches {
207                    if lid as usize == cid {
208                        matched_specs.push((cid, spec));
209                    }
210                }
211            }
212        } else {
213            for &(lid, spec) in matches {
214                let lid_usize = lid as usize;
215                if candidate_ids.is_empty() || candidate_ids.contains(&lid_usize) {
216                    matched_specs.push((lid_usize, spec));
217                }
218            }
219        }
220        if !matched_specs.is_empty() {
221            let specs_only: Vec<RelativeSpec> = if settings.use_given_language_order && !candidate_ids.is_empty() {
222                let first_lid = matched_specs[0].0;
223                matched_specs
224                    .iter()
225                    .filter(|(l, _)| *l == first_lid)
226                    .map(|(_, s)| *s)
227                    .collect()
228            } else {
229                matched_specs.iter().map(|(_, s)| *s).collect()
230            };
231            let chosen = select_relative_spec(&specs_only, settings.prefer_dates_from);
232            let chosen_lid = matched_specs
233                .iter()
234                .find(|(_, s)| *s == chosen)
235                .map(|(l, _)| *l)
236                .unwrap_or(matched_specs[0].0);
237            let dt = apply_relative_offset(base, chosen.sign, chosen.amount as f64, chosen.unit)?;
238            return Some(RelativeMatch {
239                naive: dt,
240                period: period_for_unit(chosen.unit),
241                locale: registry.locales[chosen_lid].code.clone(),
242                has_time: false,
243                parts: parts_for_relative(false, Some(chosen.unit)),
244                part_of_day: None,
245            });
246        }
247    }
248
249    if settings.normalize {
250        if let Some(matches) = registry.folded_exact_phrase_index.get(&folded_full) {
251            let mut matched_specs: Vec<(usize, RelativeSpec)> = Vec::new();
252            if settings.use_given_language_order && !candidate_ids.is_empty() {
253                for &cid in candidate_ids {
254                    for &(lid, spec) in matches {
255                        if lid as usize == cid {
256                            matched_specs.push((cid, spec));
257                        }
258                    }
259                }
260            } else {
261                for &(lid, spec) in matches {
262                    let lid_usize = lid as usize;
263                    if candidate_ids.is_empty() || candidate_ids.contains(&lid_usize) {
264                        matched_specs.push((lid_usize, spec));
265                    }
266                }
267            }
268            if !matched_specs.is_empty() {
269                let specs_only: Vec<RelativeSpec> = if settings.use_given_language_order && !candidate_ids.is_empty() {
270                    let first_lid = matched_specs[0].0;
271                    matched_specs
272                        .iter()
273                        .filter(|(l, _)| *l == first_lid)
274                        .map(|(_, s)| *s)
275                        .collect()
276                } else {
277                    matched_specs.iter().map(|(_, s)| *s).collect()
278                };
279                let chosen = select_relative_spec(&specs_only, settings.prefer_dates_from);
280                let chosen_lid = matched_specs
281                    .iter()
282                    .find(|(_, s)| *s == chosen)
283                    .map(|(l, _)| *l)
284                    .unwrap_or(matched_specs[0].0);
285                let dt = apply_relative_offset(base, chosen.sign, chosen.amount as f64, chosen.unit)?;
286                return Some(RelativeMatch {
287                    naive: dt,
288                    period: period_for_unit(chosen.unit),
289                    locale: registry.locales[chosen_lid].code.clone(),
290                    has_time: false,
291                    parts: parts_for_relative(false, Some(chosen.unit)),
292                    part_of_day: None,
293                });
294            }
295        }
296    }
297
298    // 2. Peel off optional explicit time component
299    let (phrase_no_time, extracted_time) = extract_trailing_or_leading_time(normalized);
300
301    for &lid in candidate_ids {
302        let loc = &registry.locales[lid];
303
304        // 2a. Exact relative phrase + explicit time
305        if let Some(t) = extracted_time {
306            let cleaned = strip_connector_words(phrase_no_time, loc);
307            if let Some(spec) = lookup_exact_in_locale(cleaned, loc, settings.normalize, settings.prefer_dates_from) {
308                let dt = apply_relative_offset(base, spec.sign, spec.amount as f64, spec.unit)?;
309                return Some(RelativeMatch {
310                    naive: dt.date().and_time(t),
311                    period: Period::Day,
312                    locale: loc.code.clone(),
313                    has_time: true,
314                    parts: vec!["year", "month", "day", "time"],
315                    part_of_day: None,
316                });
317            }
318        }
319
320        // 2b. <relative_exact> [connector] <time_of_day> ("yesterday at noon", "yesterday morning", "dün akşam")
321        if extracted_time.is_none() {
322            if let Some((dt, pod)) = try_relative_plus_tod(normalized, loc, base, settings) {
323                return Some(RelativeMatch {
324                    naive: dt,
325                    period: Period::Day,
326                    locale: loc.code.clone(),
327                    has_time: true,
328                    parts: vec!["year", "month", "day", "time"],
329                    part_of_day: pod,
330                });
331            }
332        }
333
334        // 2c. Zero-regex structured affix patterns (3,592 CLDR/dateparser patterns across 205 langs!)
335        let target_str = if extracted_time.is_some() {
336            strip_connector_words(phrase_no_time, loc)
337        } else {
338            normalized
339        };
340
341        if let Some((spec_sign, amount, unit)) = try_affix_match(target_str, loc, settings.normalize) {
342            let mut dt = apply_relative_offset(base, spec_sign, amount, unit)?;
343            if let Some(t) = extracted_time {
344                dt = dt.date().and_time(t);
345            }
346            let has_t = extracted_time.is_some();
347            return Some(RelativeMatch {
348                naive: dt,
349                period: if has_t { Period::Day } else { period_for_unit(unit) },
350                locale: loc.code.clone(),
351                has_time: has_t,
352                parts: parts_for_relative(has_t, Some(unit)),
353                part_of_day: None,
354            });
355        }
356
357        // 2d. Compound & word-number relative expressions ("2 ay 3 gün önce", "5 dk önce", "1 year, 2 months, 3 days ago")
358        if let Some((mut dt, period, has_time_unit)) =
359            try_compound_relative(target_str, loc, base, settings.normalize)
360        {
361            if let Some(t) = extracted_time {
362                dt = dt.date().and_time(t);
363            }
364            let has_t = extracted_time.is_some();
365            return Some(RelativeMatch {
366                naive: dt,
367                period: if has_t { Period::Day } else { period },
368                locale: loc.code.clone(),
369                has_time: has_t,
370                parts: if has_t || has_time_unit {
371                    vec!["year", "month", "day", "time"]
372                } else {
373                    vec!["year", "month", "day"]
374                },
375                part_of_day: None,
376            });
377        }
378
379        // 2e. Bare relative duration ("2 days", "3 hours", "1 week", "2 gün") without explicit ago/in
380        if let Some((mut dt, period, has_time_unit)) =
381            try_bare_duration_relative(target_str, loc, base, settings)
382        {
383            if let Some(t) = extracted_time {
384                dt = dt.date().and_time(t);
385            }
386            let has_t = extracted_time.is_some();
387            return Some(RelativeMatch {
388                naive: dt,
389                period: if has_t { Period::Day } else { period },
390                locale: loc.code.clone(),
391                has_time: has_t,
392                parts: if has_t || has_time_unit {
393                    vec!["year", "month", "day", "time"]
394                } else {
395                    vec!["year", "month", "day"]
396                },
397                part_of_day: None,
398            });
399        }
400
401        // 2f. Relative period/weekday expressions: "last Monday", "geçen hafta", "gelecek ay"
402        if let Some((mut dt, period)) =
403            try_relative_period_or_weekday(target_str, loc, base, settings.normalize)
404        {
405            if let Some(t) = extracted_time {
406                dt = dt.date().and_time(t);
407            }
408            let has_t = extracted_time.is_some();
409            return Some(RelativeMatch {
410                naive: dt,
411                period: if has_t { Period::Day } else { period },
412                locale: loc.code.clone(),
413                has_time: has_t,
414                parts: parts_for_relative(has_t, None),
415                part_of_day: None,
416            });
417        }
418    }
419
420    None
421}
422
423fn try_compound_tod_idiom(
424    normalized: &str,
425    folded: &str,
426    candidate_ids: &[usize],
427    registry: &LocaleRegistry,
428    base: NaiveDateTime,
429    settings: &Settings,
430) -> Option<RelativeMatch> {
431    let check = if settings.normalize { folded } else { normalized };
432    let (day_offset, hour, lang_code): (i64, u8, &str) = match check {
433        "tonight" | "this night" => (0, 20, "en"),
434        "last night" => (-1, 20, "en"),
435        "this morning" | "today morning" => (0, 9, "en"),
436        "this afternoon" | "today afternoon" => (0, 15, "en"),
437        "this evening" | "today evening" => (0, 18, "en"),
438        "day before yesterday" => {
439            let dt = base - Duration::days(2);
440            return Some(RelativeMatch {
441                naive: dt,
442                period: Period::Day,
443                locale: "en".to_string(),
444                has_time: false,
445                parts: vec!["year", "month", "day"],
446                part_of_day: None,
447            });
448        }
449        "day after tomorrow" => {
450            let dt = base + Duration::days(2);
451            return Some(RelativeMatch {
452                naive: dt,
453                period: Period::Day,
454                locale: "en".to_string(),
455                has_time: false,
456                parts: vec!["year", "month", "day"],
457                part_of_day: None,
458            });
459        }
460        "yesterday morning" => (-1, 9, "en"),
461        "yesterday afternoon" => (-1, 15, "en"),
462        "yesterday evening" => (-1, 18, "en"),
463        "tomorrow morning" => (1, 9, "en"),
464        "tomorrow evening" => (1, 18, "en"),
465        "tomorrow night" => (1, 20, "en"),
466        "dün gece" | "dun gece" => (-1, 20, "tr"),
467        "dün akşam" | "dun aksam" => (-1, 18, "tr"),
468        "dün sabah" | "dun sabah" => (-1, 9, "tr"),
469        "bu akşam" | "bu aksam" => (0, 18, "tr"),
470        "bu sabah" => (0, 9, "tr"),
471        "bu gece" => (0, 20, "tr"),
472        "yarın sabah" | "yarin sabah" => (1, 9, "tr"),
473        "yarın akşam" | "yarin aksam" => (1, 18, "tr"),
474        "heute abend" => (0, 18, "de"),
475        "heute morgen" => (0, 9, "de"),
476        "gestern abend" => (-1, 18, "de"),
477        "heute nacht" => (0, 20, "de"),
478        "ce soir" => (0, 18, "fr"),
479        "ce matin" => (0, 9, "fr"),
480        "hier soir" => (-1, 18, "fr"),
481        "anoche" => (-1, 20, "es"),
482        "esta noche" => (0, 20, "es"),
483        "esta tarde" => (0, 15, "es"),
484        _ => return None,
485    };
486
487    if !candidate_ids.is_empty() {
488        let lang_allowed = candidate_ids
489            .iter()
490            .any(|&id| registry.locales[id].code == lang_code);
491        if !lang_allowed {
492            return None;
493        }
494    }
495
496    let target_date = (base + Duration::days(day_offset)).date();
497    let (nt, pod) = time_for_hour_anchor(hour, settings);
498    Some(RelativeMatch {
499        naive: target_date.and_time(nt),
500        period: Period::Day,
501        locale: lang_code.to_string(),
502        has_time: true,
503        parts: vec!["year", "month", "day", "time"],
504        part_of_day: pod,
505    })
506}
507
508fn split_tod_hour<'a>(
509    s: &'a str,
510    loc: &CompiledLocale,
511    normalize: bool,
512) -> Option<(&'a str, u8)> {
513    for (phrase, &hour) in &loc.time_of_day {
514        if let Some(rest) = s.strip_suffix(phrase.as_str()) {
515            if rest.is_empty() || rest.ends_with(' ') {
516                return Some((rest.trim_end(), hour));
517            }
518        }
519    }
520    if normalize {
521        let fs = fold_diacritics(s);
522        for (phrase, &hour) in &loc.folded_time_of_day {
523            if let Some(rest) = fs.strip_suffix(phrase.as_str()) {
524                if rest.is_empty() || rest.ends_with(' ') {
525                    return Some((s[..rest.len().min(s.len())].trim_end(), hour));
526                }
527            }
528        }
529        for (phrase, &hour) in &loc.time_of_day {
530            if let Some(rest) = fs.strip_suffix(phrase.as_str()) {
531                if rest.is_empty() || rest.ends_with(' ') {
532                    return Some((s[..rest.len().min(s.len())].trim_end(), hour));
533                }
534            }
535        }
536    }
537    None
538}
539
540fn try_relative_plus_tod(
541    normalized: &str,
542    loc: &CompiledLocale,
543    base: NaiveDateTime,
544    settings: &Settings,
545) -> Option<(NaiveDateTime, Option<PartOfDay>)> {
546    let (prefix_raw, hour) = split_tod_hour(normalized, loc, settings.normalize)?;
547    let (nt, pod) = time_for_hour_anchor(hour, settings);
548    if prefix_raw.is_empty() {
549        return Some((base.date().and_time(nt), pod));
550    }
551
552    let cleaned = strip_connector_words(prefix_raw, loc);
553    if let Some(spec) = lookup_exact_in_locale(
554        cleaned,
555        loc,
556        settings.normalize,
557        settings.prefer_dates_from,
558    ) {
559        let dt = apply_relative_offset(base, spec.sign, spec.amount as f64, spec.unit)?;
560        return Some((dt.date().and_time(nt), pod));
561    }
562
563    None
564}
565
566/// Zero-regex prefix + number + suffix matcher covering 99.97% of dateparser's relative-type-regex!
567fn try_affix_match(s: &str, loc: &CompiledLocale, normalize: bool) -> Option<(i8, f64, TimeUnit)> {
568    let mut candidates: Vec<String> = Vec::with_capacity(3);
569    candidates.push(s.to_string());
570    if let Some(r) = replace_word_numbers_once(s, loc, normalize) {
571        candidates.push(r);
572    }
573    if normalize {
574        let fs = fold_diacritics(s);
575        if fs != s {
576            if let Some(r) = replace_word_numbers_once(&fs, loc, true) {
577                candidates.push(r);
578            }
579            candidates.push(fs);
580        }
581    }
582
583    let match_against = |cand: &str, affixes: &[RelativeAffix]| -> Option<(i8, f64, TimeUnit)> {
584        for affix in affixes {
585            let after_prefix = if affix.prefix.is_empty() {
586                cand
587            } else if let Some(rest) = cand.strip_prefix(&affix.prefix) {
588                rest
589            } else {
590                continue;
591            };
592
593            let middle = if affix.suffix.is_empty() {
594                after_prefix
595            } else if let Some(rest) = after_prefix.strip_suffix(&affix.suffix) {
596                rest
597            } else {
598                continue;
599            };
600
601            let num_str = middle.trim();
602            if let Some(val) = parse_positive_number(num_str) {
603                return Some((affix.sign, val, affix.unit));
604            }
605        }
606        None
607    };
608
609    for cand in &candidates {
610        if let Some(hit) = match_against(cand, &loc.relative_affix) {
611            return Some(hit);
612        }
613    }
614    if normalize && !loc.folded_relative_affix.is_empty() {
615        for cand in &candidates {
616            if let Some(hit) = match_against(cand, &loc.folded_relative_affix) {
617                return Some(hit);
618            }
619        }
620    }
621    None
622}
623
624fn parse_positive_number(s: &str) -> Option<f64> {
625    if s.is_empty() || s.len() > 12 {
626        return None;
627    }
628    let mut seen_sep = false;
629    let mut has_digit = false;
630    for b in s.bytes() {
631        if b.is_ascii_digit() {
632            has_digit = true;
633        } else if (b == b'.' || b == b',') && !seen_sep {
634            seen_sep = true;
635        } else {
636            return None;
637        }
638    }
639    if !has_digit {
640        return None;
641    }
642    if s.contains(',') {
643        s.replace(',', ".").parse::<f64>().ok()
644    } else {
645        s.parse::<f64>().ok()
646    }
647}
648
649fn replace_word_numbers_once(s: &str, loc: &CompiledLocale, normalize: bool) -> Option<String> {
650    if loc.word_numbers.is_empty() {
651        return None;
652    }
653    let mut changed = false;
654    let mut parts = Vec::new();
655    for tok in s.split_whitespace() {
656        if let Some(&n) = loc.word_numbers.get(tok) {
657            parts.push(n.to_string());
658            changed = true;
659        } else if normalize {
660            let ft = fold_diacritics(tok);
661            if let Some(&n) = loc.word_numbers.get(&ft) {
662                parts.push(n.to_string());
663                changed = true;
664            } else {
665                parts.push(tok.to_string());
666            }
667        } else {
668            parts.push(tok.to_string());
669        }
670    }
671    if changed {
672        Some(parts.join(" "))
673    } else {
674        None
675    }
676}
677
678fn try_compound_relative(
679    s: &str,
680    loc: &CompiledLocale,
681    base: NaiveDateTime,
682    normalize: bool,
683) -> Option<(NaiveDateTime, Period, bool)> {
684    let mut sign: Option<i8> = None;
685    let mut rest = s.trim().to_string();
686
687    let strip_marker = |text: &str, markers: &rustc_hash::FxHashSet<String>| -> Option<String> {
688        let mut sorted: Vec<&str> = markers.iter().map(|s| s.as_str()).collect();
689        sorted.sort_unstable_by(|a, b| b.len().cmp(&a.len()));
690        for w in sorted {
691            if let Some(stripped) = text.strip_suffix(w) {
692                if stripped.is_empty() || stripped.ends_with(' ') || !w.is_ascii() {
693                    return Some(stripped.trim().to_string());
694                }
695            }
696            if let Some(stripped) = text.strip_prefix(w) {
697                if stripped.is_empty() || stripped.starts_with(' ') || !w.is_ascii() {
698                    return Some(stripped.trim().to_string());
699                }
700            }
701        }
702        None
703    };
704
705    if let Some(r) = strip_marker(&rest, &loc.ago) {
706        sign = Some(-1);
707        rest = r;
708    } else if normalize {
709        let f_rest = fold_diacritics(&rest);
710        if let Some(r) = strip_marker(&f_rest, &loc.folded_ago) {
711            sign = Some(-1);
712            rest = r;
713        } else if let Some(r) = strip_marker(&f_rest, &loc.ago) {
714            sign = Some(-1);
715            rest = r;
716        }
717    }
718
719    if sign.is_none() {
720        if let Some(r) = strip_marker(&rest, &loc.in_words) {
721            sign = Some(1);
722            rest = r;
723        } else if normalize {
724            let f_rest = fold_diacritics(&rest);
725            if let Some(r) = strip_marker(&f_rest, &loc.folded_in_words) {
726                sign = Some(1);
727                rest = r;
728            } else if let Some(r) = strip_marker(&f_rest, &loc.in_words) {
729                sign = Some(1);
730                rest = r;
731            }
732        }
733    }
734
735    let sign = sign?;
736    if rest.is_empty() {
737        return None;
738    }
739
740    apply_token_duration_pairs(&rest, loc, base, sign, normalize, true)
741}
742
743fn try_bare_duration_relative(
744    s: &str,
745    loc: &CompiledLocale,
746    base: NaiveDateTime,
747    settings: &Settings,
748) -> Option<(NaiveDateTime, Period, bool)> {
749    let sign = if settings.prefer_dates_from == PreferDatesFrom::Future {
750        1
751    } else {
752        -1
753    };
754    apply_token_duration_pairs(s, loc, base, sign, settings.normalize, false)
755}
756
757fn apply_token_duration_pairs(
758    rest: &str,
759    loc: &CompiledLocale,
760    base: NaiveDateTime,
761    sign: i8,
762    normalize: bool,
763    allow_single_char_attached_units: bool,
764) -> Option<(NaiveDateTime, Period, bool)> {
765    let lookup_unit = |tok: &str| -> Option<TimeUnit> {
766        if let Some(&u) = loc.units.get(tok) {
767            return Some(u);
768        }
769        if normalize {
770            let ft = fold_diacritics(tok);
771            if let Some(&u) = loc.units.get(&ft).or_else(|| loc.folded_units.get(&ft)) {
772                return Some(u);
773            }
774        }
775        None
776    };
777
778    let tokens: Vec<&str> = rest
779        .split(|c: char| c.is_whitespace() || c == ',' || c == ';')
780        .filter(|t| !t.is_empty())
781        .collect();
782
783    let mut pairs: Vec<(f64, TimeUnit)> = Vec::new();
784    let mut pending_num: Option<f64> = None;
785
786    for &tok in &tokens {
787        let clean = tok.trim_matches(|c: char| c == ',' || c == '.');
788        if clean.is_empty() {
789            continue;
790        }
791        if matches!(clean, "and" | "ve" | "und" | "et" | "y" | "e" | "of") || loc.skip.contains(clean)
792        {
793            continue;
794        }
795
796        if pending_num.is_none() && allow_single_char_attached_units {
797            if let Some((num, unit_str)) = split_attached_num_unit(clean) {
798                if let Some(u) = lookup_unit(unit_str) {
799                    pairs.push((num, u));
800                    continue;
801                }
802            }
803        }
804
805        if let Some(n) = parse_positive_number(clean) {
806            if pending_num.is_some() {
807                return None;
808            }
809            pending_num = Some(n);
810        } else if let Some(&wn) = loc.word_numbers.get(clean) {
811            if pending_num.is_some() {
812                return None;
813            }
814            pending_num = Some(wn as f64);
815        } else if let Some(u) = lookup_unit(clean) {
816            if !allow_single_char_attached_units && pending_num.is_none() {
817                return None;
818            }
819            if !allow_single_char_attached_units && clean.chars().count() < 2 {
820                return None;
821            }
822            let amt = pending_num.take().unwrap_or(1.0);
823            pairs.push((amt, u));
824        } else {
825            return None;
826        }
827    }
828
829    if pairs.is_empty() || pending_num.is_some() {
830        return None;
831    }
832
833    let mut dt = base;
834    let mut finest_period = Period::Year;
835    let mut has_time_unit = false;
836    for (amt, unit) in pairs {
837        // Avoid misinterpreting calendar years like "2000 год" / "1000 год" as "2000 years ago"
838        if !allow_single_char_attached_units && unit == TimeUnit::Year && amt >= 1000.0 {
839            return None;
840        }
841        if matches!(unit, TimeUnit::Hour | TimeUnit::Minute | TimeUnit::Second) {
842            has_time_unit = true;
843        }
844        dt = apply_relative_offset(dt, sign, amt, unit)?;
845        let p = period_for_unit(unit);
846        let rank = |per: Period| match per {
847            Period::Year => 0,
848            Period::Month => 1,
849            Period::Week => 2,
850            Period::Day => 3,
851            Period::Time => 4,
852        };
853        if rank(p) > rank(finest_period) {
854            finest_period = p;
855        }
856    }
857
858    Some((dt, finest_period, has_time_unit))
859}
860
861fn split_attached_num_unit(s: &str) -> Option<(f64, &str)> {
862    let idx = s.find(|c: char| !c.is_ascii_digit() && c != '.' && c != ',')?;
863    if idx == 0 {
864        return None;
865    }
866    let num = parse_positive_number(&s[..idx])?;
867    let unit = &s[idx..];
868    if unit.is_empty() {
869        return None;
870    }
871    Some((num, unit))
872}
873
874fn classify_relative_modifier(tok: &str) -> Option<i8> {
875    match tok {
876        "last" | "previous" | "past" | "geçen" | "gecen" | "önceki" | "onceki" | "letzten"
877        | "letzter" | "letzte" | "vergangenen" | "dernier" | "dernière" | "derniere"
878        | "pasado" | "pasada" | "passado" | "passada" | "scorso" | "scorsa" | "vorige"
879        | "afgelopen" | "zeszły" | "zeszła" | "zeszly" | "zeszla" | "poprzedni"
880        | "прошлый" | "прошлая" | "миналата" | "minuly" | "minulý" | "förra" | "forra"
881        | "sidste" | "forrige" | "viime" | "지난" => Some(-1),
882        "next" | "coming" | "following" | "gelecek" | "önümüzdeki" | "onumuzdeki" | "sonraki"
883        | "nächsten" | "nächster" | "nächste" | "nachsten" | "nachster" | "nachste"
884        | "kommenden" | "prochain" | "prochaine" | "próximo" | "próxima" | "proximo"
885        | "proxima" | "siguiente" | "prossimo" | "prossima" | "volgende" | "komende"
886        | "przyszły" | "przyszła" | "przyszly" | "przyszla" | "następny" | "nastepny"
887        | "следующий" | "следующая" | "nästa" | "nasta" | "næste" | "naeste" | "neste"
888        | "ensi" | "다음" => Some(1),
889        "this" | "bu" | "diesen" | "dieser" | "diese" | "ce" | "cette" | "cet" | "este"
890        | "esta" | "questo" | "questa" | "deze" | "dit" | "ten" | "ta" | "этот" | "эта"
891        | "denna" | "denne" | "tämä" | "tama" | "이번" => Some(0),
892        _ => None,
893    }
894}
895
896fn try_cjk_relative_weekday(s: &str, base: NaiveDateTime) -> Option<(NaiveDateTime, Period)> {
897    // Chinese: 上/下/本周[一..日|天] or 上/下星期[一..日|天]
898    // Japanese: 先週/来週/今週[の][月..日][曜[日]]
899    let (dir, rest): (i8, &str) = if let Some(r) = s.strip_prefix("先週の").or_else(|| s.strip_prefix("先週")) {
900        (-1, r)
901    } else if let Some(r) = s.strip_prefix("来週の").or_else(|| s.strip_prefix("来週")) {
902        (1, r)
903    } else if let Some(r) = s.strip_prefix("今週の").or_else(|| s.strip_prefix("今週")) {
904        (0, r)
905    } else if let Some(r) = s.strip_prefix("上星期").or_else(|| s.strip_prefix("上周")) {
906        (-1, r)
907    } else if let Some(r) = s.strip_prefix("下星期").or_else(|| s.strip_prefix("下周")) {
908        (1, r)
909    } else if let Some(r) = s
910        .strip_prefix("本星期")
911        .or_else(|| s.strip_prefix("本周"))
912        .or_else(|| s.strip_prefix("这星期"))
913        .or_else(|| s.strip_prefix("这周"))
914    {
915        (0, r)
916    } else {
917        return None;
918    };
919
920    let target_wd: i64 = match rest.trim() {
921        "一" | "月" | "月曜" | "月曜日" => 0,
922        "二" | "火" | "火曜" | "火曜日" => 1,
923        "三" | "水" | "水曜" | "水曜日" => 2,
924        "四" | "木" | "木曜" | "木曜日" => 3,
925        "五" | "金" | "金曜" | "金曜日" => 4,
926        "六" | "土" | "土曜" | "土曜日" => 5,
927        "日" | "天" | "日曜" | "日曜日" => 6,
928        _ => return None,
929    };
930
931    let current_wd = base.weekday().num_days_from_monday() as i64;
932    let delta_days = compute_weekday_delta(dir, current_wd, target_wd);
933    base.checked_add_signed(Duration::days(delta_days))
934        .map(|dt| (dt.date().and_hms_opt(0, 0, 0).unwrap_or(dt), Period::Day))
935}
936
937#[inline]
938fn compute_weekday_delta(dir: i8, current_wd: i64, target_wd: i64) -> i64 {
939    if dir < 0 {
940        let mut diff = target_wd - current_wd;
941        if diff >= 0 {
942            diff -= 7;
943        }
944        diff
945    } else if dir > 0 {
946        let mut diff = target_wd - current_wd;
947        if diff <= 0 {
948            diff += 7;
949        }
950        diff
951    } else {
952        target_wd - current_wd
953    }
954}
955
956fn try_relative_period_or_weekday(
957    s: &str,
958    loc: &CompiledLocale,
959    base: NaiveDateTime,
960    normalize: bool,
961) -> Option<(NaiveDateTime, Period)> {
962    if let Some(cjk) = try_cjk_relative_weekday(s.trim(), base) {
963        return Some(cjk);
964    }
965
966    let fs = if normalize {
967        fold_diacritics(s)
968    } else {
969        s.to_string()
970    };
971    let mut tokens: Vec<&str> = fs.split_whitespace().collect();
972    if tokens.len() == 3 && matches!(tokens[0], "el" | "la" | "le" | "w" | "в" | "am") {
973        tokens.remove(0);
974    }
975    if tokens.len() != 2 {
976        return None;
977    }
978
979    let (dir, target_tok) = if let Some(d) = classify_relative_modifier(tokens[0]) {
980        (d, tokens[1])
981    } else if let Some(d) = classify_relative_modifier(tokens[1]) {
982        (d, tokens[0])
983    } else {
984        return None;
985    };
986
987    let unit_opt = loc.units.get(target_tok).copied().or_else(|| {
988        if normalize {
989            loc.folded_units.get(target_tok).copied()
990        } else {
991            None
992        }
993    });
994    if let Some(unit) = unit_opt {
995        let period = period_for_unit(unit);
996        if dir == 0 {
997            return Some((base, period));
998        }
999        return apply_relative_offset(base, dir, 1.0, unit).map(|dt| (dt, period));
1000    }
1001
1002    let target_wd = loc
1003        .weekdays
1004        .get(target_tok)
1005        .copied()
1006        .or_else(|| {
1007            if normalize {
1008                loc.folded_weekdays.get(target_tok).copied()
1009            } else {
1010                None
1011            }
1012        })
1013        .or_else(|| {
1014            target_tok
1015                .strip_suffix("-feira")
1016                .and_then(|stem| loc.weekdays.get(stem).copied())
1017        })?;
1018
1019    let current_wd = base.weekday().num_days_from_monday() as i64;
1020    let delta_days = compute_weekday_delta(dir, current_wd, target_wd as i64);
1021
1022    base.checked_add_signed(Duration::days(delta_days))
1023        .map(|dt| (dt.date().and_hms_opt(0, 0, 0).unwrap_or(dt), Period::Day))
1024}
1025
1026/// Parse standalone fractional relative durations and conversational clock idioms
1027/// (e.g. "two and a half hours ago", "bir buçuk saat önce", "quarter past 3", "saat 3 buçuk").
1028pub fn try_conversational_clock_or_fraction(
1029    normalized: &str,
1030    settings: &Settings,
1031) -> Option<RelativeMatch> {
1032    let base = settings.effective_base();
1033    let s = if settings.normalize {
1034        fold_diacritics(normalized)
1035    } else {
1036        normalized.to_string()
1037    };
1038    let s = s.trim();
1039
1040    if matches!(
1041        s,
1042        "half an hour ago" | "half hour ago" | "yarım saat önce" | "yarim saat once"
1043    ) {
1044        let dt = apply_relative_offset(base, -1, 30.0, TimeUnit::Minute)?;
1045        return Some(RelativeMatch {
1046            naive: dt,
1047            period: Period::Day,
1048            locale: if s.contains("saat") { "tr" } else { "en" }.to_string(),
1049            has_time: false,
1050            parts: vec!["year", "month", "day", "time"],
1051            part_of_day: None,
1052        });
1053    }
1054    if matches!(
1055        s,
1056        "in half an hour" | "in half hour" | "yarım saat sonra" | "yarim saat sonra"
1057    ) {
1058        let dt = apply_relative_offset(base, 1, 30.0, TimeUnit::Minute)?;
1059        return Some(RelativeMatch {
1060            naive: dt,
1061            period: Period::Day,
1062            locale: if s.contains("saat") { "tr" } else { "en" }.to_string(),
1063            has_time: false,
1064            parts: vec!["year", "month", "day", "time"],
1065            part_of_day: None,
1066        });
1067    }
1068    if matches!(s, "half a day ago") {
1069        let dt = apply_relative_offset(base, -1, 12.0, TimeUnit::Hour)?;
1070        return Some(RelativeMatch {
1071            naive: dt,
1072            period: Period::Day,
1073            locale: "en".to_string(),
1074            has_time: false,
1075            parts: vec!["year", "month", "day", "time"],
1076            part_of_day: None,
1077        });
1078    }
1079
1080    if let Some(m) = try_fractional_duration(s, base) {
1081        return Some(m);
1082    }
1083    if let Some(m) = try_conversational_clock(s, settings) {
1084        return Some(m);
1085    }
1086    None
1087}
1088
1089fn parse_small_num_or_word(tok: &str) -> Option<f64> {
1090    if let Ok(v) = tok.parse::<f64>() {
1091        if v.is_finite() && v >= 0.0 {
1092            return Some(v);
1093        }
1094    }
1095    match tok {
1096        "a" | "an" | "one" | "bir" | "ein" | "eine" | "un" | "une" | "uno" | "una" => Some(1.0),
1097        "two" | "iki" | "zwei" | "deux" | "dos" => Some(2.0),
1098        "three" | "üç" | "uc" | "drei" | "trois" | "tres" => Some(3.0),
1099        "four" | "dört" | "dort" | "vier" | "quatre" | "cuatro" => Some(4.0),
1100        "five" | "beş" | "bes" | "fünf" | "funf" | "cinq" | "cinco" => Some(5.0),
1101        "six" | "altı" | "alti" | "sechs" | "seis" => Some(6.0),
1102        "seven" | "yedi" | "sieben" | "sept" | "siete" => Some(7.0),
1103        "eight" | "sekiz" | "acht" | "huit" | "ocho" => Some(8.0),
1104        "nine" | "dokuz" | "neun" | "neuf" | "nueve" => Some(9.0),
1105        "ten" | "on" | "zehn" | "dix" | "diez" => Some(10.0),
1106        "eleven" | "on bir" => Some(11.0),
1107        "twelve" | "on iki" => Some(12.0),
1108        _ => None,
1109    }
1110}
1111
1112fn parse_unit_token(tok: &str) -> Option<TimeUnit> {
1113    match tok {
1114        "second" | "seconds" | "sec" | "secs" | "saniye" | "sekunde" | "sekunden" => Some(TimeUnit::Second),
1115        "minute" | "minutes" | "min" | "mins" | "dakika" | "dk" => Some(TimeUnit::Minute),
1116        "hour" | "hours" | "hr" | "hrs" | "saat" | "stunde" | "stunden" => Some(TimeUnit::Hour),
1117        "day" | "days" | "gün" | "gun" | "tag" | "tage" | "tagen" => Some(TimeUnit::Day),
1118        "week" | "weeks" | "hafta" | "woche" | "wochen" => Some(TimeUnit::Week),
1119        "month" | "months" | "ay" | "monat" | "monate" | "monaten" => Some(TimeUnit::Month),
1120        "year" | "years" | "yıl" | "yil" | "sene" | "jahr" | "jahre" | "jahren" => Some(TimeUnit::Year),
1121        _ => None,
1122    }
1123}
1124
1125fn apply_fractional_offset(base: NaiveDateTime, sign: i8, whole_and_half: f64, unit: TimeUnit) -> Option<NaiveDateTime> {
1126    match unit {
1127        TimeUnit::Month => {
1128            let days = (whole_and_half * 30.0).round();
1129            apply_relative_offset(base, sign, days, TimeUnit::Day)
1130        }
1131        TimeUnit::Year => {
1132            let months = (whole_and_half * 12.0).round();
1133            apply_relative_offset(base, sign, months, TimeUnit::Month)
1134        }
1135        _ => apply_relative_offset(base, sign, whole_and_half, unit),
1136    }
1137}
1138
1139fn try_fractional_duration(s: &str, base: NaiveDateTime) -> Option<RelativeMatch> {
1140    // English: "[in ]<n> and a half <unit>[ ago| from now]"
1141    let (sign_en, core_en): (i8, &str) = if let Some(rest) = s.strip_prefix("in ") {
1142        (1, rest.trim())
1143    } else if let Some(rest) = s.strip_suffix(" ago") {
1144        (-1, rest.trim())
1145    } else if let Some(rest) = s.strip_suffix(" from now") {
1146        (1, rest.trim())
1147    } else {
1148        (0, s)
1149    };
1150    if sign_en != 0 {
1151        if let Some((left, right)) = core_en.split_once(" and a half ") {
1152            if let (Some(n), Some(unit)) = (parse_small_num_or_word(left.trim()), parse_unit_token(right.trim())) {
1153                let dt = apply_fractional_offset(base, sign_en, n + 0.5, unit)?;
1154                return Some(RelativeMatch {
1155                    naive: dt,
1156                    period: period_for_unit(unit),
1157                    locale: "en".to_string(),
1158                    has_time: false,
1159                    parts: parts_for_relative(false, Some(unit)),
1160                    part_of_day: None,
1161                });
1162            }
1163        }
1164    }
1165
1166    // Turkish: "<n> buçuk <unit> önce/sonra" (folded: "bucuk", "once")
1167    let (sign_tr, core_tr): (i8, &str) = if let Some(rest) = s.strip_suffix(" once").or_else(|| s.strip_suffix(" önce")) {
1168        (-1, rest.trim())
1169    } else if let Some(rest) = s.strip_suffix(" sonra") {
1170        (1, rest.trim())
1171    } else {
1172        (0, "")
1173    };
1174    if sign_tr != 0 {
1175        if let Some((left, right)) = core_tr.split_once(" bucuk ").or_else(|| core_tr.split_once(" buçuk ")) {
1176            if let (Some(n), Some(unit)) = (parse_small_num_or_word(left.trim()), parse_unit_token(right.trim())) {
1177                let dt = apply_fractional_offset(base, sign_tr, n + 0.5, unit)?;
1178                return Some(RelativeMatch {
1179                    naive: dt,
1180                    period: period_for_unit(unit),
1181                    locale: "tr".to_string(),
1182                    has_time: false,
1183                    parts: parts_for_relative(false, Some(unit)),
1184                    part_of_day: None,
1185                });
1186            }
1187        }
1188    }
1189
1190    // German: "vor eineinhalb <unit>" / "in anderthalb <unit>"
1191    let (sign_de, core_de): (i8, &str) = if let Some(rest) = s.strip_prefix("vor ") {
1192        (-1, rest.trim())
1193    } else if let Some(rest) = s.strip_prefix("in ") {
1194        (1, rest.trim())
1195    } else {
1196        (0, "")
1197    };
1198    if sign_de != 0 {
1199        for kw in ["eineinhalb ", "anderthalb "] {
1200            if let Some(unit_str) = core_de.strip_prefix(kw) {
1201                if let Some(unit) = parse_unit_token(unit_str.trim()) {
1202                    let dt = apply_fractional_offset(base, sign_de, 1.5, unit)?;
1203                    return Some(RelativeMatch {
1204                        naive: dt,
1205                        period: period_for_unit(unit),
1206                        locale: "de".to_string(),
1207                        has_time: false,
1208                        parts: parts_for_relative(false, Some(unit)),
1209                        part_of_day: None,
1210                    });
1211                }
1212            }
1213        }
1214    }
1215
1216    None
1217}
1218
1219fn parse_clock_hour_spec(raw: &str) -> Option<u32> {
1220    let mut t = raw.trim().trim_end_matches('.');
1221    let mut is_pm = false;
1222    let mut is_am = false;
1223    for suf in ["p.m.", "p.m", "pm"] {
1224        if let Some(rest) = t.strip_suffix(suf) {
1225            t = rest.trim();
1226            is_pm = true;
1227            break;
1228        }
1229    }
1230    if !is_pm {
1231        for suf in ["a.m.", "a.m", "am"] {
1232            if let Some(rest) = t.strip_suffix(suf) {
1233                t = rest.trim();
1234                is_am = true;
1235                break;
1236            }
1237        }
1238    }
1239    let val = parse_small_num_or_word(t)?;
1240    let mut h = val as u32;
1241    if (h as f64 - val).abs() > 1e-6 || h > 23 {
1242        return None;
1243    }
1244    if is_pm {
1245        if h == 0 || h > 12 {
1246            return None;
1247        }
1248        if h < 12 {
1249            h += 12;
1250        }
1251    } else if is_am {
1252        if h == 0 || h > 12 {
1253            return None;
1254        }
1255        if h == 12 {
1256            h = 0;
1257        }
1258    }
1259    Some(h)
1260}
1261
1262fn try_conversational_clock(s: &str, settings: &Settings) -> Option<RelativeMatch> {
1263    // English: "[a ]quarter past <H>", "[a ]quarter to <H>", "half past <H>"
1264    let trimmed = s.strip_prefix("a ").unwrap_or(s);
1265    let en_clock: Option<(u32, u32)> = if let Some(rest) = trimmed.strip_prefix("quarter past ") {
1266        parse_clock_hour_spec(rest).map(|h| (h, 15))
1267    } else if let Some(rest) = trimmed.strip_prefix("quarter to ") {
1268        parse_clock_hour_spec(rest).map(|h| (if h == 0 { 23 } else { h - 1 }, 45))
1269    } else if let Some(rest) = trimmed.strip_prefix("half past ") {
1270        parse_clock_hour_spec(rest).map(|h| (h, 30))
1271    } else {
1272        None
1273    };
1274    if let Some((hh, mm)) = en_clock {
1275        let nt = NaiveTime::from_hms_opt(hh, mm, 0)?;
1276        let nd = resolve_time_only_date(nt, settings);
1277        return Some(RelativeMatch {
1278            naive: nd.and_time(nt),
1279            period: Period::Day,
1280            locale: "en".to_string(),
1281            has_time: true,
1282            parts: vec!["time"],
1283            part_of_day: None,
1284        });
1285    }
1286
1287    // Turkish: "[saat ]<H> bucuk" / "[saat ]<H> ceyrek gece" / "[saat ]<H> ceyrek kala"
1288    let tr_s = s.strip_prefix("saat ").unwrap_or(s).trim();
1289    let tr_clock: Option<(u32, u32)> = if let Some(rest) = tr_s.strip_suffix(" bucuk").or_else(|| tr_s.strip_suffix(" buçuk")) {
1290        parse_clock_hour_spec(rest).map(|h| (h, 30))
1291    } else if let Some(rest) = tr_s.strip_suffix(" ceyrek gece").or_else(|| tr_s.strip_suffix(" çeyrek geçe")) {
1292        let base_h = rest.trim().split(['\'', '’']).next().unwrap_or("").trim();
1293        parse_clock_hour_spec(base_h).map(|h| (h, 15))
1294    } else if let Some(rest) = tr_s.strip_suffix(" ceyrek kala").or_else(|| tr_s.strip_suffix(" çeyrek kala")) {
1295        let base_h = rest.trim().split(['\'', '’']).next().unwrap_or("").trim();
1296        parse_clock_hour_spec(base_h).map(|h| (if h == 0 { 23 } else { h - 1 }, 45))
1297    } else {
1298        None
1299    };
1300    if let Some((hh, mm)) = tr_clock {
1301        let nt = NaiveTime::from_hms_opt(hh, mm, 0)?;
1302        let nd = resolve_time_only_date(nt, settings);
1303        return Some(RelativeMatch {
1304            naive: nd.and_time(nt),
1305            period: Period::Day,
1306            locale: "tr".to_string(),
1307            has_time: true,
1308            parts: vec!["time"],
1309            part_of_day: None,
1310        });
1311    }
1312
1313    None
1314}
1315
1316/// Extract a trailing time from strings like "yesterday at 5pm", "hier à 14h30", "dün saat 15:30".
1317pub fn extract_trailing_or_leading_time(s: &str) -> (&str, Option<NaiveTime>) {
1318    let tokens: Vec<&str> = s.split_whitespace().collect();
1319    if tokens.len() < 2 {
1320        return (s, None);
1321    }
1322
1323    if tokens.len() >= 3 {
1324        let last2 = format!("{} {}", tokens[tokens.len() - 2], tokens[tokens.len() - 1]);
1325        if let Some(t) = parse_time_str(&last2) {
1326            let cut = s.len() - tokens[tokens.len() - 1].len() - tokens[tokens.len() - 2].len() - 1;
1327            if cut < s.len() {
1328                return (s[..cut].trim_end(), Some(t));
1329            }
1330        }
1331    }
1332
1333    let last = tokens[tokens.len() - 1];
1334    if last.contains(':')
1335        || last.contains('h')
1336        || last.ends_with("am")
1337        || last.ends_with("pm")
1338        || last.ends_with("a.m.")
1339        || last.ends_with("p.m.")
1340    {
1341        if let Some(t) = parse_time_str(last) {
1342            let cut = s.len() - last.len();
1343            return (s[..cut].trim_end(), Some(t));
1344        }
1345    }
1346
1347    (s, None)
1348}
1349
1350fn strip_connector_words<'a>(s: &'a str, loc: &CompiledLocale) -> &'a str {
1351    let mut cur = s.trim();
1352    loop {
1353        let mut trimmed = false;
1354        if let Some(sp) = cur.rfind(' ') {
1355            let tail = &cur[sp + 1..];
1356            if matches!(tail, "at" | "on" | "à" | "a" | "um" | "am" | "saat" | "las" | "в")
1357                || loc.skip.contains(tail)
1358            {
1359                cur = cur[..sp].trim_end();
1360                trimmed = true;
1361            }
1362        }
1363        if !trimmed {
1364            break;
1365        }
1366    }
1367    cur
1368}
1369
1370#[allow(dead_code)]
1371fn _spec_unused(_s: RelativeSpec) {}