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
19pub 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 = ®istry.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 extract_cjk_era_year(s: &str) -> Option<Result<(i32, String, bool), ()>> {
79 const ERAS: [(&str, i32, bool); 7] = [
80 ("令和", 2018, true),
81 ("平成", 1988, true),
82 ("昭和", 1925, true),
83 ("大正", 1911, true),
84 ("明治", 1867, true),
85 ("民國", 1911, false),
86 ("民国", 1911, false),
87 ];
88 for &(era, base, is_jp) in &ERAS {
89 if let Some(pos) = s.find(era) {
90 let after_era = &s[pos + era.len()..];
91 let trimmed = after_era.trim_start();
92 let ws_skipped = after_era.len() - trimmed.len();
93 let mut cursor = pos + era.len() + ws_skipped;
94
95 let era_num: i32 = if let Some(rest) = trimmed.strip_prefix('元') {
96 let rest_trim = rest.trim_start();
97 let nen_ws = rest.len() - rest_trim.len();
98 if !rest_trim.starts_with('年') {
99 return Some(Err(()));
100 }
101 cursor += '元'.len_utf8() + nen_ws + '年'.len_utf8();
102 1
103 } else {
104 let mut d_end = 0usize;
105 for (i, ch) in trimmed.char_indices() {
106 if ch.is_ascii_digit() {
107 d_end = i + 1;
108 } else {
109 break;
110 }
111 }
112 let max_digits = if is_jp { 2 } else { 3 };
113 let max_val = if is_jp { 99 } else { 999 };
114 if d_end == 0 || d_end > max_digits {
115 return Some(Err(()));
116 }
117 let val: i32 = match trimmed[..d_end].parse() {
118 Ok(v) if (1..=max_val).contains(&v) => v,
119 _ => return Some(Err(())),
120 };
121 let after_digits = &trimmed[d_end..];
122 let rest_trim = after_digits.trim_start();
123 let nen_ws = after_digits.len() - rest_trim.len();
124 if !rest_trim.starts_with('年') {
125 return Some(Err(()));
126 }
127 cursor += d_end + nen_ws + '年'.len_utf8();
128 val
129 };
130
131 let mut rem = String::with_capacity(s.len());
132 rem.push_str(&s[..pos]);
133 rem.push_str(&s[cursor..]);
134 return Some(Ok((base + era_num, rem, is_jp)));
135 }
136 }
137 None
138}
139
140fn try_cjk_or_korean_date(s: &str, settings: &Settings) -> Option<AbsoluteMatch> {
141 let mut year: Option<i32> = None;
142 let mut month: Option<u32> = None;
143 let mut day: Option<u32> = None;
144 let mut hour: u32 = 0;
145 let mut minute: u32 = 0;
146 let mut second: u32 = 0;
147 let mut has_time = false;
148 let mut is_japanese = false;
149 let owned_rem;
150 let scan_s: &str = match extract_cjk_era_year(s) {
151 Some(Ok((gy, rem, era_is_jp))) => {
152 year = Some(gy);
153 is_japanese = era_is_jp;
154 owned_rem = rem;
155 &owned_rem
156 }
157 Some(Err(())) => return None,
158 None => s,
159 };
160
161 let is_korean =
162 scan_s.contains('년') || scan_s.contains('월') || scan_s.contains('일') || scan_s.contains('시');
163 let is_pm = scan_s.contains("오후") || scan_s.contains("pm") || scan_s.contains("下午");
164 let is_am = scan_s.contains("오전") || scan_s.contains("am") || scan_s.contains("上午");
165
166 let mut loose_nums: Vec<(u32, usize)> = Vec::new();
167 let mut cur_num = String::new();
168 let chars: Vec<char> = scan_s.chars().collect();
169 let mut idx = 0usize;
170
171 while idx < chars.len() {
172 let ch = chars[idx];
173 if ch.is_ascii_digit() {
174 cur_num.push(ch);
175 idx += 1;
176 continue;
177 }
178 if ch.is_whitespace() {
179 let mut la = idx + 1;
181 while la < chars.len() && chars[la].is_whitespace() {
182 la += 1;
183 }
184 if la < chars.len()
185 && matches!(
186 chars[la],
187 '年' | '년' | '月' | '월' | '日' | '号' | '일' | '時' | '时' | '点' | '點' | '시' | '分' | '분' | '秒' | '초'
188 )
189 {
190 idx += 1;
191 continue;
192 }
193 }
194 if !cur_num.is_empty() {
195 let val: u32 = cur_num.parse().ok()?;
196 let len = cur_num.len();
197 cur_num.clear();
198 match ch {
199 '年' | '년' => {
200 year = Some(if len <= 2 {
201 expand_two_digit_year(val)
202 } else {
203 val as i32
204 });
205 }
206 '月' | '월' => month = Some(val),
207 '日' | '号' | '일' => day = Some(val),
208 '時' | '时' | '点' | '點' | '시' => {
209 hour = val;
210 has_time = true;
211 }
212 '分' | '분' => {
213 minute = val;
214 has_time = true;
215 }
216 '秒' | '초' => {
217 second = val;
218 has_time = true;
219 }
220 ':' => {
221 if len == 4 && day.is_none() {
223 let d_cand = val / 100;
224 let h_cand = val % 100;
225 if (1..=31).contains(&d_cand) && h_cand <= 23 {
226 day = Some(d_cand);
227 let byte_idx = scan_s
228 .char_indices()
229 .nth(idx)
230 .map(|(b, _)| b)
231 .unwrap_or(0);
232 if let Some(t) = parse_time_str(&format!("{}{}", h_cand, &scan_s[byte_idx..])) {
233 hour = t.hour();
234 minute = t.minute();
235 second = t.second();
236 has_time = true;
237 break;
238 }
239 }
240 }
241 let byte_idx = scan_s
242 .char_indices()
243 .nth(idx)
244 .map(|(b, _)| b)
245 .unwrap_or(0);
246 let start = scan_s[..byte_idx]
247 .char_indices()
248 .rev()
249 .find(|&(_, c)| !c.is_ascii_digit())
250 .map(|(p, c)| p + c.len_utf8())
251 .unwrap_or(0);
252 if let Some(t) = parse_time_str(scan_s[start..].trim()) {
253 hour = t.hour();
254 minute = t.minute();
255 second = t.second();
256 has_time = true;
257 break;
258 }
259 }
260 _ => loose_nums.push((val, len)),
261 }
262 }
263 idx += 1;
264 }
265
266 if !cur_num.is_empty() {
267 let len = cur_num.len();
268 if let Ok(val) = cur_num.parse::<u32>() {
269 loose_nums.push((val, len));
270 }
271 }
272
273 for (val, len) in loose_nums {
274 if year.is_none() && len == 4 && (1000..=2999).contains(&val) {
275 year = Some(val as i32);
276 } else if day.is_none() && (1..=31).contains(&val) && len <= 2 {
277 day = Some(val);
278 }
279 }
280
281 if year.is_none() && month.is_none() {
282 return None;
283 }
284
285 let mut part_of_day: Option<PartOfDay> = None;
286 let mut tod_time: Option<NaiveTime> = None;
287 if has_time {
288 if is_pm && hour >= 1 && hour < 12 {
289 hour += 12;
290 } else if is_am && hour == 12 {
291 hour = 0;
292 }
293 } else {
294 let tod_hour: Option<u8> = [
295 ("真夜中", 0u8),
296 ("午夜", 0),
297 ("자정", 0),
298 ("早上", 9),
299 ("上午", 9),
300 ("아침", 9),
301 ("오전", 9),
302 ("朝", 9),
303 ("正午", 12),
304 ("中午", 12),
305 ("정오", 12),
306 ("午後", 15),
307 ("下午", 15),
308 ("오후", 15),
309 ("夕方", 18),
310 ("傍晚", 18),
311 ("저녁", 18),
312 ("晚上", 20),
313 ("夜", 20),
314 ("밤", 20),
315 ]
316 .into_iter()
317 .find(|(tok, _)| scan_s.contains(tok))
318 .map(|(_, h)| h);
319
320 if let Some(h) = tod_hour {
321 has_time = true;
322 part_of_day = PartOfDay::from_hour(h);
323 if h == 0 || h == 12 {
324 tod_time = NaiveTime::from_hms_opt(h as u32, 0, 0);
325 } else if let Some(p) = part_of_day {
326 tod_time = Some(settings.parts_of_day.time_for(p));
327 }
328 }
329 }
330
331 let base = settings.effective_base();
332 let (y, m, d, period, parts) = complete_partial_date(year, month, day, has_time, base, settings)?;
333 let nd = NaiveDate::from_ymd_opt(y, m, d)?;
334 let nt = tod_time.or_else(|| NaiveTime::from_hms_opt(hour, minute, second))?;
335 let lang = if is_korean {
336 "ko"
337 } else if is_japanese
338 || scan_s.contains('時')
339 || scan_s.contains('朝')
340 || scan_s.contains('夜')
341 || scan_s.contains("夕方")
342 || scan_s.contains("正午")
343 || scan_s.contains("真夜中")
344 || settings
345 .languages
346 .as_deref()
347 .map(|ls| {
348 ls.iter().any(|l| l.eq_ignore_ascii_case("ja"))
349 && !ls.iter().any(|l| l.to_ascii_lowercase().starts_with("zh"))
350 })
351 .unwrap_or(false)
352 {
353 "ja"
354 } else {
355 "zh"
356 };
357
358 Some(AbsoluteMatch {
359 naive: nd.and_time(nt),
360 period,
361 locale: lang.to_string(),
362 has_time,
363 parts,
364 part_of_day,
365 })
366}
367
368fn lookup_month(s: &str, loc: &CompiledLocale, normalize: bool) -> Option<u8> {
369 if let Some(&m) = loc.months.get(s) {
370 return Some(m);
371 }
372 if normalize {
373 let f = fold_diacritics(s);
374 if let Some(&m) = loc.folded_months.get(&f) {
375 return Some(m);
376 }
377 }
378 None
379}
380
381fn lookup_weekday(s: &str, loc: &CompiledLocale, normalize: bool) -> Option<u8> {
382 if let Some(&w) = loc.weekdays.get(s) {
383 return Some(w);
384 }
385 if normalize {
386 let f = fold_diacritics(s);
387 if let Some(&w) = loc.folded_weekdays.get(&f) {
388 return Some(w);
389 }
390 }
391 None
392}
393
394fn lookup_tod_hour(s: &str, loc: &CompiledLocale, normalize: bool) -> Option<u8> {
395 if let Some(&h) = loc.time_of_day.get(s) {
396 return Some(h);
397 }
398 if normalize {
399 let f = fold_diacritics(s);
400 if let Some(&h) = loc.folded_time_of_day.get(&f).or_else(|| loc.time_of_day.get(&f)) {
401 return Some(h);
402 }
403 }
404 None
405}
406
407fn tod_hour_to_time_and_pod(hour: u8, settings: &Settings) -> (NaiveTime, Option<PartOfDay>) {
408 match hour {
409 3 | 6 => (settings.parts_of_day.time_for(PartOfDay::EarlyMorning), Some(PartOfDay::EarlyMorning)),
410 9 => (settings.parts_of_day.time_for(PartOfDay::Morning), Some(PartOfDay::Morning)),
411 15 => (settings.parts_of_day.time_for(PartOfDay::Afternoon), Some(PartOfDay::Afternoon)),
412 18 => (settings.parts_of_day.time_for(PartOfDay::Evening), Some(PartOfDay::Evening)),
413 20 => (settings.parts_of_day.time_for(PartOfDay::Night), Some(PartOfDay::Night)),
414 12 => (NaiveTime::from_hms_opt(12, 0, 0).unwrap(), None),
415 0 => (NaiveTime::from_hms_opt(0, 0, 0).unwrap(), None),
416 h => (NaiveTime::from_hms_opt(h as u32, 0, 0).unwrap(), None),
417 }
418}
419
420fn try_parse_in_locale(
421 normalized: &str,
422 loc: &CompiledLocale,
423 settings: &Settings,
424) -> Option<AbsoluteMatch> {
425 let raw_tokens = split_date_tokens(normalized, loc, settings.normalize);
426 if raw_tokens.is_empty() || raw_tokens.len() > 18 {
427 return None;
428 }
429
430 let mut year: Option<i32> = None;
431 let mut month: Option<u32> = None;
432 let mut day: Option<u32> = None;
433 let mut weekday_seen: Option<u8> = None;
434 let mut time: Option<NaiveTime> = None;
435 let mut part_of_day: Option<PartOfDay> = None;
436 let mut ampm: Option<bool> = None;
437 let mut free_nums: Vec<(u32, usize)> = Vec::new();
438 let mut matched_locale_signal = false;
439 let mut ambiguous_month_weekday: Option<u8> = None;
440
441 let mut i = 0;
442 while i < raw_tokens.len() {
443 let tok = raw_tokens[i];
444 let clean = tok.trim_matches(|c: char| matches!(c, ',' | '.' | '(' | ')' | '[' | ']'));
445 if clean.is_empty() {
446 i += 1;
447 continue;
448 }
449
450 if settings
451 .skip_tokens
452 .iter()
453 .any(|st| st.eq_ignore_ascii_case(clean))
454 {
455 i += 1;
456 continue;
457 }
458
459 if year.is_none() && time.is_none() && clean.len() >= 12 {
461 if let Some((y_part, t_part)) = clean.split_once(':') {
462 if y_part.len() == 4 && y_part.bytes().all(|b| b.is_ascii_digit()) {
463 if let (Ok(y_val), Some(t_val)) = (y_part.parse::<i32>(), parse_time_str(t_part)) {
464 if (1000..=2999).contains(&y_val) {
465 year = Some(y_val);
466 time = Some(t_val);
467 i += 1;
468 continue;
469 }
470 }
471 }
472 }
473 }
474
475 if time.is_none()
477 && (clean.contains(':')
478 || (clean.len() >= 4
479 && clean.contains('.')
480 && clean.as_bytes()[0].is_ascii_digit()
481 && clean.matches('.').count() == 1)
482 || (clean.len() >= 3
483 && clean.as_bytes()[0].is_ascii_digit()
484 && (clean.contains('h')
485 || clean.ends_with("am")
486 || clean.ends_with("pm")
487 || clean.ends_with("a.m")
488 || clean.ends_with("p.m")
489 || tok.ends_with("a.m.")
490 || tok.ends_with("p.m."))))
491 {
492 let time_cand = if tok.ends_with("a.m.") || tok.ends_with("p.m.") {
493 tok.trim_matches(',')
494 } else {
495 clean
496 };
497 if i + 1 < raw_tokens.len() {
498 let next_clean = raw_tokens[i + 1].trim_matches(|c: char| c == '.' || c == ',');
499 if next_clean == "am"
500 || next_clean == "pm"
501 || next_clean == "a.m"
502 || next_clean == "p.m"
503 || next_clean == "ip"
504 || next_clean == "ap"
505 || next_clean == "uhr"
506 || loc.am.contains(next_clean)
507 || loc.pm.contains(next_clean)
508 {
509 let combined = format!("{} {}", time_cand, raw_tokens[i + 1].trim_matches(','));
510 if let Some(t) = parse_time_str(&combined) {
511 time = Some(t);
512 i += 2;
513 continue;
514 }
515 }
516 }
517 if let Some(t) = parse_time_str(time_cand) {
518 time = Some(t);
519 i += 1;
520 continue;
521 }
522 }
523
524 if month.is_none() || (weekday_seen.is_none() && ambiguous_month_weekday.is_some()) {
527 let mut matched_span = 0usize;
528 for span in (1..=5).rev() {
529 if i + span <= raw_tokens.len() {
530 let cand = if span == 1 {
531 clean.to_string()
532 } else {
533 let mut s = String::from(clean);
534 for k in 1..span {
535 s.push(' ');
536 s.push_str(raw_tokens[i + k].trim_matches(','));
537 }
538 s
539 };
540 if let Some(m) = lookup_month(&cand, loc, settings.normalize) {
541 if month.is_none() {
542 ambiguous_month_weekday = if weekday_seen.is_none() {
543 lookup_weekday(&cand, loc, settings.normalize)
544 } else {
545 None
546 };
547 } else if lookup_weekday(&cand, loc, settings.normalize).is_some() {
548 continue;
549 } else if let Some(prev_wd) = ambiguous_month_weekday.take() {
550 weekday_seen = Some(prev_wd);
551 }
552 month = Some(m as u32);
553 matched_locale_signal = true;
554 matched_span = span;
555 break;
556 }
557 }
558 }
559 if matched_span > 0 {
560 i += matched_span;
561 continue;
562 }
563 }
564
565 if clean == "pm" || clean == "p.m" || loc.pm.contains(clean) {
567 ampm = Some(true);
568 i += 1;
569 continue;
570 }
571 if clean == "am" || clean == "a.m" || loc.am.contains(clean) {
572 ampm = Some(false);
573 i += 1;
574 continue;
575 }
576
577 if weekday_seen.is_none() {
579 let mut matched_span = 0usize;
580 for span in (1..=4).rev() {
581 if i + span <= raw_tokens.len() {
582 let cand = if span == 1 {
583 clean.to_string()
584 } else {
585 let mut s = String::from(clean);
586 for k in 1..span {
587 s.push(' ');
588 s.push_str(raw_tokens[i + k].trim_matches(','));
589 }
590 s
591 };
592 if let Some(wd) = lookup_weekday(&cand, loc, settings.normalize) {
593 weekday_seen = Some(wd);
594 matched_locale_signal = true;
595 matched_span = span;
596 break;
597 }
598 }
599 }
600 if matched_span > 0 {
601 i += matched_span;
602 continue;
603 }
604 }
605
606 if time.is_none() {
608 if i + 1 < raw_tokens.len() {
609 let bigram = format!("{} {}", clean, raw_tokens[i + 1].trim_matches(','));
610 if let Some(h) = lookup_tod_hour(&bigram, loc, settings.normalize) {
611 let (t, pod) = tod_hour_to_time_and_pod(h, settings);
612 time = Some(t);
613 part_of_day = pod;
614 i += 2;
615 continue;
616 }
617 }
618 if let Some(h) = lookup_tod_hour(clean, loc, settings.normalize) {
619 let (t, pod) = tod_hour_to_time_and_pod(h, settings);
620 time = Some(t);
621 part_of_day = pod;
622 i += 1;
623 continue;
624 }
625 }
626
627 if year.is_none() {
629 if let Some(rest) = clean
630 .strip_prefix('\'')
631 .or_else(|| clean.strip_prefix('\u{2019}'))
632 .or_else(|| clean.strip_prefix('\u{2018}'))
633 {
634 if rest.len() == 2 && rest.bytes().all(|b| b.is_ascii_digit()) {
635 if let Ok(y2) = rest.parse::<u32>() {
636 year = Some(expand_two_digit_year(y2));
637 i += 1;
638 continue;
639 }
640 }
641 }
642 }
643
644 if let Some((num, digit_len)) = parse_date_number_or_ordinal(clean) {
646 if digit_len == 4 && (1000..=2999).contains(&num) && year.is_none() {
647 year = Some(num as i32);
648 } else {
649 free_nums.push((num, digit_len));
650 }
651 i += 1;
652 continue;
653 }
654
655 if loc.skip.contains(clean)
657 || loc.units.contains_key(clean)
658 || is_locale_connector(loc.code.as_str(), clean)
659 || matches!(
660 clean,
661 "at" | "on" | "of" | "the" | "in" | "de" | "del" | "el" | "la" | "le" | "à"
662 | "am" | "um" | "den" | "saat" | "tarih" | "tarihinde" | "в" | "г" | "года"
663 | "год" | "günü" | "gunu" | "yılında" | "yilinda" | "yılı" | "year" | "klo"
664 | "u" | "у" | "سنة" | "år"
665 )
666 {
667 i += 1;
668 continue;
669 }
670
671 return None;
672 }
673
674 if !matched_locale_signal && year.is_none() {
675 return None;
676 }
677
678 let has_time = time.is_some();
679 if let (Some(t), Some(is_pm)) = (time, ampm) {
680 let mut h = t.hour();
681 if is_pm && h >= 1 && h < 12 {
682 h += 12;
683 } else if !is_pm && h == 12 {
684 h = 0;
685 }
686 time = NaiveTime::from_hms_nano_opt(h, t.minute(), t.second(), t.nanosecond());
687 }
688
689 let year_first = year.is_some()
690 && raw_tokens
691 .first()
692 .and_then(|t| parse_date_number_or_ordinal(t))
693 .map(|(n, l)| l == 4 && n as i32 == year.unwrap())
694 .unwrap_or(false);
695
696 let order = if settings.date_order.is_some() || settings.region.is_some() {
697 settings.effective_date_order(loc.date_order)
698 } else if year_first {
699 DateOrder::YMD
700 } else if settings.prefer_locale_date_order {
701 loc.date_order
702 } else {
703 DateOrder::MDY
704 };
705
706 match free_nums.as_slice() {
707 [] => {}
708 [(n, len)] => {
709 if month.is_some() && day.is_none() && (1..=31).contains(n) && *len <= 2 {
710 day = Some(*n);
711 } else if year.is_none() && *len == 2 {
712 year = Some(expand_two_digit_year(*n));
713 } else {
714 return None;
715 }
716 }
717 [(n1, l1), (n2, l2)] => {
718 if month.is_some() && day.is_none() && year.is_none() {
719 if (1..=31).contains(n1) && *l1 <= 2 && *l2 == 2 {
720 day = Some(*n1);
721 year = Some(expand_two_digit_year(*n2));
722 } else if (1..=31).contains(n2) && *l2 <= 2 && *l1 == 2 {
723 year = Some(expand_two_digit_year(*n1));
724 day = Some(*n2);
725 } else if (1..=31).contains(n1) && (1..=31).contains(n2) && n1 <= n2 {
726 day = Some(*n1);
728 } else {
729 return None;
730 }
731 } else if month.is_some() && year.is_some() && day.is_none() && (1..=31).contains(n1) && (1..=31).contains(n2) && n1 <= n2 {
732 day = Some(*n1);
734 } else if month.is_none() && day.is_none() {
735 match order {
736 DateOrder::YMD | DateOrder::MDY if (1..=12).contains(n1) && (1..=31).contains(n2) => {
737 month = Some(*n1);
738 day = Some(*n2);
739 }
740 DateOrder::YMD | DateOrder::MDY if settings.strict_date_order == StrictDateOrder::All => {
741 return None;
742 }
743 _ if (1..=31).contains(n1) && (1..=12).contains(n2) => {
744 day = Some(*n1);
745 month = Some(*n2);
746 }
747 _ if settings.strict_date_order == StrictDateOrder::All => {
748 return None;
749 }
750 _ if (1..=12).contains(n1) && (1..=31).contains(n2) => {
751 month = Some(*n1);
752 day = Some(*n2);
753 }
754 _ => return None,
755 }
756 } else {
757 return None;
758 }
759 }
760 _ => return None,
761 }
762
763 if year.is_none() && month.is_none() && day.is_none() {
764 let wd = weekday_seen?;
765 if settings.strict_parsing
766 || settings.require_parts.contains(&DatePart::Year)
767 || settings.require_parts.contains(&DatePart::Month)
768 || settings.require_parts.contains(&DatePart::Day)
769 {
770 return None;
771 }
772 let base = settings.effective_base();
773 let cur_wd = base.weekday().num_days_from_monday() as i64;
774 let tgt_wd = wd as i64;
775 let diff = match settings.prefer_dates_from {
776 PreferDatesFrom::Past | PreferDatesFrom::CurrentPeriod => {
777 let mut d = tgt_wd - cur_wd;
778 if d > 0 {
779 d -= 7;
780 }
781 d
782 }
783 PreferDatesFrom::Future => {
784 let mut d = tgt_wd - cur_wd;
785 if d < 0 {
786 d += 7;
787 }
788 d
789 }
790 };
791 let target_date = base.date() + chrono::Duration::days(diff);
792 let nt = time.unwrap_or_else(|| NaiveTime::from_hms_opt(0, 0, 0).unwrap());
793 let mut p = vec!["year", "month", "day"];
794 if has_time {
795 p.push("time");
796 }
797 return Some(AbsoluteMatch {
798 naive: target_date.and_time(nt),
799 period: Period::Day,
800 locale: loc.code.clone(),
801 has_time,
802 parts: p,
803 part_of_day,
804 });
805 }
806
807 let base = settings.effective_base();
808 let (y, m, d, period, parts) =
809 complete_partial_date(year, month, day, has_time, base, settings)?;
810 let nd = NaiveDate::from_ymd_opt(y, m, d)?;
811 let nt = time.unwrap_or_else(|| NaiveTime::from_hms_opt(0, 0, 0).unwrap());
812
813 Some(AbsoluteMatch {
814 naive: nd.and_time(nt),
815 period,
816 locale: loc.code.clone(),
817 has_time,
818 parts,
819 part_of_day,
820 })
821}
822
823fn complete_partial_date(
824 year: Option<i32>,
825 month: Option<u32>,
826 day: Option<u32>,
827 has_time: bool,
828 base: NaiveDateTime,
829 settings: &Settings,
830) -> Option<(i32, u32, u32, Period, Vec<&'static str>)> {
831 if settings.strict_parsing && (year.is_none() || month.is_none() || day.is_none()) {
832 return None;
833 }
834 if settings.require_parts.contains(&DatePart::Year) && year.is_none() {
835 return None;
836 }
837 if settings.require_parts.contains(&DatePart::Month) && month.is_none() {
838 return None;
839 }
840 if settings.require_parts.contains(&DatePart::Day) && day.is_none() {
841 return None;
842 }
843
844 let period = if day.is_some() {
845 Period::Day
846 } else if month.is_some() {
847 Period::Month
848 } else {
849 Period::Year
850 };
851
852 let mut parts = Vec::with_capacity(4);
853 if year.is_some() {
854 parts.push("year");
855 }
856 if month.is_some() {
857 parts.push("month");
858 }
859 if day.is_some() {
860 parts.push("day");
861 }
862 if has_time {
863 parts.push("time");
864 }
865
866 let m = month.unwrap_or_else(|| match settings.prefer_month_of_year {
867 PreferMonthOfYear::First => 1,
868 PreferMonthOfYear::Last => 12,
869 PreferMonthOfYear::Current => base.month(),
870 });
871 if !(1..=12).contains(&m) {
872 return None;
873 }
874
875 let mut y = year.unwrap_or_else(|| base.year());
876 let d = day.unwrap_or_else(|| resolve_missing_day(y, m, base.day(), settings.prefer_day_of_month));
877 if d < 1 || d > days_in_month(y, m) {
878 return None;
879 }
880
881 if year.is_none() {
882 if let Some(cand) = NaiveDate::from_ymd_opt(y, m, d) {
883 match settings.prefer_dates_from {
884 PreferDatesFrom::Past if cand > base.date() => y -= 1,
885 PreferDatesFrom::Future if cand < base.date() => y += 1,
886 _ => {}
887 }
888 }
889 }
890
891 let final_d = d.min(days_in_month(y, m));
892 Some((y, m, final_d, period, parts))
893}
894
895fn split_date_tokens<'a>(s: &'a str, loc: &CompiledLocale, normalize: bool) -> Vec<&'a str> {
896 let mut out = Vec::with_capacity(8);
897 for chunk in s.split(|c: char| {
898 c.is_whitespace() || c == ',' || c == '/' || c == '[' || c == ']' || c == '–' || c == '—'
899 }) {
900 if chunk.is_empty() {
901 continue;
902 }
903 if chunk.contains('.')
905 && !chunk.contains(':')
906 && !chunk.ends_with("a.m.")
907 && !chunk.ends_with("p.m.")
908 && !(chunk.matches('.').count() == 1
909 && chunk.chars().all(|c| c.is_ascii_digit() || c == '.'))
910 {
911 let clean = chunk.trim_matches('.');
912 if lookup_month(clean, loc, normalize).is_some()
913 || lookup_weekday(clean, loc, normalize).is_some()
914 {
915 out.push(clean);
916 continue;
917 }
918 for sub in chunk.split('.') {
919 if !sub.is_empty() {
920 push_splitting_attached_digits(sub, loc, normalize, &mut out);
921 }
922 }
923 continue;
924 }
925 if chunk.contains('-') {
926 let clean = chunk.trim_matches('.');
927 if lookup_month(clean, loc, normalize).is_some()
928 || lookup_weekday(clean, loc, normalize).is_some()
929 || loc.months.keys().any(|k| k.split_whitespace().any(|w| w == clean))
930 {
931 out.push(chunk);
932 continue;
933 }
934 for sub in chunk.split('-') {
935 if !sub.is_empty() {
936 push_splitting_attached_digits(sub, loc, normalize, &mut out);
937 }
938 }
939 } else {
940 push_splitting_attached_digits(chunk, loc, normalize, &mut out);
941 }
942 }
943 out
944}
945
946#[inline]
947fn is_locale_connector(lang: &str, clean: &str) -> bool {
948 match lang {
949 "it" => matches!(clean, "il" | "alle" | "ore" | "nel" | "della" | "all" | "di" | "lo"),
950 "es" => matches!(clean, "a" | "las" | "al" | "horas"),
951 "pt" => matches!(clean, "às" | "as" | "em" | "no" | "na" | "dia" | "horas"),
952 "fr" => matches!(clean, "au" | "du" | "les" | "heures" | "vers"),
953 "nl" => matches!(clean, "op" | "om" | "uur"),
954 "pl" => matches!(clean, "dnia" | "o" | "godz" | "roku" | "r"),
955 "sv" | "nb" | "da" | "nn" => matches!(clean, "kl" | "klockan" | "klokken"),
956 "ro" => matches!(clean, "la" | "ora" | "orele" | "în" | "in" | "pe" | "din"),
957 "sk" => matches!(clean, "o" | "v" | "vo" | "dňa" | "dna" | "hod"),
958 "cs" => matches!(clean, "v" | "ve" | "hod" | "dne"),
959 "hr" | "bs" | "sr" | "sr-Latn" | "sl" => matches!(clean, "u" | "ob" | "sati" | "dana"),
960 "et" => matches!(clean, "kell" | "kl"),
961 "lt" => matches!(clean, "m" | "d" | "val"),
962 "lv" => matches!(clean, "gada" | "g" | "plkst"),
963 "uk" => matches!(clean, "р" | "о" | "об" | "року"),
964 "bg" => matches!(clean, "г" | "в" | "ч" | "часа"),
965 "el" => matches!(clean, "στις" | "την" | "τον"),
966 "id" | "ms" => matches!(clean, "pukul" | "jam" | "pada"),
967 "vi" => matches!(clean, "ngày" | "ngay" | "lúc" | "luc" | "vào" | "vao"),
968 "ar" => matches!(clean, "الساعة" | "ساعة" | "في" | "يوم" | "بتاريخ"),
969 _ => false,
970 }
971}
972
973fn push_splitting_attached_digits<'a>(
974 tok: &'a str,
975 loc: &CompiledLocale,
976 normalize: bool,
977 out: &mut Vec<&'a str>,
978) {
979 if let Some(rest) = tok
981 .strip_prefix('\'')
982 .or_else(|| tok.strip_prefix('\u{2019}'))
983 .or_else(|| tok.strip_prefix('\u{2018}'))
984 {
985 if rest.len() == 2 && rest.bytes().all(|b| b.is_ascii_digit()) {
986 out.push(tok);
987 return;
988 }
989 }
990 if tok.contains(':')
991 || tok.ends_with("am")
992 || tok.ends_with("pm")
993 || tok.ends_with("a.m.")
994 || tok.ends_with("p.m.")
995 || tok.bytes().all(|b| b.is_ascii_digit())
996 || parse_date_number_or_ordinal(tok).is_some()
997 || lookup_month(tok, loc, normalize).is_some()
998 || lookup_weekday(tok, loc, normalize).is_some()
999 {
1000 out.push(tok);
1001 return;
1002 }
1003 let has_digit = tok.chars().any(|c| c.is_ascii_digit());
1005 let has_alpha = tok.chars().any(|c| c.is_alphabetic());
1006 if !has_digit || !has_alpha {
1007 out.push(tok);
1008 return;
1009 }
1010 if tok.contains('h') && tok.chars().all(|c| c.is_ascii_digit() || c == 'h' || c == 'm' || c == 's') {
1012 out.push(tok);
1013 return;
1014 }
1015 let mut start = 0usize;
1016 let mut prev_digit = tok.chars().next().unwrap().is_ascii_digit();
1017 for (idx, ch) in tok.char_indices().skip(1) {
1018 let cur_digit = ch.is_ascii_digit();
1019 if cur_digit != prev_digit {
1020 out.push(&tok[start..idx]);
1021 start = idx;
1022 prev_digit = cur_digit;
1023 }
1024 }
1025 if start < tok.len() {
1026 out.push(&tok[start..]);
1027 }
1028}
1029
1030fn parse_date_number_or_ordinal(s: &str) -> Option<(u32, usize)> {
1031 if s.is_empty() || s.len() > 6 {
1032 return None;
1033 }
1034 let stripped = s
1035 .strip_suffix("st")
1036 .or_else(|| s.strip_suffix("nd"))
1037 .or_else(|| s.strip_suffix("rd"))
1038 .or_else(|| s.strip_suffix("th"))
1039 .or_else(|| s.strip_suffix("er"))
1040 .or_else(|| s.strip_suffix('º'))
1041 .or_else(|| s.strip_suffix('ª'))
1042 .unwrap_or(s);
1043
1044 if stripped.is_empty() || stripped.len() > 4 || !stripped.bytes().all(|b| b.is_ascii_digit()) {
1045 return None;
1046 }
1047 let val: u32 = stripped.parse().ok()?;
1048 Some((val, stripped.len()))
1049}