Skip to main content

dateoxide_core/locale/
mod.rs

1pub mod schema;
2
3use crate::settings::DateOrder;
4use rustc_hash::{FxHashMap, FxHashSet};
5use schema::RawLocale;
6use std::sync::OnceLock;
7
8static EMBEDDED_LOCALES: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/locales.bin"));
9static REGISTRY: OnceLock<LocaleRegistry> = OnceLock::new();
10
11#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
12#[repr(u8)]
13pub enum TimeUnit {
14    Year = 0,
15    Month = 1,
16    Week = 2,
17    Day = 3,
18    Hour = 4,
19    Minute = 5,
20    Second = 6,
21    Decade = 7,
22    Century = 8,
23    Fortnight = 9,
24}
25
26impl TimeUnit {
27    #[inline]
28    pub fn from_u8(v: u8) -> Option<Self> {
29        match v {
30            0 => Some(Self::Year),
31            1 => Some(Self::Month),
32            2 => Some(Self::Week),
33            3 => Some(Self::Day),
34            4 => Some(Self::Hour),
35            5 => Some(Self::Minute),
36            6 => Some(Self::Second),
37            7 => Some(Self::Decade),
38            8 => Some(Self::Century),
39            9 => Some(Self::Fortnight),
40            _ => None,
41        }
42    }
43}
44
45#[derive(Debug, Clone, Copy, PartialEq, Eq)]
46pub struct RelativeSpec {
47    /// -1 for past ("ago"), +1 for future ("in")
48    pub sign: i8,
49    pub amount: i32,
50    pub unit: TimeUnit,
51}
52
53#[derive(Debug, Clone)]
54pub struct RelativeAffix {
55    pub prefix: String,
56    pub suffix: String,
57    pub sign: i8,
58    pub unit: TimeUnit,
59}
60
61#[derive(Debug)]
62pub struct CompiledLocale {
63    pub id: u16,
64    pub code: String,
65    pub date_order: DateOrder,
66    pub months: FxHashMap<String, u8>,
67    pub weekdays: FxHashMap<String, u8>,
68    pub am: FxHashSet<String>,
69    pub pm: FxHashSet<String>,
70    pub units: FxHashMap<String, TimeUnit>,
71    pub ago: FxHashSet<String>,
72    pub in_words: FxHashSet<String>,
73    pub skip: FxHashSet<String>,
74    pub relative_exact: FxHashMap<String, Vec<RelativeSpec>>,
75    pub relative_affix: Vec<RelativeAffix>,
76    pub word_numbers: FxHashMap<String, u32>,
77    pub time_of_day: FxHashMap<String, u8>,
78    // Diacritic-folded secondary tables (populated only where folded != exact)
79    pub folded_months: FxHashMap<String, u8>,
80    pub folded_weekdays: FxHashMap<String, u8>,
81    pub folded_units: FxHashMap<String, TimeUnit>,
82    pub folded_ago: FxHashSet<String>,
83    pub folded_in_words: FxHashSet<String>,
84    pub folded_relative_exact: FxHashMap<String, Vec<RelativeSpec>>,
85    pub folded_relative_affix: Vec<RelativeAffix>,
86    pub folded_time_of_day: FxHashMap<String, u8>,
87}
88
89pub struct LocaleRegistry {
90    pub locales: Vec<CompiledLocale>,
91    pub code_to_id: FxHashMap<String, usize>,
92    /// Global inverted index: lowercase token -> priority-ordered list of locale IDs.
93    pub token_to_langs: FxHashMap<String, Vec<u16>>,
94    /// Folded inverted index: diacritic-folded token -> priority-ordered list of locale IDs.
95    pub folded_token_to_langs: FxHashMap<String, Vec<u16>>,
96    /// Global exact relative phrase index: phrase -> list of (lang_id, RelativeSpec).
97    pub exact_phrase_index: FxHashMap<String, Vec<(u16, RelativeSpec)>>,
98    /// Folded exact relative phrase index: folded phrase -> list of (lang_id, RelativeSpec).
99    pub folded_exact_phrase_index: FxHashMap<String, Vec<(u16, RelativeSpec)>>,
100    /// Tokens that can start or belong to a date expression (used for fast search_dates).
101    pub known_date_tokens: FxHashSet<String>,
102}
103
104impl LocaleRegistry {
105    #[inline]
106    pub fn global() -> &'static Self {
107        REGISTRY.get_or_init(Self::load)
108    }
109
110    fn load() -> Self {
111        let raw_locales: Vec<RawLocale> = postcard::from_bytes(EMBEDDED_LOCALES)
112            .expect("embedded locales.bin must deserialize cleanly");
113
114        let mut locales = Vec::with_capacity(raw_locales.len());
115        let mut code_to_id = FxHashMap::default();
116        let mut token_to_langs: FxHashMap<String, Vec<u16>> = FxHashMap::default();
117        let mut folded_token_to_langs: FxHashMap<String, Vec<u16>> = FxHashMap::default();
118        let mut exact_phrase_index: FxHashMap<String, Vec<(u16, RelativeSpec)>> =
119            FxHashMap::default();
120        let mut folded_exact_phrase_index: FxHashMap<String, Vec<(u16, RelativeSpec)>> =
121            FxHashMap::default();
122        let mut known_date_tokens: FxHashSet<String> = FxHashSet::default();
123
124        let mut register_token = |tok: &str, lang_id: u16, is_search_token: bool| {
125            if tok.is_empty() {
126                return;
127            }
128            let entry = token_to_langs.entry(tok.to_string()).or_default();
129            if entry.last().copied() != Some(lang_id) && !entry.contains(&lang_id) {
130                entry.push(lang_id);
131            }
132            if is_search_token {
133                known_date_tokens.insert(tok.to_string());
134            }
135            let folded = fold_diacritics(tok);
136            if folded != tok && !folded.is_empty() {
137                let fentry = folded_token_to_langs.entry(folded.clone()).or_default();
138                if fentry.last().copied() != Some(lang_id) && !fentry.contains(&lang_id) {
139                    fentry.push(lang_id);
140                }
141                if is_search_token {
142                    known_date_tokens.insert(folded);
143                }
144            }
145        };
146
147        for (idx, raw) in raw_locales.into_iter().enumerate() {
148            let lang_id = idx as u16;
149            code_to_id.insert(raw.code.to_ascii_lowercase(), idx);
150            let date_order = DateOrder::from_str(&raw.date_order).unwrap_or(DateOrder::DMY);
151
152            let mut months = FxHashMap::default();
153            let mut folded_months = FxHashMap::default();
154            for (m_idx, names) in raw.months.into_iter().enumerate() {
155                let month_num = (m_idx + 1) as u8;
156                for name in names {
157                    for part in name.split_whitespace() {
158                        if part.chars().count() >= 2 {
159                            register_token(part, lang_id, true);
160                        }
161                    }
162                    register_token(&name, lang_id, true);
163                    let f = fold_diacritics(&name);
164                    if f != name {
165                        folded_months.entry(f).or_insert(month_num);
166                    }
167                    months.insert(name, month_num);
168                }
169            }
170
171            let mut weekdays = FxHashMap::default();
172            let mut folded_weekdays = FxHashMap::default();
173            for (d_idx, names) in raw.weekdays.into_iter().enumerate() {
174                let wd_num = d_idx as u8;
175                for name in names {
176                    for part in name.split_whitespace() {
177                        if part.chars().count() >= 2 {
178                            register_token(part, lang_id, true);
179                        }
180                    }
181                    register_token(&name, lang_id, true);
182                    let f = fold_diacritics(&name);
183                    if f != name {
184                        folded_weekdays.entry(f).or_insert(wd_num);
185                    }
186                    weekdays.insert(name, wd_num);
187                }
188            }
189
190            let mut am = FxHashSet::default();
191            for s in raw.am {
192                register_token(&s, lang_id, true);
193                am.insert(s);
194            }
195            let mut pm = FxHashSet::default();
196            for s in raw.pm {
197                register_token(&s, lang_id, true);
198                pm.insert(s);
199            }
200
201            let mut units = FxHashMap::default();
202            let mut folded_units = FxHashMap::default();
203            for (tok, u_id) in raw.units {
204                if let Some(u) = TimeUnit::from_u8(u_id) {
205                    register_token(&tok, lang_id, true);
206                    let f = fold_diacritics(&tok);
207                    if f != tok {
208                        folded_units.entry(f).or_insert(u);
209                    }
210                    units.insert(tok, u);
211                }
212            }
213
214            let mut ago = FxHashSet::default();
215            let mut folded_ago = FxHashSet::default();
216            for s in raw.ago {
217                for part in s.split_whitespace() {
218                    register_token(part, lang_id, true);
219                }
220                register_token(&s, lang_id, true);
221                let f = fold_diacritics(&s);
222                if f != s {
223                    folded_ago.insert(f);
224                }
225                ago.insert(s);
226            }
227
228            let mut in_words = FxHashSet::default();
229            let mut folded_in_words = FxHashSet::default();
230            for s in raw.in_words {
231                for part in s.split_whitespace() {
232                    register_token(part, lang_id, true);
233                }
234                register_token(&s, lang_id, true);
235                let f = fold_diacritics(&s);
236                if f != s {
237                    folded_in_words.insert(f);
238                }
239                in_words.insert(s);
240            }
241
242            let mut skip = FxHashSet::default();
243            for s in raw.skip {
244                skip.insert(s);
245            }
246
247            let mut relative_exact: FxHashMap<String, Vec<RelativeSpec>> = FxHashMap::default();
248            let mut folded_relative_exact: FxHashMap<String, Vec<RelativeSpec>> =
249                FxHashMap::default();
250            for (phrase, sign, amount, u_id) in raw.relative_exact {
251                if let Some(unit) = TimeUnit::from_u8(u_id) {
252                    let spec = RelativeSpec { sign, amount, unit };
253                    for part in phrase.split_whitespace() {
254                        register_token(part, lang_id, true);
255                    }
256                    register_token(&phrase, lang_id, true);
257                    exact_phrase_index
258                        .entry(phrase.clone())
259                        .or_default()
260                        .push((lang_id, spec));
261                    let f = fold_diacritics(&phrase);
262                    if f != phrase {
263                        folded_exact_phrase_index
264                            .entry(f.clone())
265                            .or_default()
266                            .push((lang_id, spec));
267                        folded_relative_exact.entry(f).or_default().push(spec);
268                    }
269                    relative_exact.entry(phrase).or_default().push(spec);
270                }
271            }
272
273            let mut relative_affix = Vec::with_capacity(raw.relative_affix.len());
274            let mut folded_relative_affix = Vec::new();
275            for (prefix, suffix, sign, u_id) in raw.relative_affix {
276                if let Some(unit) = TimeUnit::from_u8(u_id) {
277                    for part in prefix.split_whitespace().chain(suffix.split_whitespace()) {
278                        if part.chars().count() >= 2 {
279                            register_token(part, lang_id, true);
280                        }
281                    }
282                    let fp = fold_diacritics(&prefix);
283                    let fs = fold_diacritics(&suffix);
284                    if fp != prefix || fs != suffix {
285                        folded_relative_affix.push(RelativeAffix {
286                            prefix: fp,
287                            suffix: fs,
288                            sign,
289                            unit,
290                        });
291                    }
292                    relative_affix.push(RelativeAffix {
293                        prefix,
294                        suffix,
295                        sign,
296                        unit,
297                    });
298                }
299            }
300            // Match longest affixes first for specificity
301            let sort_affix = |v: &mut Vec<RelativeAffix>| {
302                v.sort_by(|a, b| {
303                    let la = a.prefix.len() + a.suffix.len();
304                    let lb = b.prefix.len() + b.suffix.len();
305                    lb.cmp(&la)
306                });
307            };
308            sort_affix(&mut relative_affix);
309            sort_affix(&mut folded_relative_affix);
310
311            let mut word_numbers = FxHashMap::default();
312            for (w, n) in raw.word_numbers {
313                let f = fold_diacritics(&w);
314                if f != w {
315                    word_numbers.entry(f).or_insert(n);
316                }
317                word_numbers.insert(w, n);
318            }
319
320            let mut time_of_day = FxHashMap::default();
321            let mut folded_time_of_day = FxHashMap::default();
322            for (phrase, hour) in raw.time_of_day {
323                for part in phrase.split_whitespace() {
324                    register_token(part, lang_id, true);
325                }
326                register_token(&phrase, lang_id, true);
327                let f = fold_diacritics(&phrase);
328                if f != phrase {
329                    folded_time_of_day.entry(f).or_insert(hour);
330                }
331                time_of_day.insert(phrase, hour);
332            }
333
334            // Ensure key compound time-of-day trigger words are indexed for search_dates / lang detect
335            if raw.code == "en" {
336                register_token("tonight", lang_id, true);
337            } else if raw.code == "es" {
338                register_token("anoche", lang_id, true);
339            } else if raw.code == "tr" {
340                register_token("saat", lang_id, true);
341            }
342
343            locales.push(CompiledLocale {
344                id: lang_id,
345                code: raw.code,
346                date_order,
347                months,
348                weekdays,
349                am,
350                pm,
351                units,
352                ago,
353                in_words,
354                skip,
355                relative_exact,
356                relative_affix,
357                word_numbers,
358                time_of_day,
359                folded_months,
360                folded_weekdays,
361                folded_units,
362                folded_ago,
363                folded_in_words,
364                folded_relative_exact,
365                folded_relative_affix,
366                folded_time_of_day,
367            });
368        }
369
370        Self {
371            locales,
372            code_to_id,
373            token_to_langs,
374            folded_token_to_langs,
375            exact_phrase_index,
376            folded_exact_phrase_index,
377            known_date_tokens,
378        }
379    }
380
381    pub fn resolve_lang_id(&self, code: &str) -> Option<usize> {
382        let lower = code.trim().to_ascii_lowercase();
383        if let Some(&id) = self.code_to_id.get(&lower) {
384            return Some(id);
385        }
386        // Handle underscore/hyphen variants (e.g. "uz_cyrl" -> "uz-cyrl")
387        let dash = lower.replace('_', "-");
388        if let Some(&id) = self.code_to_id.get(&dash) {
389            return Some(id);
390        }
391        // Fallback: "en-US" or "tr_TR" -> "en" or "tr"
392        if let Some(base) = dash.split('-').next() {
393            if let Some(&id) = self.code_to_id.get(base) {
394                return Some(id);
395            }
396        }
397        None
398    }
399
400    /// Detect top candidate language IDs in O(tokens) time without scanning all 205 locales.
401    pub fn detect_candidates(
402        &self,
403        normalized: &str,
404        tokens: &[&str],
405        explicit_langs: Option<&[String]>,
406        default_langs: &[String],
407        normalize: bool,
408    ) -> Vec<usize> {
409        if let Some(langs) = explicit_langs {
410            if !langs.is_empty() {
411                let mut out = Vec::with_capacity(langs.len());
412                for code in langs {
413                    if let Some(id) = self.resolve_lang_id(code) {
414                        if !out.contains(&id) {
415                            out.push(id);
416                        }
417                    }
418                }
419                return out;
420            }
421        }
422
423        // Fast exact relative phrase lookup
424        if let Some(matches) = self.exact_phrase_index.get(normalized) {
425            let mut out: Vec<usize> = matches.iter().map(|(id, _)| *id as usize).collect();
426            out.sort_unstable();
427            out.dedup();
428            return out;
429        }
430
431        if normalize {
432            let f = fold_diacritics(normalized);
433            if let Some(matches) = self.folded_exact_phrase_index.get(&f) {
434                let mut out: Vec<usize> = matches.iter().map(|(id, _)| *id as usize).collect();
435                out.sort_unstable();
436                out.dedup();
437                return out;
438            }
439        }
440
441        // Script-based fast narrowing for non-Latin scripts
442        let script_hint = detect_script_hint(normalized);
443
444        let mut scores: FxHashMap<u16, u32> = FxHashMap::default();
445        for &tok in tokens {
446            if tok.len() <= 1 && tok.is_ascii() {
447                continue;
448            }
449            if let Some(langs) = self.token_to_langs.get(tok) {
450                let weight = if langs.len() <= 3 {
451                    8
452                } else if langs.len() <= 12 {
453                    4
454                } else {
455                    2
456                };
457                for &lid in langs {
458                    *scores.entry(lid).or_insert(0) += weight;
459                }
460            }
461            if normalize {
462                let ft = fold_diacritics(tok);
463                if let Some(langs) = self.folded_token_to_langs.get(&ft) {
464                    let weight = if langs.len() <= 3 {
465                        5
466                    } else if langs.len() <= 12 {
467                        3
468                    } else {
469                        1
470                    };
471                    for &lid in langs {
472                        *scores.entry(lid).or_insert(0) += weight;
473                    }
474                }
475            }
476        }
477
478        // Also check 2-word phrases (e.g. "il y a", "geçen hafta", "next week", "hace 2")
479        for w in tokens.windows(2) {
480            let bigram = format!("{} {}", w[0], w[1]);
481            if let Some(langs) = self.token_to_langs.get(&bigram) {
482                for &lid in langs {
483                    *scores.entry(lid).or_insert(0) += 6;
484                }
485            }
486            if normalize {
487                let fb = fold_diacritics(&bigram);
488                if fb != bigram {
489                    if let Some(langs) = self.folded_token_to_langs.get(&fb) {
490                        for &lid in langs {
491                            *scores.entry(lid).or_insert(0) += 4;
492                        }
493                    }
494                }
495            }
496        }
497
498        // Boost script-matched languages (crucial for CJK/Arabic/Thai where no spaces exist)
499        if let Some(hint_codes) = script_hint {
500            for code in hint_codes {
501                if let Some(id) = self.resolve_lang_id(code) {
502                    *scores.entry(id as u16).or_insert(0) += 5;
503                }
504            }
505        }
506
507        // Slight tie-break boost for default_languages
508        for code in default_langs {
509            if let Some(id) = self.resolve_lang_id(code) {
510                if let Some(sc) = scores.get_mut(&(id as u16)) {
511                    *sc += 2;
512                }
513            }
514        }
515
516        if scores.is_empty() {
517            return Vec::new();
518        }
519
520        let mut ranked: Vec<(u16, u32)> = scores.into_iter().collect();
521        // Highest score first; ties broken by global language priority (lower id = higher priority)
522        ranked.sort_unstable_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(&b.0)));
523
524        ranked.into_iter().take(8).map(|(id, _)| id as usize).collect()
525    }
526}
527
528/// Fold common Latin and Arabic diacritics for accent-tolerant matching (`NORMALIZE=True`).
529pub fn fold_diacritics(s: &str) -> String {
530    let mut out = String::with_capacity(s.len());
531    for ch in s.chars() {
532        let mapped = match ch {
533            'á' | 'à' | 'â' | 'ä' | 'ã' | 'å' | 'ā' | 'ă' | 'ą' => 'a',
534            'é' | 'è' | 'ê' | 'ë' | 'ē' | 'ĕ' | 'ė' | 'ę' | 'ě' => 'e',
535            'í' | 'ì' | 'î' | 'ï' | 'ī' | 'ĭ' | 'į' | 'ı' => 'i',
536            'ó' | 'ò' | 'ô' | 'ö' | 'õ' | 'ø' | 'ō' | 'ŏ' | 'ő' => 'o',
537            'ú' | 'ù' | 'û' | 'ü' | 'ū' | 'ŭ' | 'ů' | 'ű' | 'ų' => 'u',
538            'ç' | 'ć' | 'ĉ' | 'ċ' | 'č' => 'c',
539            'ğ' | 'ĝ' | 'ġ' | 'ģ' => 'g',
540            'ş' | 'ś' | 'ŝ' | 'š' => 's',
541            'ñ' | 'ń' | 'ņ' | 'ň' => 'n',
542            'ý' | 'ÿ' | 'ŷ' => 'y',
543            'ž' | 'ź' | 'ż' => 'z',
544            'ł' | 'ĺ' | 'ļ' | 'ľ' => 'l',
545            'ř' | 'ŕ' | 'ŗ' => 'r',
546            'ď' | 'đ' => 'd',
547            'ť' | 'ţ' => 't',
548            // Arabic alef normalization & harakat/tatweel stripping
549            'أ' | 'إ' | 'آ' | 'ٱ' => 'ا',
550            'ى' => 'ي',
551            '\u{064B}'..='\u{065F}' | '\u{0670}' | '\u{0640}' | '\u{0300}'..='\u{036F}' => {
552                continue;
553            }
554            other => other,
555        };
556        out.push(mapped);
557    }
558    out
559}
560
561fn detect_script_hint(s: &str) -> Option<&'static [&'static str]> {
562    let mut has_hiragana_katakana = false;
563    let mut has_han = false;
564    let mut has_hangul = false;
565    let mut has_cyrillic = false;
566    let mut has_arabic = false;
567    let mut has_hebrew = false;
568    let mut has_greek = false;
569    let mut has_thai = false;
570    let mut has_devanagari = false;
571
572    for ch in s.chars() {
573        let c = ch as u32;
574        match c {
575            0x3040..=0x30FF => has_hiragana_katakana = true,
576            0x4E00..=0x9FFF => has_han = true,
577            0xAC00..=0xD7AF => has_hangul = true,
578            0x0400..=0x04FF => has_cyrillic = true,
579            0x0600..=0x06FF => has_arabic = true,
580            0x0590..=0x05FF => has_hebrew = true,
581            0x0370..=0x03FF => has_greek = true,
582            0x0E00..=0x0E7F => has_thai = true,
583            0x0900..=0x097F => has_devanagari = true,
584            _ => {}
585        }
586    }
587
588    if has_hiragana_katakana {
589        Some(&["ja"])
590    } else if has_hangul {
591        Some(&["ko"])
592    } else if has_han {
593        Some(&["zh", "ja"])
594    } else if has_cyrillic {
595        Some(&["ru", "uk", "bg", "sr", "be", "kk"])
596    } else if has_arabic {
597        Some(&["ar", "fa", "ur"])
598    } else if has_hebrew {
599        Some(&["he"])
600    } else if has_greek {
601        Some(&["el"])
602    } else if has_thai {
603        Some(&["th"])
604    } else if has_devanagari {
605        Some(&["hi", "mr", "ne"])
606    } else {
607        None
608    }
609}
610
611/// Normalize Unicode digits (Arabic-Indic, Eastern Arabic, Devanagari, Fullwidth) to ASCII 0-9
612/// and collapse whitespace/punctuation for fast matching.
613pub fn normalize_digits_and_lower(input: &str) -> String {
614    let mut out = String::with_capacity(input.len());
615    let mut prev_space = true;
616    for ch in input.chars() {
617        let mapped = match ch {
618            '\u{0660}'..='\u{0669}' => char::from_u32('0' as u32 + (ch as u32 - 0x0660)).unwrap(),
619            '\u{06F0}'..='\u{06F9}' => char::from_u32('0' as u32 + (ch as u32 - 0x06F0)).unwrap(),
620            '\u{0966}'..='\u{096F}' => char::from_u32('0' as u32 + (ch as u32 - 0x0966)).unwrap(),
621            '\u{FF10}'..='\u{FF19}' => char::from_u32('0' as u32 + (ch as u32 - 0xFF10)).unwrap(),
622            // Turkish dotted/dotless I normalization to match lowercase tables cleanly
623            '\u{0130}' => 'i',
624            '\u{00A0}' | '\u{2009}' | '\u{202F}' => ' ',
625            other => other,
626        };
627        if mapped.is_whitespace() {
628            if !prev_space {
629                out.push(' ');
630                prev_space = true;
631            }
632        } else if mapped == '\u{0307}' {
633            continue;
634        } else {
635            for lc in mapped.to_lowercase() {
636                if lc != '\u{0307}' {
637                    out.push(lc);
638                }
639            }
640            prev_space = false;
641        }
642    }
643    if out.ends_with(' ') {
644        out.pop();
645    }
646    out
647}