Skip to main content

dateoxide_core/
absolute.rs

1use crate::fast_path::{days_in_month, expand_two_digit_year, parse_time_str, resolve_missing_day};
2use crate::locale::{fold_diacritics, CompiledLocale, LocaleRegistry};
3use crate::settings::{
4    DateOrder, DatePart, PartOfDay, Period, PreferDatesFrom, PreferMonthOfYear, Settings,
5    StrictDateOrder,
6};
7use chrono::{Datelike, NaiveDate, NaiveDateTime, NaiveTime, Timelike};
8
9#[derive(Debug, Clone)]
10pub struct AbsoluteMatch {
11    pub naive: NaiveDateTime,
12    pub period: Period,
13    pub locale: String,
14    pub has_time: bool,
15    pub parts: Vec<&'static str>,
16    pub part_of_day: Option<PartOfDay>,
17}
18
19/// Try parsing a natural-language absolute or partial date across candidate locales.
20pub fn try_parse_absolute(
21    normalized: &str,
22    candidate_ids: &[usize],
23    registry: &LocaleRegistry,
24    settings: &Settings,
25) -> Option<AbsoluteMatch> {
26    if normalized.contains('年')
27        || normalized.contains('月')
28        || normalized.contains('日')
29        || normalized.contains('년')
30        || normalized.contains('월')
31        || normalized.contains('일')
32    {
33        if let Some(m) = try_cjk_or_korean_date(normalized, settings) {
34            return Some(m);
35        }
36    }
37
38    if normalized.len() == 4 && normalized.bytes().all(|b| b.is_ascii_digit()) {
39        if !settings.strict_parsing
40            && !settings.require_parts.contains(&DatePart::Month)
41            && !settings.require_parts.contains(&DatePart::Day)
42        {
43            if let Ok(year) = normalized.parse::<i32>() {
44                if (1000..=2999).contains(&year) {
45                    let base = settings.effective_base();
46                    let month = match settings.prefer_month_of_year {
47                        PreferMonthOfYear::First => 1,
48                        PreferMonthOfYear::Last => 12,
49                        PreferMonthOfYear::Current => base.month(),
50                    };
51                    let day = resolve_missing_day(year, month, base.day(), settings.prefer_day_of_month);
52                    if let Some(nd) = NaiveDate::from_ymd_opt(year, month, day) {
53                        return Some(AbsoluteMatch {
54                            naive: nd.and_hms_opt(0, 0, 0)?,
55                            period: Period::Year,
56                            locale: "en".to_string(),
57                            has_time: false,
58                            parts: vec!["year"],
59                            part_of_day: None,
60                        });
61                    }
62                }
63            }
64        }
65        return None;
66    }
67
68    for &lid in candidate_ids {
69        let loc = &registry.locales[lid];
70        if let Some(m) = try_parse_in_locale(normalized, loc, settings) {
71            return Some(m);
72        }
73    }
74
75    None
76}
77
78fn try_cjk_or_korean_date(s: &str, settings: &Settings) -> Option<AbsoluteMatch> {
79    let mut year: Option<i32> = None;
80    let mut month: Option<u32> = None;
81    let mut day: Option<u32> = None;
82    let mut hour: u32 = 0;
83    let mut minute: u32 = 0;
84    let mut second: u32 = 0;
85    let mut has_time = false;
86    let is_korean = s.contains('년') || s.contains('월') || s.contains('일') || s.contains('시');
87    let is_pm = s.contains("오후") || s.contains("pm") || s.contains("下午");
88    let is_am = s.contains("오전") || s.contains("am") || s.contains("上午");
89
90    let mut loose_nums: Vec<(u32, usize)> = Vec::new();
91    let mut cur_num = String::new();
92    let chars: Vec<char> = s.chars().collect();
93    let mut idx = 0usize;
94
95    while idx < chars.len() {
96        let ch = chars[idx];
97        if ch.is_ascii_digit() {
98            cur_num.push(ch);
99            idx += 1;
100            continue;
101        }
102        if ch.is_whitespace() {
103            // Look ahead past whitespace: if followed by CJK/Korean suffix, keep cur_num attached!
104            let mut la = idx + 1;
105            while la < chars.len() && chars[la].is_whitespace() {
106                la += 1;
107            }
108            if la < chars.len()
109                && matches!(
110                    chars[la],
111                    '年' | '년' | '月' | '월' | '日' | '号' | '일' | '時' | '时' | '시' | '分' | '분' | '秒' | '초'
112                )
113            {
114                idx += 1;
115                continue;
116            }
117        }
118        if !cur_num.is_empty() {
119            let val: u32 = cur_num.parse().ok()?;
120            let len = cur_num.len();
121            cur_num.clear();
122            match ch {
123                '年' | '년' => {
124                    year = Some(if len <= 2 {
125                        expand_two_digit_year(val)
126                    } else {
127                        val as i32
128                    });
129                }
130                '月' | '월' => month = Some(val),
131                '日' | '号' | '일' => day = Some(val),
132                '時' | '时' | '시' => {
133                    hour = val;
134                    has_time = true;
135                }
136                '分' | '분' => {
137                    minute = val;
138                    has_time = true;
139                }
140                '秒' | '초' => {
141                    second = val;
142                    has_time = true;
143                }
144                ':' => {
145                    // Handle attached day+hour like "2016年6月2911:30" -> day=29, hour=11
146                    if len == 4 && day.is_none() {
147                        let d_cand = val / 100;
148                        let h_cand = val % 100;
149                        if (1..=31).contains(&d_cand) && h_cand <= 23 {
150                            day = Some(d_cand);
151                            let byte_idx = s
152                                .char_indices()
153                                .nth(idx)
154                                .map(|(b, _)| b)
155                                .unwrap_or(0);
156                            if let Some(t) = parse_time_str(&format!("{}{}", h_cand, &s[byte_idx..])) {
157                                hour = t.hour();
158                                minute = t.minute();
159                                second = t.second();
160                                has_time = true;
161                                break;
162                            }
163                        }
164                    }
165                    let byte_idx = s
166                        .char_indices()
167                        .nth(idx)
168                        .map(|(b, _)| b)
169                        .unwrap_or(0);
170                    let start = s[..byte_idx]
171                        .char_indices()
172                        .rev()
173                        .find(|&(_, c)| !c.is_ascii_digit())
174                        .map(|(p, c)| p + c.len_utf8())
175                        .unwrap_or(0);
176                    if let Some(t) = parse_time_str(s[start..].trim()) {
177                        hour = t.hour();
178                        minute = t.minute();
179                        second = t.second();
180                        has_time = true;
181                        break;
182                    }
183                }
184                _ => loose_nums.push((val, len)),
185            }
186        }
187        idx += 1;
188    }
189
190    if !cur_num.is_empty() {
191        let len = cur_num.len();
192        if let Ok(val) = cur_num.parse::<u32>() {
193            loose_nums.push((val, len));
194        }
195    }
196
197    for (val, len) in loose_nums {
198        if year.is_none() && len == 4 && (1000..=2999).contains(&val) {
199            year = Some(val as i32);
200        } else if day.is_none() && (1..=31).contains(&val) && len <= 2 {
201            day = Some(val);
202        }
203    }
204
205    if year.is_none() && month.is_none() {
206        return None;
207    }
208
209    if has_time {
210        if is_pm && hour >= 1 && hour < 12 {
211            hour += 12;
212        } else if is_am && hour == 12 {
213            hour = 0;
214        }
215    }
216
217    let base = settings.effective_base();
218    let (y, m, d, period, parts) = complete_partial_date(year, month, day, has_time, base, settings)?;
219    let nd = NaiveDate::from_ymd_opt(y, m, d)?;
220    let nt = NaiveTime::from_hms_opt(hour, minute, second)?;
221    let lang = if is_korean {
222        "ko"
223    } else if s.contains('時') {
224        "ja"
225    } else {
226        "zh"
227    };
228
229    Some(AbsoluteMatch {
230        naive: nd.and_time(nt),
231        period,
232        locale: lang.to_string(),
233        has_time,
234        parts,
235        part_of_day: None,
236    })
237}
238
239fn lookup_month(s: &str, loc: &CompiledLocale, normalize: bool) -> Option<u8> {
240    if let Some(&m) = loc.months.get(s) {
241        return Some(m);
242    }
243    if normalize {
244        let f = fold_diacritics(s);
245        if let Some(&m) = loc.folded_months.get(&f) {
246            return Some(m);
247        }
248    }
249    None
250}
251
252fn lookup_weekday(s: &str, loc: &CompiledLocale, normalize: bool) -> Option<u8> {
253    if let Some(&w) = loc.weekdays.get(s) {
254        return Some(w);
255    }
256    if normalize {
257        let f = fold_diacritics(s);
258        if let Some(&w) = loc.folded_weekdays.get(&f) {
259            return Some(w);
260        }
261    }
262    None
263}
264
265fn lookup_tod_hour(s: &str, loc: &CompiledLocale, normalize: bool) -> Option<u8> {
266    if let Some(&h) = loc.time_of_day.get(s) {
267        return Some(h);
268    }
269    if normalize {
270        let f = fold_diacritics(s);
271        if let Some(&h) = loc.folded_time_of_day.get(&f).or_else(|| loc.time_of_day.get(&f)) {
272            return Some(h);
273        }
274    }
275    None
276}
277
278fn tod_hour_to_time_and_pod(hour: u8, settings: &Settings) -> (NaiveTime, Option<PartOfDay>) {
279    match hour {
280        3 | 6 => (settings.parts_of_day.time_for(PartOfDay::EarlyMorning), Some(PartOfDay::EarlyMorning)),
281        9 => (settings.parts_of_day.time_for(PartOfDay::Morning), Some(PartOfDay::Morning)),
282        15 => (settings.parts_of_day.time_for(PartOfDay::Afternoon), Some(PartOfDay::Afternoon)),
283        18 => (settings.parts_of_day.time_for(PartOfDay::Evening), Some(PartOfDay::Evening)),
284        20 => (settings.parts_of_day.time_for(PartOfDay::Night), Some(PartOfDay::Night)),
285        12 => (NaiveTime::from_hms_opt(12, 0, 0).unwrap(), None),
286        0 => (NaiveTime::from_hms_opt(0, 0, 0).unwrap(), None),
287        h => (NaiveTime::from_hms_opt(h as u32, 0, 0).unwrap(), None),
288    }
289}
290
291fn try_parse_in_locale(
292    normalized: &str,
293    loc: &CompiledLocale,
294    settings: &Settings,
295) -> Option<AbsoluteMatch> {
296    let raw_tokens = split_date_tokens(normalized, loc, settings.normalize);
297    if raw_tokens.is_empty() || raw_tokens.len() > 18 {
298        return None;
299    }
300
301    let mut year: Option<i32> = None;
302    let mut month: Option<u32> = None;
303    let mut day: Option<u32> = None;
304    let mut weekday_seen: Option<u8> = None;
305    let mut time: Option<NaiveTime> = None;
306    let mut part_of_day: Option<PartOfDay> = None;
307    let mut ampm: Option<bool> = None;
308    let mut free_nums: Vec<(u32, usize)> = Vec::new();
309    let mut matched_locale_signal = false;
310
311    let mut i = 0;
312    while i < raw_tokens.len() {
313        let tok = raw_tokens[i];
314        let clean = tok.trim_matches(|c: char| matches!(c, ',' | '.' | '(' | ')' | '[' | ']'));
315        if clean.is_empty() {
316            i += 1;
317            continue;
318        }
319
320        if settings
321            .skip_tokens
322            .iter()
323            .any(|st| st.eq_ignore_ascii_case(clean))
324        {
325            i += 1;
326            continue;
327        }
328
329        // 1. Apache / Nginx combined year:HH:MM:SS token (e.g. "2026:15:30:00")
330        if year.is_none() && time.is_none() && clean.len() >= 12 {
331            if let Some((y_part, t_part)) = clean.split_once(':') {
332                if y_part.len() == 4 && y_part.bytes().all(|b| b.is_ascii_digit()) {
333                    if let (Ok(y_val), Some(t_val)) = (y_part.parse::<i32>(), parse_time_str(t_part)) {
334                        if (1000..=2999).contains(&y_val) {
335                            year = Some(y_val);
336                            time = Some(t_val);
337                            i += 1;
338                            continue;
339                        }
340                    }
341                }
342            }
343        }
344
345        // 2. Time token (including dot-separated HH.MM with optional German Uhr / Finnish ip.)
346        if time.is_none()
347            && (clean.contains(':')
348                || (clean.len() >= 4
349                    && clean.contains('.')
350                    && clean.as_bytes()[0].is_ascii_digit()
351                    && clean.matches('.').count() == 1)
352                || (clean.len() >= 3
353                    && clean.as_bytes()[0].is_ascii_digit()
354                    && (clean.contains('h')
355                        || clean.ends_with("am")
356                        || clean.ends_with("pm")
357                        || clean.ends_with("a.m")
358                        || clean.ends_with("p.m")
359                        || tok.ends_with("a.m.")
360                        || tok.ends_with("p.m."))))
361        {
362            let time_cand = if tok.ends_with("a.m.") || tok.ends_with("p.m.") {
363                tok.trim_matches(',')
364            } else {
365                clean
366            };
367            if i + 1 < raw_tokens.len() {
368                let next_clean = raw_tokens[i + 1].trim_matches(|c: char| c == '.' || c == ',');
369                if next_clean == "am"
370                    || next_clean == "pm"
371                    || next_clean == "a.m"
372                    || next_clean == "p.m"
373                    || next_clean == "ip"
374                    || next_clean == "ap"
375                    || next_clean == "uhr"
376                    || loc.am.contains(next_clean)
377                    || loc.pm.contains(next_clean)
378                {
379                    let combined = format!("{} {}", time_cand, raw_tokens[i + 1].trim_matches(','));
380                    if let Some(t) = parse_time_str(&combined) {
381                        time = Some(t);
382                        i += 2;
383                        continue;
384                    }
385                }
386            }
387            if let Some(t) = parse_time_str(time_cand) {
388                time = Some(t);
389                i += 1;
390                continue;
391            }
392        }
393
394        // 3. Month name: trigram -> bigram -> unigram
395        if month.is_none() {
396            let mut matched_span = 0usize;
397            for span in (1..=5).rev() {
398                if i + span <= raw_tokens.len() {
399                    let cand = if span == 1 {
400                        clean.to_string()
401                    } else {
402                        let mut s = String::from(clean);
403                        for k in 1..span {
404                            s.push(' ');
405                            s.push_str(raw_tokens[i + k].trim_matches(','));
406                        }
407                        s
408                    };
409                    if let Some(m) = lookup_month(&cand, loc, settings.normalize) {
410                        month = Some(m as u32);
411                        matched_locale_signal = true;
412                        matched_span = span;
413                        break;
414                    }
415                }
416            }
417            if matched_span > 0 {
418                i += matched_span;
419                continue;
420            }
421        }
422
423        // 4. AM/PM markers
424        if clean == "pm" || clean == "p.m" || loc.pm.contains(clean) {
425            ampm = Some(true);
426            i += 1;
427            continue;
428        }
429        if clean == "am" || clean == "a.m" || loc.am.contains(clean) {
430            ampm = Some(false);
431            i += 1;
432            continue;
433        }
434
435        // 5. Weekday name: match up to 4-word phrases -> unigram
436        if weekday_seen.is_none() {
437            let mut matched_span = 0usize;
438            for span in (1..=4).rev() {
439                if i + span <= raw_tokens.len() {
440                    let cand = if span == 1 {
441                        clean.to_string()
442                    } else {
443                        let mut s = String::from(clean);
444                        for k in 1..span {
445                            s.push(' ');
446                            s.push_str(raw_tokens[i + k].trim_matches(','));
447                        }
448                        s
449                    };
450                    if let Some(wd) = lookup_weekday(&cand, loc, settings.normalize) {
451                        weekday_seen = Some(wd);
452                        matched_locale_signal = true;
453                        matched_span = span;
454                        break;
455                    }
456                }
457            }
458            if matched_span > 0 {
459                i += matched_span;
460                continue;
461            }
462        }
463
464        // 6. Time-of-day word on absolute date ("12 December 2025 morning")
465        if time.is_none() {
466            if i + 1 < raw_tokens.len() {
467                let bigram = format!("{} {}", clean, raw_tokens[i + 1].trim_matches(','));
468                if let Some(h) = lookup_tod_hour(&bigram, loc, settings.normalize) {
469                    let (t, pod) = tod_hour_to_time_and_pod(h, settings);
470                    time = Some(t);
471                    part_of_day = pod;
472                    i += 2;
473                    continue;
474                }
475            }
476            if let Some(h) = lookup_tod_hour(clean, loc, settings.normalize) {
477                let (t, pod) = tod_hour_to_time_and_pod(h, settings);
478                time = Some(t);
479                part_of_day = pod;
480                i += 1;
481                continue;
482            }
483        }
484
485        // 7. Numeric token (including ordinals)
486        if let Some((num, digit_len)) = parse_date_number_or_ordinal(clean) {
487            if digit_len == 4 && (1000..=2999).contains(&num) && year.is_none() {
488                year = Some(num as i32);
489            } else {
490                free_nums.push((num, digit_len));
491            }
492            i += 1;
493            continue;
494        }
495
496        // 8. Skip / connector words (including localized "year" markers like "year", "год", "সাল", "klo", "u")
497        if loc.skip.contains(clean)
498            || loc.units.contains_key(clean)
499            || matches!(
500                clean,
501                "at" | "on" | "of" | "the" | "in" | "de" | "del" | "el" | "la" | "le" | "à"
502                    | "am" | "um" | "den" | "saat" | "tarih" | "tarihinde" | "в" | "г" | "года"
503                    | "год" | "günü" | "gunu" | "yılında" | "yilinda" | "yılı" | "year" | "klo"
504                    | "u" | "у" | "سنة" | "år"
505            )
506        {
507            i += 1;
508            continue;
509        }
510
511        return None;
512    }
513
514    if !matched_locale_signal && year.is_none() {
515        return None;
516    }
517
518    let has_time = time.is_some();
519    if let (Some(t), Some(is_pm)) = (time, ampm) {
520        let mut h = t.hour();
521        if is_pm && h >= 1 && h < 12 {
522            h += 12;
523        } else if !is_pm && h == 12 {
524            h = 0;
525        }
526        time = NaiveTime::from_hms_nano_opt(h, t.minute(), t.second(), t.nanosecond());
527    }
528
529    let year_first = year.is_some()
530        && raw_tokens
531            .first()
532            .and_then(|t| parse_date_number_or_ordinal(t))
533            .map(|(n, l)| l == 4 && n as i32 == year.unwrap())
534            .unwrap_or(false);
535
536    let order = if settings.date_order.is_some() || settings.region.is_some() {
537        settings.effective_date_order(loc.date_order)
538    } else if year_first {
539        DateOrder::YMD
540    } else if settings.prefer_locale_date_order {
541        loc.date_order
542    } else {
543        DateOrder::MDY
544    };
545
546    match free_nums.as_slice() {
547        [] => {}
548        [(n, len)] => {
549            if month.is_some() && day.is_none() && (1..=31).contains(n) && *len <= 2 {
550                day = Some(*n);
551            } else if year.is_none() && *len == 2 {
552                year = Some(expand_two_digit_year(*n));
553            } else {
554                return None;
555            }
556        }
557        [(n1, l1), (n2, l2)] => {
558            if month.is_some() && day.is_none() && year.is_none() {
559                if (1..=31).contains(n1) && *l1 <= 2 && *l2 == 2 {
560                    day = Some(*n1);
561                    year = Some(expand_two_digit_year(*n2));
562                } else if (1..=31).contains(n2) && *l2 <= 2 && *l1 == 2 {
563                    year = Some(expand_two_digit_year(*n1));
564                    day = Some(*n2);
565                } else if (1..=31).contains(n1) && (1..=31).contains(n2) && n1 <= n2 {
566                    // Range without year: "June 12-14"
567                    day = Some(*n1);
568                } else {
569                    return None;
570                }
571            } else if month.is_some() && year.is_some() && day.is_none() && (1..=31).contains(n1) && (1..=31).contains(n2) && n1 <= n2 {
572                // Date range like "June 12-14, 2021" or "12-14 June 2021" -> take start day
573                day = Some(*n1);
574            } else if month.is_none() && day.is_none() {
575                match order {
576                    DateOrder::YMD | DateOrder::MDY if (1..=12).contains(n1) && (1..=31).contains(n2) => {
577                        month = Some(*n1);
578                        day = Some(*n2);
579                    }
580                    DateOrder::YMD | DateOrder::MDY if settings.strict_date_order == StrictDateOrder::All => {
581                        return None;
582                    }
583                    _ if (1..=31).contains(n1) && (1..=12).contains(n2) => {
584                        day = Some(*n1);
585                        month = Some(*n2);
586                    }
587                    _ if settings.strict_date_order == StrictDateOrder::All => {
588                        return None;
589                    }
590                    _ if (1..=12).contains(n1) && (1..=31).contains(n2) => {
591                        month = Some(*n1);
592                        day = Some(*n2);
593                    }
594                    _ => return None,
595                }
596            } else {
597                return None;
598            }
599        }
600        _ => return None,
601    }
602
603    if year.is_none() && month.is_none() && day.is_none() {
604        let wd = weekday_seen?;
605        if settings.strict_parsing
606            || settings.require_parts.contains(&DatePart::Year)
607            || settings.require_parts.contains(&DatePart::Month)
608            || settings.require_parts.contains(&DatePart::Day)
609        {
610            return None;
611        }
612        let base = settings.effective_base();
613        let cur_wd = base.weekday().num_days_from_monday() as i64;
614        let tgt_wd = wd as i64;
615        let diff = match settings.prefer_dates_from {
616            PreferDatesFrom::Past | PreferDatesFrom::CurrentPeriod => {
617                let mut d = tgt_wd - cur_wd;
618                if d > 0 {
619                    d -= 7;
620                }
621                d
622            }
623            PreferDatesFrom::Future => {
624                let mut d = tgt_wd - cur_wd;
625                if d < 0 {
626                    d += 7;
627                }
628                d
629            }
630        };
631        let target_date = base.date() + chrono::Duration::days(diff);
632        let nt = time.unwrap_or_else(|| NaiveTime::from_hms_opt(0, 0, 0).unwrap());
633        let mut p = vec!["year", "month", "day"];
634        if has_time {
635            p.push("time");
636        }
637        return Some(AbsoluteMatch {
638            naive: target_date.and_time(nt),
639            period: Period::Day,
640            locale: loc.code.clone(),
641            has_time,
642            parts: p,
643            part_of_day,
644        });
645    }
646
647    let base = settings.effective_base();
648    let (y, m, d, period, parts) =
649        complete_partial_date(year, month, day, has_time, base, settings)?;
650    let nd = NaiveDate::from_ymd_opt(y, m, d)?;
651    let nt = time.unwrap_or_else(|| NaiveTime::from_hms_opt(0, 0, 0).unwrap());
652
653    Some(AbsoluteMatch {
654        naive: nd.and_time(nt),
655        period,
656        locale: loc.code.clone(),
657        has_time,
658        parts,
659        part_of_day,
660    })
661}
662
663fn complete_partial_date(
664    year: Option<i32>,
665    month: Option<u32>,
666    day: Option<u32>,
667    has_time: bool,
668    base: NaiveDateTime,
669    settings: &Settings,
670) -> Option<(i32, u32, u32, Period, Vec<&'static str>)> {
671    if settings.strict_parsing && (year.is_none() || month.is_none() || day.is_none()) {
672        return None;
673    }
674    if settings.require_parts.contains(&DatePart::Year) && year.is_none() {
675        return None;
676    }
677    if settings.require_parts.contains(&DatePart::Month) && month.is_none() {
678        return None;
679    }
680    if settings.require_parts.contains(&DatePart::Day) && day.is_none() {
681        return None;
682    }
683
684    let period = if day.is_some() {
685        Period::Day
686    } else if month.is_some() {
687        Period::Month
688    } else {
689        Period::Year
690    };
691
692    let mut parts = Vec::with_capacity(4);
693    if year.is_some() {
694        parts.push("year");
695    }
696    if month.is_some() {
697        parts.push("month");
698    }
699    if day.is_some() {
700        parts.push("day");
701    }
702    if has_time {
703        parts.push("time");
704    }
705
706    let m = month.unwrap_or_else(|| match settings.prefer_month_of_year {
707        PreferMonthOfYear::First => 1,
708        PreferMonthOfYear::Last => 12,
709        PreferMonthOfYear::Current => base.month(),
710    });
711    if !(1..=12).contains(&m) {
712        return None;
713    }
714
715    let mut y = year.unwrap_or_else(|| base.year());
716    let d = day.unwrap_or_else(|| resolve_missing_day(y, m, base.day(), settings.prefer_day_of_month));
717    if d < 1 || d > days_in_month(y, m) {
718        return None;
719    }
720
721    if year.is_none() {
722        if let Some(cand) = NaiveDate::from_ymd_opt(y, m, d) {
723            match settings.prefer_dates_from {
724                PreferDatesFrom::Past if cand > base.date() => y -= 1,
725                PreferDatesFrom::Future if cand < base.date() => y += 1,
726                _ => {}
727            }
728        }
729    }
730
731    let final_d = d.min(days_in_month(y, m));
732    Some((y, m, final_d, period, parts))
733}
734
735fn split_date_tokens<'a>(s: &'a str, loc: &CompiledLocale, normalize: bool) -> Vec<&'a str> {
736    let mut out = Vec::with_capacity(8);
737    for chunk in s.split(|c: char| {
738        c.is_whitespace() || c == ',' || c == '/' || c == '[' || c == ']' || c == '–' || c == '—'
739    }) {
740        if chunk.is_empty() {
741            continue;
742        }
743        // Split dot-separated month expressions like "08.Haziran.2014" or "2005г.", but keep fractional times like "13:11:23.678" intact
744        if chunk.contains('.')
745            && !chunk.contains(':')
746            && !chunk.ends_with("a.m.")
747            && !chunk.ends_with("p.m.")
748            && !(chunk.matches('.').count() == 1
749                && chunk.chars().all(|c| c.is_ascii_digit() || c == '.'))
750        {
751            let clean = chunk.trim_matches('.');
752            if lookup_month(clean, loc, normalize).is_some()
753                || lookup_weekday(clean, loc, normalize).is_some()
754            {
755                out.push(clean);
756                continue;
757            }
758            for sub in chunk.split('.') {
759                if !sub.is_empty() {
760                    push_splitting_attached_digits(sub, loc, normalize, &mut out);
761                }
762            }
763            continue;
764        }
765        if chunk.contains('-') {
766            let clean = chunk.trim_matches('.');
767            if lookup_month(clean, loc, normalize).is_some()
768                || lookup_weekday(clean, loc, normalize).is_some()
769                || loc.months.keys().any(|k| k.split_whitespace().any(|w| w == clean))
770            {
771                out.push(chunk);
772                continue;
773            }
774            for sub in chunk.split('-') {
775                if !sub.is_empty() {
776                    push_splitting_attached_digits(sub, loc, normalize, &mut out);
777                }
778            }
779        } else {
780            push_splitting_attached_digits(chunk, loc, normalize, &mut out);
781        }
782    }
783    out
784}
785
786fn push_splitting_attached_digits<'a>(
787    tok: &'a str,
788    loc: &CompiledLocale,
789    normalize: bool,
790    out: &mut Vec<&'a str>,
791) {
792    // Keep pure numbers, times, ordinals, and known hyphenated/numeric month names intact
793    if tok.contains(':')
794        || tok.ends_with("am")
795        || tok.ends_with("pm")
796        || tok.ends_with("a.m.")
797        || tok.ends_with("p.m.")
798        || tok.bytes().all(|b| b.is_ascii_digit())
799        || parse_date_number_or_ordinal(tok).is_some()
800        || lookup_month(tok, loc, normalize).is_some()
801        || lookup_weekday(tok, loc, normalize).is_some()
802    {
803        out.push(tok);
804        return;
805    }
806    // Check if token mixes digits and non-digits (e.g. "2005г", "12Dec2025")
807    let has_digit = tok.chars().any(|c| c.is_ascii_digit());
808    let has_alpha = tok.chars().any(|c| c.is_alphabetic());
809    if !has_digit || !has_alpha {
810        out.push(tok);
811        return;
812    }
813    // Keep French/European "14h30" intact
814    if tok.contains('h') && tok.chars().all(|c| c.is_ascii_digit() || c == 'h' || c == 'm' || c == 's') {
815        out.push(tok);
816        return;
817    }
818    let mut start = 0usize;
819    let mut prev_digit = tok.chars().next().unwrap().is_ascii_digit();
820    for (idx, ch) in tok.char_indices().skip(1) {
821        let cur_digit = ch.is_ascii_digit();
822        if cur_digit != prev_digit {
823            out.push(&tok[start..idx]);
824            start = idx;
825            prev_digit = cur_digit;
826        }
827    }
828    if start < tok.len() {
829        out.push(&tok[start..]);
830    }
831}
832
833fn parse_date_number_or_ordinal(s: &str) -> Option<(u32, usize)> {
834    if s.is_empty() || s.len() > 6 {
835        return None;
836    }
837    let stripped = s
838        .strip_suffix("st")
839        .or_else(|| s.strip_suffix("nd"))
840        .or_else(|| s.strip_suffix("rd"))
841        .or_else(|| s.strip_suffix("th"))
842        .or_else(|| s.strip_suffix("er"))
843        .or_else(|| s.strip_suffix('º'))
844        .or_else(|| s.strip_suffix('ª'))
845        .unwrap_or(s);
846
847    if stripped.is_empty() || stripped.len() > 4 || !stripped.bytes().all(|b| b.is_ascii_digit()) {
848        return None;
849    }
850    let val: u32 = stripped.parse().ok()?;
851    Some((val, stripped.len()))
852}