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        use_given_order: bool,
409    ) -> Vec<usize> {
410        if let Some(langs) = explicit_langs {
411            if !langs.is_empty() {
412                let mut out = Vec::with_capacity(langs.len());
413                for code in langs {
414                    if let Some(id) = self.resolve_lang_id(code) {
415                        if !out.contains(&id) {
416                            out.push(id);
417                        }
418                    }
419                }
420                return out;
421            }
422        }
423
424        let order_with_defaults = |mut ids: Vec<usize>| -> Vec<usize> {
425            if use_given_order && !default_langs.is_empty() {
426                let mut ordered = Vec::with_capacity(ids.len());
427                for code in default_langs {
428                    if let Some(did) = self.resolve_lang_id(code) {
429                        if ids.contains(&did) && !ordered.contains(&did) {
430                            ordered.push(did);
431                        }
432                    }
433                }
434                for id in ids {
435                    if !ordered.contains(&id) {
436                        ordered.push(id);
437                    }
438                }
439                ids = ordered;
440            }
441            ids
442        };
443
444        // Fast exact relative phrase lookup
445        if let Some(matches) = self.exact_phrase_index.get(normalized) {
446            let mut out: Vec<usize> = matches.iter().map(|(id, _)| *id as usize).collect();
447            out.sort_unstable();
448            out.dedup();
449            return order_with_defaults(out);
450        }
451
452        if normalize {
453            let f = fold_diacritics(normalized);
454            if let Some(matches) = self.folded_exact_phrase_index.get(&f) {
455                let mut out: Vec<usize> = matches.iter().map(|(id, _)| *id as usize).collect();
456                out.sort_unstable();
457                out.dedup();
458                return order_with_defaults(out);
459            }
460        }
461
462        // Script-based fast narrowing for non-Latin scripts
463        let script_hint = detect_script_hint(normalized);
464
465        let mut scores: FxHashMap<u16, u32> = FxHashMap::default();
466        for &tok in tokens {
467            if tok.len() <= 1 && tok.is_ascii() {
468                continue;
469            }
470            if let Some(langs) = self.token_to_langs.get(tok) {
471                let weight = if langs.len() <= 3 {
472                    8
473                } else if langs.len() <= 12 {
474                    4
475                } else {
476                    2
477                };
478                for &lid in langs {
479                    *scores.entry(lid).or_insert(0) += weight;
480                }
481            }
482            if normalize {
483                let ft = fold_diacritics(tok);
484                if let Some(langs) = self.folded_token_to_langs.get(&ft) {
485                    let weight = if langs.len() <= 3 {
486                        5
487                    } else if langs.len() <= 12 {
488                        3
489                    } else {
490                        1
491                    };
492                    for &lid in langs {
493                        *scores.entry(lid).or_insert(0) += weight;
494                    }
495                }
496            }
497        }
498
499        // Also check 2-word phrases (e.g. "il y a", "geçen hafta", "next week", "hace 2")
500        for w in tokens.windows(2) {
501            let bigram = format!("{} {}", w[0], w[1]);
502            if let Some(langs) = self.token_to_langs.get(&bigram) {
503                for &lid in langs {
504                    *scores.entry(lid).or_insert(0) += 6;
505                }
506            }
507            if normalize {
508                let fb = fold_diacritics(&bigram);
509                if fb != bigram {
510                    if let Some(langs) = self.folded_token_to_langs.get(&fb) {
511                        for &lid in langs {
512                            *scores.entry(lid).or_insert(0) += 4;
513                        }
514                    }
515                }
516            }
517        }
518
519        // Boost script-matched languages (crucial for CJK/Arabic/Thai where no spaces exist)
520        if let Some(hint_codes) = script_hint {
521            for code in hint_codes {
522                if let Some(id) = self.resolve_lang_id(code) {
523                    *scores.entry(id as u16).or_insert(0) += 5;
524                }
525            }
526        }
527
528        // Slight tie-break boost for default_languages
529        for code in default_langs {
530            if let Some(id) = self.resolve_lang_id(code) {
531                if let Some(sc) = scores.get_mut(&(id as u16)) {
532                    *sc += 2;
533                }
534            }
535        }
536
537        if scores.is_empty() {
538            return Vec::new();
539        }
540
541        let mut ranked: Vec<(u16, u32)> = scores.into_iter().collect();
542        // Highest score first; ties broken by global language priority (lower id = higher priority)
543        ranked.sort_unstable_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(&b.0)));
544
545        let top: Vec<usize> = ranked.into_iter().take(8).map(|(id, _)| id as usize).collect();
546        order_with_defaults(top)
547    }
548}
549
550/// Fold common Latin and Arabic diacritics for accent-tolerant matching (`NORMALIZE=True`).
551pub fn fold_diacritics(s: &str) -> String {
552    let mut out = String::with_capacity(s.len());
553    for ch in s.chars() {
554        let mapped = match ch {
555            'á' | 'à' | 'â' | 'ä' | 'ã' | 'å' | 'ā' | 'ă' | 'ą' => 'a',
556            'é' | 'è' | 'ê' | 'ë' | 'ē' | 'ĕ' | 'ė' | 'ę' | 'ě' => 'e',
557            'í' | 'ì' | 'î' | 'ï' | 'ī' | 'ĭ' | 'į' | 'ı' => 'i',
558            'ó' | 'ò' | 'ô' | 'ö' | 'õ' | 'ø' | 'ō' | 'ŏ' | 'ő' => 'o',
559            'ú' | 'ù' | 'û' | 'ü' | 'ū' | 'ŭ' | 'ů' | 'ű' | 'ų' => 'u',
560            'ç' | 'ć' | 'ĉ' | 'ċ' | 'č' => 'c',
561            'ğ' | 'ĝ' | 'ġ' | 'ģ' => 'g',
562            'ş' | 'ś' | 'ŝ' | 'š' => 's',
563            'ñ' | 'ń' | 'ņ' | 'ň' => 'n',
564            'ý' | 'ÿ' | 'ŷ' => 'y',
565            'ž' | 'ź' | 'ż' => 'z',
566            'ł' | 'ĺ' | 'ļ' | 'ľ' => 'l',
567            'ř' | 'ŕ' | 'ŗ' => 'r',
568            'ď' | 'đ' => 'd',
569            'ť' | 'ţ' => 't',
570            // Arabic alef normalization & harakat/tatweel stripping
571            'أ' | 'إ' | 'آ' | 'ٱ' => 'ا',
572            'ى' => 'ي',
573            '\u{064B}'..='\u{065F}' | '\u{0670}' | '\u{0640}' | '\u{0300}'..='\u{036F}' => {
574                continue;
575            }
576            other => other,
577        };
578        out.push(mapped);
579    }
580    out
581}
582
583fn detect_script_hint(s: &str) -> Option<&'static [&'static str]> {
584    let mut has_hiragana_katakana = false;
585    let mut has_han = false;
586    let mut has_hangul = false;
587    let mut has_cyrillic = false;
588    let mut has_arabic = false;
589    let mut has_hebrew = false;
590    let mut has_greek = false;
591    let mut has_thai = false;
592    let mut has_devanagari = false;
593
594    for ch in s.chars() {
595        let c = ch as u32;
596        match c {
597            0x3040..=0x30FF => has_hiragana_katakana = true,
598            0x4E00..=0x9FFF => has_han = true,
599            0xAC00..=0xD7AF => has_hangul = true,
600            0x0400..=0x04FF => has_cyrillic = true,
601            0x0600..=0x06FF => has_arabic = true,
602            0x0590..=0x05FF => has_hebrew = true,
603            0x0370..=0x03FF => has_greek = true,
604            0x0E00..=0x0E7F => has_thai = true,
605            0x0900..=0x097F => has_devanagari = true,
606            _ => {}
607        }
608    }
609
610    if has_hiragana_katakana {
611        Some(&["ja"])
612    } else if has_hangul {
613        Some(&["ko"])
614    } else if has_han {
615        Some(&["zh", "ja"])
616    } else if has_cyrillic {
617        Some(&["ru", "uk", "bg", "sr", "be", "kk"])
618    } else if has_arabic {
619        Some(&["ar", "fa", "ur"])
620    } else if has_hebrew {
621        Some(&["he"])
622    } else if has_greek {
623        Some(&["el"])
624    } else if has_thai {
625        Some(&["th"])
626    } else if has_devanagari {
627        Some(&["hi", "mr", "ne"])
628    } else {
629        None
630    }
631}
632
633/// Normalize Unicode digits (Arabic-Indic, Eastern Arabic, Devanagari, Fullwidth) to ASCII 0-9
634/// and collapse whitespace/punctuation for fast matching.
635pub fn normalize_digits_and_lower(input: &str) -> String {
636    let mut out = String::with_capacity(input.len());
637    let mut prev_space = true;
638    for ch in input.chars() {
639        let mapped = match ch {
640            '\u{0660}'..='\u{0669}' => char::from_u32('0' as u32 + (ch as u32 - 0x0660)).unwrap(),
641            '\u{06F0}'..='\u{06F9}' => char::from_u32('0' as u32 + (ch as u32 - 0x06F0)).unwrap(),
642            '\u{0966}'..='\u{096F}' => char::from_u32('0' as u32 + (ch as u32 - 0x0966)).unwrap(),
643            '\u{FF10}'..='\u{FF19}' => char::from_u32('0' as u32 + (ch as u32 - 0xFF10)).unwrap(),
644            // Turkish dotted/dotless I normalization to match lowercase tables cleanly
645            '\u{0130}' => 'i',
646            '\u{00A0}' | '\u{2009}' | '\u{202F}' => ' ',
647            other => other,
648        };
649        if mapped.is_whitespace() {
650            if !prev_space {
651                out.push(' ');
652                prev_space = true;
653            }
654        } else if mapped == '\u{0307}' {
655            continue;
656        } else {
657            for lc in mapped.to_lowercase() {
658                if lc != '\u{0307}' {
659                    out.push(lc);
660                }
661            }
662            prev_space = false;
663        }
664    }
665    if out.ends_with(' ') {
666        out.pop();
667    }
668    out
669}