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