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 try_parse_absolute_with_raw(normalized, None, candidate_ids, registry, settings)
27}
28
29pub fn try_parse_absolute_with_raw(
31 normalized: &str,
32 raw_input: Option<&str>,
33 candidate_ids: &[usize],
34 registry: &LocaleRegistry,
35 settings: &Settings,
36) -> Option<AbsoluteMatch> {
37 if (normalized.contains('年')
38 || normalized.contains('月')
39 || normalized.contains('日')
40 || normalized.contains('년')
41 || normalized.contains('월')
42 || normalized.contains('일'))
43 && (crate::locale::settings_allows_locale(settings, "zh")
44 || crate::locale::settings_allows_locale(settings, "ja")
45 || crate::locale::settings_allows_locale(settings, "ko"))
46 {
47 if let Some(m) = try_cjk_or_korean_date(normalized, settings) {
48 return Some(m);
49 }
50 }
51
52 if normalized.len() == 4 && normalized.bytes().all(|b| b.is_ascii_digit()) {
53 if !settings.strict_parsing
54 && !settings.require_parts.contains(&DatePart::Month)
55 && !settings.require_parts.contains(&DatePart::Day)
56 {
57 if let Ok(mut year) = normalized.parse::<i32>() {
58 let mut bare_locale = "en";
59 if settings
60 .languages
61 .as_deref()
62 .is_some_and(|ls| ls.iter().any(|l| l.eq_ignore_ascii_case("th")))
63 && (2400..=2700).contains(&year)
64 {
65 year -= 543;
66 bare_locale = "th";
67 }
68 if (1000..=2999).contains(&year) {
69 let base = settings.effective_base();
70 let month = match settings.prefer_month_of_year {
71 PreferMonthOfYear::First => 1,
72 PreferMonthOfYear::Last => 12,
73 PreferMonthOfYear::Current => base.month(),
74 };
75 let day = resolve_missing_day(year, month, base.day(), settings.prefer_day_of_month);
76 if let Some(nd) = NaiveDate::from_ymd_opt(year, month, day) {
77 return Some(AbsoluteMatch {
78 naive: nd.and_hms_opt(0, 0, 0)?,
79 period: Period::Year,
80 locale: bare_locale.to_string(),
81 has_time: false,
82 parts: vec!["year"],
83 part_of_day: None,
84 });
85 }
86 }
87 }
88 }
89 return None;
90 }
91
92 for &lid in candidate_ids {
93 let loc = ®istry.locales[lid];
94 if let Some(m) = try_parse_in_locale(normalized, raw_input, loc, settings) {
95 return Some(m);
96 }
97 }
98
99 None
100}
101
102fn extract_cjk_era_year(s: &str) -> Option<Result<(i32, String, bool), ()>> {
103 const ERAS: [(&str, i32, bool); 7] = [
104 ("令和", 2018, true),
105 ("平成", 1988, true),
106 ("昭和", 1925, true),
107 ("大正", 1911, true),
108 ("明治", 1867, true),
109 ("民國", 1911, false),
110 ("民国", 1911, false),
111 ];
112 for &(era, base, is_jp) in &ERAS {
113 if let Some(pos) = s.find(era) {
114 let after_era = &s[pos + era.len()..];
115 let trimmed = after_era.trim_start();
116 let ws_skipped = after_era.len() - trimmed.len();
117 let mut cursor = pos + era.len() + ws_skipped;
118
119 let era_num: i32 = if let Some(rest) = trimmed.strip_prefix('元') {
120 let rest_trim = rest.trim_start();
121 let nen_ws = rest.len() - rest_trim.len();
122 if !rest_trim.starts_with('年') {
123 return Some(Err(()));
124 }
125 cursor += '元'.len_utf8() + nen_ws + '年'.len_utf8();
126 1
127 } else {
128 let mut d_end = 0usize;
129 for (i, ch) in trimmed.char_indices() {
130 if ch.is_ascii_digit() {
131 d_end = i + 1;
132 } else {
133 break;
134 }
135 }
136 let max_digits = if is_jp { 2 } else { 3 };
137 let max_val = if is_jp { 99 } else { 999 };
138 if d_end == 0 || d_end > max_digits {
139 return Some(Err(()));
140 }
141 let val: i32 = match trimmed[..d_end].parse() {
142 Ok(v) if (1..=max_val).contains(&v) => v,
143 _ => return Some(Err(())),
144 };
145 let after_digits = &trimmed[d_end..];
146 let rest_trim = after_digits.trim_start();
147 let nen_ws = after_digits.len() - rest_trim.len();
148 if !rest_trim.starts_with('年') {
149 return Some(Err(()));
150 }
151 cursor += d_end + nen_ws + '年'.len_utf8();
152 val
153 };
154
155 let mut rem = String::with_capacity(s.len());
156 rem.push_str(&s[..pos]);
157 rem.push_str(&s[cursor..]);
158 return Some(Ok((base + era_num, rem, is_jp)));
159 }
160 }
161 None
162}
163
164fn try_cjk_or_korean_date(s: &str, settings: &Settings) -> Option<AbsoluteMatch> {
165 if s.contains("四半期") || s.contains("季度") || s.contains("분기") || s.contains('、') {
166 return None;
167 }
168 let rel_check = s
169 .replace("午前", "")
170 .replace("午後", "")
171 .replace("오전", "")
172 .replace("오후", "");
173 if rel_check.contains(['前', '後', '后', '전', '후']) {
174 return None;
175 }
176 let mut year: Option<i32> = None;
177 let mut month: Option<u32> = None;
178 let mut day: Option<u32> = None;
179 let mut hour: u32 = 0;
180 let mut minute: u32 = 0;
181 let mut second: u32 = 0;
182 let mut has_time = false;
183 let mut is_japanese = false;
184 let owned_rem;
185 let scan_s: &str = match extract_cjk_era_year(s) {
186 Some(Ok((gy, rem, era_is_jp))) => {
187 year = Some(gy);
188 is_japanese = era_is_jp;
189 owned_rem = rem;
190 &owned_rem
191 }
192 Some(Err(())) => return None,
193 None => s,
194 };
195
196 let is_korean =
197 scan_s.contains('년') || scan_s.contains('월') || scan_s.contains('일') || scan_s.contains('시');
198 let is_pm = scan_s.contains("오후")
199 || scan_s.contains("pm")
200 || scan_s.contains("下午")
201 || scan_s.contains("午後")
202 || scan_s.contains("晚上");
203 let is_am = scan_s.contains("오전")
204 || scan_s.contains("am")
205 || scan_s.contains("上午")
206 || scan_s.contains("午前")
207 || scan_s.contains("早上");
208
209 let mut loose_nums: Vec<(u32, usize)> = Vec::new();
210 let mut cur_num = String::new();
211 let chars: Vec<(usize, char)> = scan_s.char_indices().collect();
212 let mut idx = 0usize;
213
214 while idx < chars.len() {
215 let (byte_idx, ch) = chars[idx];
216 if ch.is_ascii_digit() {
217 cur_num.push(ch);
218 idx += 1;
219 continue;
220 }
221 if ch.is_whitespace() {
222 let mut la = idx + 1;
224 while la < chars.len() && chars[la].1.is_whitespace() {
225 la += 1;
226 }
227 if la < chars.len()
228 && matches!(
229 chars[la].1,
230 '年' | '년' | '月' | '월' | '日' | '号' | '일' | '時' | '时' | '点' | '點' | '시' | '分' | '분' | '秒' | '초'
231 )
232 {
233 idx += 1;
234 continue;
235 }
236 }
237 if !cur_num.is_empty() {
238 let val: u32 = cur_num.parse().ok()?;
239 let len = cur_num.len();
240 cur_num.clear();
241 match ch {
242 '年' | '년' => {
243 if year.is_some() {
244 return None;
245 }
246 year = Some(if len <= 2 {
247 expand_two_digit_year(val)
248 } else {
249 val as i32
250 });
251 }
252 '月' | '월' => {
253 if month.is_some() {
254 return None;
255 }
256 month = Some(val);
257 }
258 '日' | '号' | '일' => {
259 if day.is_some() {
260 return None;
261 }
262 day = Some(val);
263 }
264 '時' | '时' | '点' | '點' | '시' => {
265 hour = val;
266 has_time = true;
267 }
268 '分' | '분' => {
269 minute = val;
270 has_time = true;
271 }
272 '秒' | '초' => {
273 second = val;
274 has_time = true;
275 }
276 ':' => {
277 if len == 4 && day.is_none() && scan_s.len() - byte_idx <= 32 {
279 let d_cand = val / 100;
280 let h_cand = val % 100;
281 if (1..=31).contains(&d_cand) && h_cand <= 23 {
282 day = Some(d_cand);
283 if let Some(t) = parse_time_str(&format!("{}{}", h_cand, &scan_s[byte_idx..])) {
284 hour = t.hour();
285 minute = t.minute();
286 second = t.second();
287 has_time = true;
288 break;
289 }
290 }
291 }
292 let start = scan_s[..byte_idx]
293 .char_indices()
294 .rev()
295 .find(|&(_, c)| !c.is_ascii_digit())
296 .map(|(p, c)| p + c.len_utf8())
297 .unwrap_or(0);
298 if scan_s.len() - start <= 32 {
299 if let Some(t) = parse_time_str(scan_s[start..].trim()) {
300 hour = t.hour();
301 minute = t.minute();
302 second = t.second();
303 has_time = true;
304 break;
305 }
306 }
307 }
308 _ => loose_nums.push((val, len)),
309 }
310 } else if ch == ':' {
311 return None;
312 }
313 idx += 1;
314 }
315
316 if !cur_num.is_empty() {
317 let len = cur_num.len();
318 if let Ok(val) = cur_num.parse::<u32>() {
319 loose_nums.push((val, len));
320 }
321 }
322
323 for (val, len) in loose_nums {
324 if year.is_none() && len == 4 && (1000..=2999).contains(&val) {
325 year = Some(val as i32);
326 } else if day.is_none() && (1..=31).contains(&val) && len <= 2 {
327 day = Some(val);
328 }
329 }
330
331 if year.is_none() && month.is_none() {
332 return None;
333 }
334
335 let mut part_of_day: Option<PartOfDay> = None;
336 let mut tod_time: Option<NaiveTime> = None;
337 if has_time {
338 if is_pm && (1..12).contains(&hour) {
339 hour += 12;
340 } else if is_am && hour == 12 {
341 hour = 0;
342 }
343 } else {
344 let tod_hour: Option<u8> = [
345 ("真夜中", 0u8),
346 ("午夜", 0),
347 ("자정", 0),
348 ("早上", 9),
349 ("上午", 9),
350 ("아침", 9),
351 ("오전", 9),
352 ("朝", 9),
353 ("正午", 12),
354 ("中午", 12),
355 ("정오", 12),
356 ("午後", 15),
357 ("下午", 15),
358 ("오후", 15),
359 ("夕方", 18),
360 ("傍晚", 18),
361 ("저녁", 18),
362 ("晚上", 20),
363 ("夜", 20),
364 ("밤", 20),
365 ]
366 .into_iter()
367 .find(|(tok, _)| scan_s.contains(tok))
368 .map(|(_, h)| h);
369
370 if let Some(h) = tod_hour {
371 has_time = true;
372 part_of_day = PartOfDay::from_hour(h);
373 if h == 0 || h == 12 {
374 tod_time = NaiveTime::from_hms_opt(h as u32, 0, 0);
375 } else if let Some(p) = part_of_day {
376 tod_time = Some(settings.parts_of_day.time_for(p));
377 }
378 }
379 }
380
381 let base = settings.effective_base();
382 let (y, m, d, period, parts) = complete_partial_date(year, month, day, has_time, base, settings)?;
383 let nd = NaiveDate::from_ymd_opt(y, m, d)?;
384 let nt = tod_time.or_else(|| NaiveTime::from_hms_opt(hour, minute, second))?;
385 let lang = if is_korean {
386 "ko"
387 } else if is_japanese
388 || scan_s.contains('時')
389 || scan_s.contains('朝')
390 || scan_s.contains('夜')
391 || scan_s.contains("夕方")
392 || scan_s.contains("正午")
393 || scan_s.contains("真夜中")
394 || settings
395 .languages
396 .as_deref()
397 .map(|ls| {
398 ls.iter().any(|l| l.eq_ignore_ascii_case("ja"))
399 && !ls.iter().any(|l| l.to_ascii_lowercase().starts_with("zh"))
400 })
401 .unwrap_or(false)
402 {
403 "ja"
404 } else {
405 "zh"
406 };
407
408 Some(AbsoluteMatch {
409 naive: nd.and_time(nt),
410 period,
411 locale: lang.to_string(),
412 has_time,
413 parts,
414 part_of_day,
415 })
416}
417
418fn lookup_month(s: &str, loc: &CompiledLocale, normalize: bool) -> Option<u8> {
419 if let Some(&m) = loc.months.get(s) {
420 return Some(m);
421 }
422 if normalize {
423 let f = fold_diacritics(s);
424 if let Some(&m) = loc.folded_months.get(f.as_ref()) {
425 return Some(m);
426 }
427 }
428 None
429}
430
431fn lookup_weekday(s: &str, loc: &CompiledLocale, normalize: bool) -> Option<u8> {
432 if let Some(&w) = loc.weekdays.get(s) {
433 return Some(w);
434 }
435 if normalize {
436 let f = fold_diacritics(s);
437 if let Some(&w) = loc.folded_weekdays.get(f.as_ref()) {
438 return Some(w);
439 }
440 }
441 None
442}
443
444fn lookup_tod_hour(s: &str, loc: &CompiledLocale, normalize: bool) -> Option<u8> {
445 if let Some(&h) = loc.time_of_day.get(s) {
446 return Some(h);
447 }
448 if normalize {
449 let f = fold_diacritics(s);
450 if let Some(&h) = loc
451 .folded_time_of_day
452 .get(f.as_ref())
453 .or_else(|| loc.time_of_day.get(f.as_ref()))
454 {
455 return Some(h);
456 }
457 }
458 None
459}
460
461fn tod_hour_to_time_and_pod(hour: u8, settings: &Settings) -> (NaiveTime, Option<PartOfDay>) {
462 match hour {
463 3 | 6 => (settings.parts_of_day.time_for(PartOfDay::EarlyMorning), Some(PartOfDay::EarlyMorning)),
464 9 => (settings.parts_of_day.time_for(PartOfDay::Morning), Some(PartOfDay::Morning)),
465 15 => (settings.parts_of_day.time_for(PartOfDay::Afternoon), Some(PartOfDay::Afternoon)),
466 18 => (settings.parts_of_day.time_for(PartOfDay::Evening), Some(PartOfDay::Evening)),
467 20 => (settings.parts_of_day.time_for(PartOfDay::Night), Some(PartOfDay::Night)),
468 12 => (NaiveTime::from_hms_opt(12, 0, 0).unwrap(), None),
469 0 => (NaiveTime::from_hms_opt(0, 0, 0).unwrap(), None),
470 h => (NaiveTime::from_hms_opt(h as u32, 0, 0).unwrap(), None),
471 }
472}
473
474fn raw_has_uppercase_roman(raw_input: Option<&str>, clean_lower: &str) -> Option<u32> {
475 let raw = raw_input?;
476 if !clean_lower
477 .bytes()
478 .all(|b| matches!(b, b'i' | b'v' | b'x' | b'l' | b'c' | b'd' | b'm'))
479 {
480 return None;
481 }
482 for tok in raw.split(|c: char| !c.is_ascii_alphanumeric()) {
483 if tok.eq_ignore_ascii_case(clean_lower) && tok.bytes().all(|b| b.is_ascii_uppercase()) {
484 if let Some(v) = crate::numerals::parse_roman_numeral(tok) {
485 return Some(v);
486 }
487 }
488 }
489 None
490}
491
492fn try_parse_in_locale(
493 normalized: &str,
494 raw_input: Option<&str>,
495 loc: &CompiledLocale,
496 settings: &Settings,
497) -> Option<AbsoluteMatch> {
498 let raw_tokens = split_date_tokens(normalized, loc, settings.normalize);
499 if raw_tokens.is_empty() || raw_tokens.len() > 18 {
500 return None;
501 }
502
503 let mut year: Option<i32> = None;
504 let mut year_expanded_from_two = false;
505 let mut year_pos: Option<usize> = None;
506 let mut month: Option<u32> = None;
507 let mut month_pos: Option<usize> = None;
508 let mut month_token_len: usize = 0;
509 let mut month_token_ascii: bool = false;
510 let mut day: Option<u32> = None;
511 let mut day_pos: Option<usize> = None;
512 let mut weekday_seen: Option<u8> = None;
513 let mut ambiguous_ord_wd: Option<(u32, u8, usize)> = None;
514 let mut time: Option<NaiveTime> = None;
515 let mut part_of_day: Option<PartOfDay> = None;
516 let mut ampm: Option<bool> = None;
517 let mut free_nums: Vec<(u32, usize, usize)> = Vec::new();
518 let mut roman_cands: Vec<(u32, usize)> = Vec::new();
519 let mut matched_locale_signal = false;
520 let mut is_thai_be = false;
521 let mut ambiguous_month_weekday: Option<u8> = None;
522
523 let mut i = 0;
524 while i < raw_tokens.len() {
525 let tok = raw_tokens[i];
526 let clean = tok.trim_matches(|c: char| matches!(c, ',' | '.' | '(' | ')' | '[' | ']'));
527 if clean.is_empty() {
528 i += 1;
529 continue;
530 }
531
532 if settings
533 .skip_tokens
534 .iter()
535 .any(|st| st.eq_ignore_ascii_case(clean))
536 {
537 i += 1;
538 continue;
539 }
540
541 if year.is_none() && time.is_none() && clean.len() >= 12 {
543 if let Some((y_part, t_part)) = clean.split_once(':') {
544 if y_part.len() == 4 && y_part.bytes().all(|b| b.is_ascii_digit()) {
545 if let (Ok(y_val), Some(t_val)) = (y_part.parse::<i32>(), parse_time_str(t_part)) {
546 if (1..=9999).contains(&y_val) {
547 year = Some(y_val);
548 year_pos = Some(i);
549 time = Some(t_val);
550 i += 1;
551 continue;
552 }
553 }
554 }
555 }
556 }
557
558 if time.is_none()
560 && (clean.contains(':')
561 || (clean.len() >= 4
562 && clean.contains('.')
563 && clean.as_bytes()[0].is_ascii_digit()
564 && clean.matches('.').count() == 1)
565 || (clean.len() >= 3
566 && clean.as_bytes()[0].is_ascii_digit()
567 && (clean.contains('h')
568 || clean.ends_with("am")
569 || clean.ends_with("pm")
570 || clean.ends_with("a.m")
571 || clean.ends_with("p.m")
572 || tok.ends_with("a.m.")
573 || tok.ends_with("p.m."))))
574 {
575 let time_cand = if tok.ends_with("a.m.") || tok.ends_with("p.m.") {
576 tok.trim_matches(',')
577 } else {
578 clean
579 };
580 if i + 1 < raw_tokens.len() {
581 let next_clean = raw_tokens[i + 1].trim_matches(|c: char| c == '.' || c == ',');
582 if next_clean == "am"
583 || next_clean == "pm"
584 || next_clean == "a.m"
585 || next_clean == "p.m"
586 || next_clean == "ip"
587 || next_clean == "ap"
588 || next_clean == "uhr"
589 || loc.am.contains(next_clean)
590 || loc.pm.contains(next_clean)
591 || (settings.normalize
592 && (loc.folded_am.contains(next_clean)
593 || loc.folded_pm.contains(next_clean)))
594 {
595 let combined = format!("{} {}", time_cand, raw_tokens[i + 1].trim_matches(','));
596 if let Some(t) = parse_time_str(&combined) {
597 time = Some(t);
598 i += 2;
599 continue;
600 }
601 }
602 }
603 if let Some(t) = parse_time_str(time_cand) {
604 time = Some(t);
605 i += 1;
606 continue;
607 }
608 }
609
610 if month.is_none() || (weekday_seen.is_none() && ambiguous_month_weekday.is_some()) {
613 let mut matched_span = 0usize;
614 for span in (1..=5).rev() {
615 if i + span <= raw_tokens.len() {
616 let cand = if span == 1 {
617 clean.to_string()
618 } else {
619 let mut s = String::from(clean);
620 for k in 1..span {
621 s.push(' ');
622 s.push_str(raw_tokens[i + k].trim_matches(','));
623 }
624 s
625 };
626 if let Some(m) = lookup_month(&cand, loc, settings.normalize) {
627 if month.is_none() {
628 ambiguous_month_weekday = if weekday_seen.is_none() {
629 lookup_weekday(&cand, loc, settings.normalize)
630 } else {
631 None
632 };
633 } else if lookup_weekday(&cand, loc, settings.normalize).is_some() {
634 continue;
635 } else if let Some(prev_wd) = ambiguous_month_weekday.take() {
636 weekday_seen = Some(prev_wd);
637 }
638 month = Some(m as u32);
639 month_pos = Some(i);
640 month_token_len = cand.chars().count();
641 month_token_ascii = cand.is_ascii();
642 matched_locale_signal = true;
643 matched_span = span;
644 break;
645 }
646 }
647 }
648 if matched_span > 0 {
649 i += matched_span;
650 continue;
651 }
652 }
653
654 if clean == "pm"
656 || clean == "p.m"
657 || loc.pm.contains(clean)
658 || (settings.normalize && loc.folded_pm.contains(clean))
659 {
660 ampm = Some(true);
661 i += 1;
662 continue;
663 }
664 let is_germanic_prep_am = clean == "am"
665 && matches!(loc.code.as_str(), "de" | "gsw" | "lb" | "ksh" | "nds");
666 if !is_germanic_prep_am
667 && (clean == "am"
668 || clean == "a.m"
669 || loc.am.contains(clean)
670 || (settings.normalize && loc.folded_am.contains(clean)))
671 {
672 ampm = Some(false);
673 i += 1;
674 continue;
675 }
676
677 if weekday_seen.is_none() {
679 let mut matched_span = 0usize;
680 for span in (1..=4).rev() {
681 if i + span <= raw_tokens.len() {
682 let cand = if span == 1 {
683 clean.to_string()
684 } else {
685 let mut s = String::from(clean);
686 for k in 1..span {
687 s.push(' ');
688 s.push_str(raw_tokens[i + k].trim_matches(','));
689 }
690 s
691 };
692 if let Some(wd) = lookup_weekday(&cand, loc, settings.normalize) {
693 if span == 1 && day.is_none() {
694 if let Some(ord) = crate::numerals::lookup_ordinal(clean, loc, settings.normalize) {
695 if (1..=31).contains(&ord) {
696 ambiguous_ord_wd = Some((ord, wd, i));
697 }
698 }
699 }
700 weekday_seen = Some(wd);
701 matched_locale_signal = true;
702 matched_span = span;
703 break;
704 }
705 }
706 }
707 if matched_span > 0 {
708 i += matched_span;
709 continue;
710 }
711 }
712
713 if time.is_none() {
715 if i + 1 < raw_tokens.len() {
716 let bigram = format!("{} {}", clean, raw_tokens[i + 1].trim_matches(','));
717 if let Some(h) = lookup_tod_hour(&bigram, loc, settings.normalize) {
718 let (t, pod) = tod_hour_to_time_and_pod(h, settings);
719 time = Some(t);
720 part_of_day = pod;
721 i += 2;
722 continue;
723 }
724 }
725 if let Some(h) = lookup_tod_hour(clean, loc, settings.normalize) {
726 let (t, pod) = tod_hour_to_time_and_pod(h, settings);
727 time = Some(t);
728 part_of_day = pod;
729 i += 1;
730 continue;
731 }
732 }
733
734 if year.is_none() {
736 if let Some(rest) = clean
737 .strip_prefix('\'')
738 .or_else(|| clean.strip_prefix('\u{2019}'))
739 .or_else(|| clean.strip_prefix('\u{2018}'))
740 {
741 if rest.len() == 2 && rest.bytes().all(|b| b.is_ascii_digit()) {
742 if let Ok(y2) = rest.parse::<u32>() {
743 year = Some(expand_two_digit_year(y2));
744 year_pos = Some(i);
745 year_expanded_from_two = true;
746 i += 1;
747 continue;
748 }
749 }
750 }
751 }
752
753 if day.is_none() {
755 if let Some(ord) = crate::numerals::lookup_ordinal(clean, loc, settings.normalize) {
756 if (1..=31).contains(&ord) {
757 day = Some(ord);
758 day_pos = Some(i);
759 matched_locale_signal = true;
760 i += 1;
761 continue;
762 }
763 }
764 }
765
766 if let Some((num, digit_len)) = parse_date_number_or_ordinal(clean) {
768 if digit_len == 4 && (1..=9999).contains(&num) && year.is_none() {
769 year = Some(num as i32);
770 year_pos = Some(i);
771 } else {
772 free_nums.push((num, digit_len, i));
773 }
774 i += 1;
775 continue;
776 }
777
778 if raw_tokens.len() >= 2 {
780 if let Some(rv) = raw_has_uppercase_roman(raw_input, clean) {
781 roman_cands.push((rv, i));
782 i += 1;
783 continue;
784 }
785 }
786
787 if loc.code == "th" && matches!(clean, "พ.ศ" | "พศ") {
789 is_thai_be = true;
790 matched_locale_signal = true;
791 i += 1;
792 continue;
793 }
794 if loc.skip.contains(clean)
795 || loc.units.contains_key(clean)
796 || is_locale_connector(loc.code.as_str(), clean)
797 || matches!(
798 clean,
799 "at" | "on" | "of" | "the" | "in" | "de" | "del" | "el" | "la" | "le" | "à"
800 | "am" | "um" | "den" | "saat" | "tarih" | "tarihinde" | "в" | "г" | "года"
801 | "год" | "günü" | "gunu" | "yılında" | "yilinda" | "yılı" | "year" | "klo"
802 | "u" | "у" | "سنة" | "år"
803 )
804 {
805 i += 1;
806 continue;
807 }
808
809 return None;
810 }
811
812 if let Some((ord, _wd, pos)) = ambiguous_ord_wd {
813 if month.is_some() && day.is_none() && free_nums.is_empty() {
814 day = Some(ord);
815 day_pos = Some(pos);
816 weekday_seen = None;
817 }
818 }
819
820 if !roman_cands.is_empty() {
821 if settings.languages.is_none() && !crate::locale::is_major_auto_locale(&loc.code) {
822 return None;
823 }
824 if month.is_none()
827 && roman_cands.len()
828 + free_nums.len()
829 + usize::from(day.is_some())
830 + usize::from(year.is_some())
831 < 3
832 {
833 return None;
834 }
835 let mut used_roman_month = false;
836 let min_roman_year = if settings.languages.is_none() { 1400 } else { 100 };
837 for &(rv, rpos) in &roman_cands {
839 if year.is_none() && (min_roman_year..=3999).contains(&rv) {
840 year = Some(rv as i32);
841 year_pos = Some(rpos);
842 }
843 }
844 if settings.languages.is_none() && year.is_none() {
845 return None;
846 }
847 for &(rv, rpos) in &roman_cands {
849 if year_pos == Some(rpos) {
850 continue;
851 }
852 if month.is_none()
853 && (1..=12).contains(&rv)
854 && (year.is_some() || day.is_some() || !free_nums.is_empty())
855 {
856 month = Some(rv);
857 month_pos = Some(rpos);
858 matched_locale_signal = true;
859 used_roman_month = true;
860 break;
861 }
862 }
863 for &(rv, rpos) in &roman_cands {
865 if year_pos == Some(rpos) || (used_roman_month && month_pos == Some(rpos)) {
866 continue;
867 }
868 if day.is_none() && (1..=31).contains(&rv) {
869 free_nums.push((rv, 2, rpos));
870 } else {
871 return None;
872 }
873 }
874 }
875
876 if !matched_locale_signal && year.is_none() {
877 return None;
878 }
879
880 if ampm.is_some() && time.is_none() {
881 return None;
882 }
883
884 if loc.code == "th" {
885 if let Some(y) = year {
886 if (is_thai_be && y > 543) || (2400..=2700).contains(&y) {
887 year = Some(y - 543);
888 }
889 }
890 }
891
892 let has_time = time.is_some();
893 if let (Some(t), Some(is_pm)) = (time, ampm) {
894 let mut h = t.hour();
895 if h == 0 || h > 12 {
896 return None;
897 }
898 if is_pm && h < 12 {
899 h += 12;
900 } else if !is_pm && h == 12 {
901 h = 0;
902 }
903 time = NaiveTime::from_hms_nano_opt(h, t.minute(), t.second(), t.nanosecond());
904 }
905
906 let year_first = year.is_some()
907 && raw_tokens
908 .first()
909 .and_then(|t| parse_date_number_or_ordinal(t))
910 .map(|(n, l)| l == 4 && n as i32 == year.unwrap())
911 .unwrap_or(false);
912
913 let order = if settings.date_order.is_some() || settings.region.is_some() {
914 settings.effective_date_order(loc.date_order)
915 } else if year_first {
916 DateOrder::YMD
917 } else if settings.prefer_locale_date_order {
918 loc.date_order
919 } else {
920 DateOrder::MDY
921 };
922
923 match free_nums.as_slice() {
924 [] => {}
925 [(n, len, pos)] => {
926 if month.is_some() && day.is_none() && (1..=31).contains(n) && *len <= 2 {
927 day = Some(*n);
928 day_pos = Some(*pos);
929 } else if year.is_none() && *len == 2 && weekday_seen.is_none() {
930 year = Some(expand_two_digit_year(*n));
931 year_pos = Some(*pos);
932 year_expanded_from_two = true;
933 } else {
934 return None;
935 }
936 }
937 [(n1, l1, p1), (n2, l2, p2)] => {
938 if month.is_some() && day.is_none() && year.is_none() {
939 if (1..=31).contains(n1) && *l1 <= 2 && *l2 == 2 {
940 day = Some(*n1);
941 day_pos = Some(*p1);
942 year = Some(expand_two_digit_year(*n2));
943 year_pos = Some(*p2);
944 year_expanded_from_two = true;
945 } else if (1..=31).contains(n2) && *l2 <= 2 && *l1 == 2 {
946 year = Some(expand_two_digit_year(*n1));
947 year_pos = Some(*p1);
948 year_expanded_from_two = true;
949 day = Some(*n2);
950 day_pos = Some(*p2);
951 } else if (1..=31).contains(n1) && (1..=31).contains(n2) && n1 <= n2 {
952 day = Some(*n1);
954 day_pos = Some(*p1);
955 } else {
956 return None;
957 }
958 } else if month.is_some()
959 && year.is_some()
960 && day.is_none()
961 && (1..=31).contains(n1)
962 && (1..=31).contains(n2)
963 && n1 <= n2
964 {
965 day = Some(*n1);
967 day_pos = Some(*p1);
968 } else if month.is_none() && day.is_none() && weekday_seen.is_none() {
969 match order {
970 DateOrder::YMD | DateOrder::MDY
971 if (1..=12).contains(n1) && (1..=31).contains(n2) =>
972 {
973 month = Some(*n1);
974 month_pos = Some(*p1);
975 day = Some(*n2);
976 day_pos = Some(*p2);
977 }
978 DateOrder::YMD | DateOrder::MDY
979 if settings.strict_date_order == StrictDateOrder::All =>
980 {
981 return None;
982 }
983 _ if (1..=31).contains(n1) && (1..=12).contains(n2) => {
984 day = Some(*n1);
985 day_pos = Some(*p1);
986 month = Some(*n2);
987 month_pos = Some(*p2);
988 }
989 _ if settings.strict_date_order == StrictDateOrder::All => {
990 return None;
991 }
992 _ if (1..=12).contains(n1) && (1..=31).contains(n2) => {
993 month = Some(*n1);
994 month_pos = Some(*p1);
995 day = Some(*n2);
996 day_pos = Some(*p2);
997 }
998 _ => return None,
999 }
1000 } else {
1001 return None;
1002 }
1003 }
1004 _ => return None,
1005 }
1006
1007 if settings.languages.is_none()
1008 && !crate::locale::is_major_auto_locale(&loc.code)
1009 && time.is_none()
1010 && ((month.is_some()
1011 && month_token_ascii
1012 && month_token_len <= 3
1013 && ((day.is_some() && year.is_none())
1014 || year_expanded_from_two
1015 || (month_token_len <= 2 && day.is_none() && year.is_some())))
1016 || (weekday_seen.is_some() && month.is_none() && day.is_none() && year.is_some()))
1017 {
1018 return None;
1019 }
1020
1021 if settings.strict_date_order == StrictDateOrder::All {
1022 if let (Some(yp), Some(mp), Some(dp)) = (year_pos, month_pos, day_pos) {
1023 let order_ok = match order {
1024 DateOrder::YMD => yp < mp && mp < dp,
1025 DateOrder::YDM => yp < dp && dp < mp,
1026 DateOrder::MDY => mp < dp && dp < yp,
1027 DateOrder::DMY => dp < mp && mp < yp,
1028 DateOrder::MYD => mp < yp && yp < dp,
1029 DateOrder::DYM => dp < yp && yp < mp,
1030 };
1031 if !order_ok {
1032 return None;
1033 }
1034 }
1035 }
1036
1037 if year.is_none() && month.is_none() && day.is_none() {
1038 let wd = weekday_seen?;
1039 if settings.strict_parsing
1040 || settings.require_parts.contains(&DatePart::Year)
1041 || settings.require_parts.contains(&DatePart::Month)
1042 || settings.require_parts.contains(&DatePart::Day)
1043 {
1044 return None;
1045 }
1046 let base = settings.effective_base();
1047 let cur_wd = base.weekday().num_days_from_monday() as i64;
1048 let tgt_wd = wd as i64;
1049 let diff = match settings.prefer_dates_from {
1050 PreferDatesFrom::Past => {
1051 let mut d = tgt_wd - cur_wd;
1052 if d >= 0 {
1053 d -= 7;
1054 }
1055 d
1056 }
1057 PreferDatesFrom::CurrentPeriod => {
1058 let mut d = tgt_wd - cur_wd;
1059 if d > 0 {
1060 d -= 7;
1061 }
1062 d
1063 }
1064 PreferDatesFrom::Future => {
1065 let mut d = tgt_wd - cur_wd;
1066 if d <= 0 {
1067 d += 7;
1068 }
1069 d
1070 }
1071 };
1072 let target_date = base.date() + chrono::Duration::days(diff);
1073 let nt = time.unwrap_or_else(|| NaiveTime::from_hms_opt(0, 0, 0).unwrap());
1074 let mut p = vec!["year", "month", "day"];
1075 if has_time {
1076 p.push("time");
1077 }
1078 return Some(AbsoluteMatch {
1079 naive: target_date.and_time(nt),
1080 period: Period::Day,
1081 locale: loc.code.clone(),
1082 has_time,
1083 parts: p,
1084 part_of_day,
1085 });
1086 }
1087
1088 let base = settings.effective_base();
1089 let (y, m, d, period, parts) =
1090 complete_partial_date(year, month, day, has_time, base, settings)?;
1091 let nd = NaiveDate::from_ymd_opt(y, m, d)?;
1092 let nt = time.unwrap_or_else(|| NaiveTime::from_hms_opt(0, 0, 0).unwrap());
1093
1094 Some(AbsoluteMatch {
1095 naive: nd.and_time(nt),
1096 period,
1097 locale: loc.code.clone(),
1098 has_time,
1099 parts,
1100 part_of_day,
1101 })
1102}
1103
1104fn complete_partial_date(
1105 year: Option<i32>,
1106 month: Option<u32>,
1107 day: Option<u32>,
1108 has_time: bool,
1109 base: NaiveDateTime,
1110 settings: &Settings,
1111) -> Option<(i32, u32, u32, Period, Vec<&'static str>)> {
1112 if settings.strict_parsing && (year.is_none() || month.is_none() || day.is_none()) {
1113 return None;
1114 }
1115 if settings.require_parts.contains(&DatePart::Year) && year.is_none() {
1116 return None;
1117 }
1118 if settings.require_parts.contains(&DatePart::Month) && month.is_none() {
1119 return None;
1120 }
1121 if settings.require_parts.contains(&DatePart::Day) && day.is_none() {
1122 return None;
1123 }
1124
1125 let period = if day.is_some() {
1126 Period::Day
1127 } else if month.is_some() {
1128 Period::Month
1129 } else {
1130 Period::Year
1131 };
1132
1133 let mut parts = Vec::with_capacity(4);
1134 if year.is_some() {
1135 parts.push("year");
1136 }
1137 if month.is_some() {
1138 parts.push("month");
1139 }
1140 if day.is_some() {
1141 parts.push("day");
1142 }
1143 if has_time {
1144 parts.push("time");
1145 }
1146
1147 let m = month.unwrap_or_else(|| match settings.prefer_month_of_year {
1148 PreferMonthOfYear::First => 1,
1149 PreferMonthOfYear::Last => 12,
1150 PreferMonthOfYear::Current => base.month(),
1151 });
1152 if !(1..=12).contains(&m) {
1153 return None;
1154 }
1155
1156 let mut y = year.unwrap_or_else(|| base.year());
1157 let d = day.unwrap_or_else(|| resolve_missing_day(y, m, base.day(), settings.prefer_day_of_month));
1158 if year.is_none() && m == 2 && d == 29 {
1159 match settings.prefer_dates_from {
1160 PreferDatesFrom::Past | PreferDatesFrom::CurrentPeriod => {
1161 while days_in_month(y, 2) < 29
1162 || NaiveDate::from_ymd_opt(y, 2, 29).is_none_or(|nd| nd > base.date())
1163 {
1164 y -= 1;
1165 if y < 1 {
1166 return None;
1167 }
1168 }
1169 }
1170 PreferDatesFrom::Future => {
1171 while days_in_month(y, 2) < 29
1172 || NaiveDate::from_ymd_opt(y, 2, 29).is_none_or(|nd| nd <= base.date())
1173 {
1174 y += 1;
1175 if y > 9999 {
1176 return None;
1177 }
1178 }
1179 }
1180 }
1181 return Some((y, m, d, period, parts));
1182 }
1183
1184 if d < 1 || d > days_in_month(y, m) {
1185 return None;
1186 }
1187
1188 if year.is_none() {
1189 if let Some(cand) = NaiveDate::from_ymd_opt(y, m, d) {
1190 match settings.prefer_dates_from {
1191 PreferDatesFrom::Past if cand > base.date() => y -= 1,
1192 PreferDatesFrom::Future
1193 if cand < base.date() || (day.is_some() && cand == base.date()) =>
1194 {
1195 y += 1;
1196 }
1197 _ => {}
1198 }
1199 }
1200 }
1201
1202 let final_d = d.min(days_in_month(y, m));
1203 Some((y, m, final_d, period, parts))
1204}
1205
1206fn split_date_tokens<'a>(s: &'a str, loc: &CompiledLocale, normalize: bool) -> Vec<&'a str> {
1207 let mut out = Vec::with_capacity(8);
1208 for chunk in s.split(|c: char| {
1209 c.is_whitespace() || c == ',' || c == '/' || c == '[' || c == ']' || c == '–' || c == '—'
1210 }) {
1211 if chunk.is_empty() {
1212 continue;
1213 }
1214 if chunk.contains('.')
1216 && chunk.trim_end_matches('.') != "พ.ศ"
1217 && !chunk.contains(':')
1218 && !chunk.ends_with("a.m.")
1219 && !chunk.ends_with("p.m.")
1220 && !(chunk.matches('.').count() == 1
1221 && chunk.chars().all(|c| c.is_ascii_digit() || c == '.'))
1222 {
1223 let clean = chunk.trim_matches('.');
1224 if lookup_month(clean, loc, normalize).is_some()
1225 || lookup_weekday(clean, loc, normalize).is_some()
1226 {
1227 out.push(clean);
1228 continue;
1229 }
1230 for sub in chunk.split('.') {
1231 if !sub.is_empty() {
1232 push_splitting_attached_digits(sub, loc, normalize, &mut out);
1233 }
1234 }
1235 continue;
1236 }
1237 if chunk.contains('-') {
1238 let clean = chunk.trim_matches('.');
1239 if parse_date_number_or_ordinal(clean).is_some()
1240 || lookup_month(clean, loc, normalize).is_some()
1241 || lookup_weekday(clean, loc, normalize).is_some()
1242 || crate::numerals::lookup_ordinal(clean, loc, normalize).is_some()
1243 || loc.months.keys().any(|k| k.split_whitespace().any(|w| w == clean))
1244 {
1245 out.push(chunk);
1246 continue;
1247 }
1248 for sub in chunk.split('-') {
1249 if !sub.is_empty() {
1250 push_splitting_attached_digits(sub, loc, normalize, &mut out);
1251 }
1252 }
1253 } else {
1254 push_splitting_attached_digits(chunk, loc, normalize, &mut out);
1255 }
1256 }
1257 out
1258}
1259
1260#[inline]
1261fn is_locale_connector(lang: &str, clean: &str) -> bool {
1262 match lang {
1263 "it" => matches!(clean, "il" | "alle" | "ore" | "nel" | "della" | "all" | "di" | "lo"),
1264 "es" => matches!(clean, "a" | "las" | "al" | "horas"),
1265 "pt" => matches!(clean, "às" | "as" | "em" | "no" | "na" | "dia" | "horas"),
1266 "fr" => matches!(clean, "au" | "du" | "les" | "heures" | "vers"),
1267 "nl" => matches!(clean, "op" | "om" | "uur"),
1268 "pl" => matches!(clean, "dnia" | "o" | "godz" | "roku" | "r"),
1269 "sv" | "nb" | "da" | "nn" => matches!(clean, "kl" | "klockan" | "klokken"),
1270 "ro" => matches!(clean, "la" | "ora" | "orele" | "în" | "in" | "pe" | "din"),
1271 "sk" => matches!(clean, "o" | "v" | "vo" | "dňa" | "dna" | "hod"),
1272 "cs" => matches!(clean, "v" | "ve" | "hod" | "dne"),
1273 "hr" | "bs" | "sr" | "sr-Latn" | "sl" => matches!(clean, "u" | "ob" | "sati" | "dana"),
1274 "et" => matches!(clean, "kell" | "kl"),
1275 "lt" => matches!(clean, "m" | "d" | "val"),
1276 "lv" => matches!(clean, "gada" | "g" | "plkst"),
1277 "uk" => matches!(clean, "р" | "о" | "об" | "року"),
1278 "bg" => matches!(clean, "г" | "в" | "ч" | "часа"),
1279 "el" => matches!(clean, "στις" | "την" | "τον"),
1280 "id" | "ms" => matches!(clean, "pukul" | "jam" | "pada"),
1281 "vi" => matches!(clean, "ngày" | "ngay" | "lúc" | "luc" | "vào" | "vao"),
1282 "ar" => matches!(clean, "الساعة" | "ساعة" | "في" | "يوم" | "بتاريخ"),
1283 _ => false,
1284 }
1285}
1286
1287fn push_splitting_attached_digits<'a>(
1288 tok: &'a str,
1289 loc: &CompiledLocale,
1290 normalize: bool,
1291 out: &mut Vec<&'a str>,
1292) {
1293 if let Some(rest) = tok
1295 .strip_prefix('\'')
1296 .or_else(|| tok.strip_prefix('\u{2019}'))
1297 .or_else(|| tok.strip_prefix('\u{2018}'))
1298 {
1299 if rest.len() == 2 && rest.bytes().all(|b| b.is_ascii_digit()) {
1300 out.push(tok);
1301 return;
1302 }
1303 }
1304 if tok.contains(':')
1305 || tok.ends_with("am")
1306 || tok.ends_with("pm")
1307 || tok.ends_with("a.m.")
1308 || tok.ends_with("p.m.")
1309 || tok.bytes().all(|b| b.is_ascii_digit())
1310 || parse_date_number_or_ordinal(tok).is_some()
1311 || lookup_month(tok, loc, normalize).is_some()
1312 || lookup_weekday(tok, loc, normalize).is_some()
1313 {
1314 out.push(tok);
1315 return;
1316 }
1317 let has_digit = tok.chars().any(|c| c.is_ascii_digit());
1319 let has_alpha = tok.chars().any(|c| c.is_alphabetic());
1320 if !has_digit || !has_alpha {
1321 out.push(tok);
1322 return;
1323 }
1324 if tok.contains('h') && tok.chars().all(|c| c.is_ascii_digit() || c == 'h' || c == 'm' || c == 's') {
1326 out.push(tok);
1327 return;
1328 }
1329 let mut start = 0usize;
1330 let mut prev_digit = tok.chars().next().unwrap().is_ascii_digit();
1331 for (idx, ch) in tok.char_indices().skip(1) {
1332 let cur_digit = ch.is_ascii_digit();
1333 if cur_digit != prev_digit {
1334 out.push(&tok[start..idx]);
1335 start = idx;
1336 prev_digit = cur_digit;
1337 }
1338 }
1339 if start < tok.len() {
1340 out.push(&tok[start..]);
1341 }
1342}
1343
1344#[inline]
1345fn parse_date_number_or_ordinal(s: &str) -> Option<(u32, usize)> {
1346 crate::numerals::parse_date_number_or_ordinal(s)
1347}