Debian Codegraph @

debian/rust-vendor/icu_locale/src/canonicalizer.rs

raw
1 // This file is part of ICU4X. For terms of use, please see the file
2 // called LICENSE at the top level of the ICU4X source tree
3 // (online at: https://github.com/unicode-org/icu4x/blob/main/LICENSE ).
4
5 //! The collection of code for locale canonicalization.
6
7 use crate::LocaleExpander;
8 use crate::TransformResult;
9 use crate::provider::*;
10 use alloc::vec::Vec;
11 use core::cmp::Ordering;
12 use icu_locale_core::extensions::Extensions;
13 use icu_locale_core::subtags::{Language, Region, Script};
14 use icu_locale_core::{
15 LanguageIdentifier, Locale,
16 extensions::unicode::key,
17 subtags::{Variant, Variants, language},
18 };
19 use icu_locale_fallback::provider::LocaleLikelySubtagsLanguageV1;
20 use icu_provider::prelude::*;
21 use tinystr::TinyAsciiStr;
22
23 /// Implements the algorithm defined in *[UTS #35: Annex C, LocaleId Canonicalization]*.
24 ///
25 /// # Examples
26 ///
27 /// ```
28 /// use icu::locale::Locale;
29 /// use icu::locale::{LocaleCanonicalizer, TransformResult};
30 ///
31 /// let lc = LocaleCanonicalizer::new_extended();
32 ///
33 /// let mut locale: Locale = "ja-Latn-fonipa-hepburn-heploc".parse().unwrap();
34 /// assert_eq!(lc.canonicalize(&mut locale), TransformResult::Modified);
35 /// assert_eq!(locale, "ja-Latn-alalc97-fonipa".parse().unwrap());
36 /// ```
37 ///
38 /// [UTS #35: Annex C, LocaleId Canonicalization]: https://unicode.org/reports/tr35/#LocaleId_Canonicalization
39 #[derive(Debug)]
40 pub struct LocaleCanonicalizer<Expander = LocaleExpander> {
41 /// Data to support canonicalization.
42 aliases: DataPayload<LocaleAliasesV1>,
43 /// Likely subtags implementation for delegation.
44 expander: Expander,
45 }
46
47 fn uts35_rule_matches<'a, I>(
48 source: &LanguageIdentifier,
49 language: Language,
50 script: Option<Script>,
51 region: Option<Region>,
52 raw_variants: I,
53 ) -> bool
54 where
55 I: Iterator<Item = &'a str>,
56 {
57 (language.is_unknown() || language == source.language)
58 && (script.is_none() || script == source.script)
59 && (region.is_none() || region == source.region)
60 && {
61 // Checks if variants are a subset of source variants.
62 // As both iterators are sorted, this can be done linearly.
63 let mut source_variants = source.variants.iter();
64 'outer: for raw_variant in raw_variants {
65 for source_variant in source_variants.by_ref() {
66 match source_variant.as_str().cmp(raw_variant) {
67 Ordering::Equal => {
68 // The source_variant is equal, move to next raw_variant
69 continue 'outer;
70 }
71 Ordering::Less => {
72 // The source_variant is smaller, take the next source_variant
73 }
74 Ordering::Greater => {
75 // The source_variant is greater,
76 // raw_variants is not a subset of source_variants
77 return false;
78 }
79 }
80 }
81 // There are raw_variants left after we exhausted source_variants
82 return false;
83 }
84 true
85 }
86 }
87
88 fn uts35_replacement<'a, I>(
89 source: &mut LanguageIdentifier,
90 ruletype_has_language: bool,
91 ruletype_has_script: bool,
92 ruletype_has_region: bool,
93 ruletype_variants: Option<I>,
94 replacement: &LanguageIdentifier,
95 ) where
96 I: Iterator<Item = &'a str>,
97 {
98 if ruletype_has_language || (source.language.is_unknown() && !replacement.language.is_unknown())
99 {
100 source.language = replacement.language;
101 }
102 if ruletype_has_script || (source.script.is_none() && replacement.script.is_some()) {
103 source.script = replacement.script;
104 }
105 if ruletype_has_region || (source.region.is_none() && replacement.region.is_some()) {
106 source.region = replacement.region;
107 }
108 if let Some(skips) = ruletype_variants {
109 // The rule matches if the ruletype variants are a subset of the source variants.
110 // This means ja-Latn-fonipa-hepburn-heploc matches against the rule for
111 // hepburn-heploc and is canonicalized to ja-Latn-alalc97-fonipa
112
113 // We're merging three sorted deduped iterators into a new sequence:
114 // sources - skips + replacements
115
116 let mut sources = source.variants.iter().peekable();
117 let mut replacements = replacement.variants.iter().peekable();
118 let mut skips = skips.peekable();
119
120 let mut variants: Vec<Variant> = Vec::new();
121
122 loop {
123 match (sources.peek(), skips.peek(), replacements.peek()) {
124 (Some(&source), Some(skip), _)
125 if source.as_str().cmp(skip) == Ordering::Greater =>
126 {
127 skips.next();
128 }
129 (Some(&source), Some(skip), _) if source.as_str().cmp(skip) == Ordering::Equal => {
130 skips.next();
131 sources.next();
132 }
133 (Some(&source), _, Some(&replacement))
134 if replacement.cmp(source) == Ordering::Less =>
135 {
136 variants.push(*replacement);
137 replacements.next();
138 }
139 (Some(&source), _, Some(&replacement))
140 if replacement.cmp(source) == Ordering::Equal =>
141 {
142 variants.push(*source);
143 sources.next();
144 replacements.next();
145 }
146 (Some(&source), _, _) => {
147 variants.push(*source);
148 sources.next();
149 }
150 (None, _, Some(&replacement)) => {
151 variants.push(*replacement);
152 replacements.next();
153 }
154 (None, _, None) => {
155 break;
156 }
157 }
158 }
159 source.variants = Variants::from_vec_unchecked(variants);
160 }
161 }
162
163 #[inline]
164 fn uts35_check_language_rules(
165 langid: &mut LanguageIdentifier,
166 alias_data: &DataPayload<LocaleAliasesV1>,
167 ) -> TransformResult {
168 if !langid.language.is_unknown() {
169 let lang: TinyAsciiStr<3> = langid.language.into();
170 let replacement = if lang.len() == 2 {
171 alias_data
172 .get()
173 .language_len2
174 .get(&lang.resize().to_unvalidated())
175 } else {
176 alias_data.get().language_len3.get(&lang.to_unvalidated())
177 };
178
179 if let Some(replacement) = replacement
180 && let Ok(new_langid) = replacement.parse()
181 {
182 uts35_replacement::<core::iter::Empty<&str>>(
183 langid,
184 true,
185 false,
186 false,
187 None,
188 &new_langid,
189 );
190 return TransformResult::Modified;
191 }
192 }
193
194 TransformResult::Unmodified
195 }
196
197 impl LocaleCanonicalizer<LocaleExpander> {
198 /// A constructor which creates a [`LocaleCanonicalizer`] from compiled data,
199 /// using a [`LocaleExpander`] for common locales.
200 ///
201 /// ✨ *Enabled with the `compiled_data` Cargo feature.*
202 ///
203 /// [📚 Help choosing a constructor](icu_provider::constructors)
204 #[cfg(feature = "compiled_data")]
205 pub const fn new_common() -> Self {
206 Self::new_with_expander(LocaleExpander::new_common())
207 }
208
209 icu_provider::gen_buffer_data_constructors!(() -> error: DataError,
210 functions: [
211 new_common: skip,
212 try_new_common_with_buffer_provider,
213 try_new_common_unstable,
214 Self,
215 ]
216 );
217
218 #[doc = icu_provider::gen_buffer_unstable_docs!(UNSTABLE, Self::new_common)]
219 pub fn try_new_common_unstable<P>(provider: &P) -> Result<Self, DataError>
220 where
221 P: DataProvider<LocaleAliasesV1>
222 + DataProvider<LocaleLikelySubtagsLanguageV1>
223 + DataProvider<LocaleLikelySubtagsScriptRegionV1>
224 + ?Sized,
225 {
226 let expander = LocaleExpander::try_new_common_unstable(provider)?;
227 Self::try_new_with_expander_unstable(provider, expander)
228 }
229
230 /// A constructor which creates a [`LocaleCanonicalizer`] from compiled data,
231 /// using a [`LocaleExpander`] for all locales.
232 ///
233 /// ✨ *Enabled with the `compiled_data` Cargo feature.*
234 ///
235 /// [📚 Help choosing a constructor](icu_provider::constructors)
236 #[cfg(feature = "compiled_data")]
237 pub const fn new_extended() -> Self {
238 Self::new_with_expander(LocaleExpander::new_extended())
239 }
240
241 icu_provider::gen_buffer_data_constructors!(() -> error: DataError,
242 functions: [
243 new_extended: skip,
244 try_new_extended_with_buffer_provider,
245 try_new_extended_unstable,
246 Self,
247 ]
248 );
249
250 #[doc = icu_provider::gen_buffer_unstable_docs!(UNSTABLE, Self::new_extended)]
251 pub fn try_new_extended_unstable<P>(provider: &P) -> Result<Self, DataError>
252 where
253 P: DataProvider<LocaleAliasesV1>
254 + DataProvider<LocaleLikelySubtagsLanguageV1>
255 + DataProvider<LocaleLikelySubtagsScriptRegionV1>
256 + DataProvider<LocaleLikelySubtagsExtendedV1>
257 + ?Sized,
258 {
259 let expander = LocaleExpander::try_new_extended_unstable(provider)?;
260 Self::try_new_with_expander_unstable(provider, expander)
261 }
262 }
263
264 impl<Expander: AsRef<LocaleExpander>> LocaleCanonicalizer<Expander> {
265 /// Creates a [`LocaleCanonicalizer`] with a custom [`LocaleExpander`] and compiled data.
266 ///
267 /// ✨ *Enabled with the `compiled_data` Cargo feature.*
268 ///
269 /// [📚 Help choosing a constructor](icu_provider::constructors)
270 #[cfg(feature = "compiled_data")]
271 pub const fn new_with_expander(expander: Expander) -> Self {
272 Self {
273 aliases: DataPayload::from_static_ref(Baked::SINGLETON_LOCALE_ALIASES_V1),
274 expander,
275 }
276 }
277
278 #[doc = icu_provider::gen_buffer_unstable_docs!(UNSTABLE, Self::new_with_expander)]
279 pub fn try_new_with_expander_unstable<P>(
280 provider: &P,
281 expander: Expander,
282 ) -> Result<Self, DataError>
283 where
284 P: DataProvider<LocaleAliasesV1> + ?Sized,
285 {
286 let aliases: DataPayload<LocaleAliasesV1> = provider.load(Default::default())?.payload;
287
288 Ok(Self { aliases, expander })
289 }
290
291 icu_provider::gen_buffer_data_constructors!((options: Expander) -> error: DataError,
292 functions: [
293 new_with_expander: skip,
294 try_new_with_expander_with_buffer_provider,
295 try_new_with_expander_unstable,
296 Self,
297 ]
298 );
299
300 /// The canonicalize method potentially updates a passed in locale in place
301 /// depending up the results of running the canonicalization algorithm
302 /// from <https://unicode.org/reports/tr35/#LocaleId_Canonicalization>.
303 ///
304 /// Some BCP47 canonicalization data is not part of the CLDR json package. Because
305 /// of this, some canonicalizations are not performed, e.g. the canonicalization of
306 /// `und-u-ca-islamicc` to `und-u-ca-islamic-civil`. This will be fixed in a future
307 /// release once the missing data has been added to the CLDR json data. See:
308 /// <https://github.com/unicode-org/icu4x/issues/746>
309 ///
310 /// # Examples
311 ///
312 /// ```
313 /// use icu::locale::{Locale, LocaleCanonicalizer, TransformResult};
314 ///
315 /// let lc = LocaleCanonicalizer::new_extended();
316 ///
317 /// let mut locale: Locale = "ja-Latn-fonipa-hepburn-heploc".parse().unwrap();
318 /// assert_eq!(lc.canonicalize(&mut locale), TransformResult::Modified);
319 /// assert_eq!(locale, "ja-Latn-alalc97-fonipa".parse().unwrap());
320 /// ```
321 pub fn canonicalize(&self, locale: &mut Locale) -> TransformResult {
322 let mut result = TransformResult::Unmodified;
323
324 // This loops until we get a 'fixed point', where applying the rules do not
325 // result in any more changes.
326 loop {
327 // These are linear searches due to the ordering imposed by the canonicalization
328 // rules, where rules with more variants should be considered first. With the
329 // current data in CLDR, we will only do this for locales which have variants,
330 // or new rules which we haven't special-cased yet (of which there are fewer
331 // than 20).
332 let modified = if locale.id.variants.is_empty() {
333 self.canonicalize_absolute_language_fallbacks(&mut locale.id)
334 } else {
335 self.canonicalize_language_variant_fallbacks(&mut locale.id)
336 };
337 if modified {
338 result = TransformResult::Modified;
339 continue;
340 }
341
342 if !locale.id.language.is_unknown() {
343 // If the region is specified, check sgn-region rules first
344 if let Some(region) = locale.id.region
345 && locale.id.language == language!("sgn")
346 && let Some(&sgn_lang) = self
347 .aliases
348 .get()
349 .sgn_region
350 .get(&region.to_tinystr().to_unvalidated())
351 {
352 uts35_replacement::<core::iter::Empty<&str>>(
353 &mut locale.id,
354 true,
355 false,
356 true,
357 None,
358 &sgn_lang.into(),
359 );
360 result = TransformResult::Modified;
361 continue;
362 }
363
364 if uts35_check_language_rules(&mut locale.id, &self.aliases)
365 == TransformResult::Modified
366 {
367 result = TransformResult::Modified;
368 continue;
369 }
370 }
371
372 if let Some(script) = locale.id.script
373 && let Some(&replacement) = self
374 .aliases
375 .get()
376 .script
377 .get(&script.to_tinystr().to_unvalidated())
378 {
379 locale.id.script = Some(replacement);
380 result = TransformResult::Modified;
381 continue;
382 }
383
384 if let Some(region) = locale.id.region {
385 let replacement = if region.is_alphabetic() {
386 self.aliases
387 .get()
388 .region_alpha
389 .get(&region.to_tinystr().resize().to_unvalidated())
390 } else {
391 self.aliases
392 .get()
393 .region_num
394 .get(&region.to_tinystr().to_unvalidated())
395 };
396 if let Some(&replacement) = replacement {
397 locale.id.region = Some(replacement);
398 result = TransformResult::Modified;
399 continue;
400 }
401
402 if let Some(regions) = self
403 .aliases
404 .get()
405 .complex_region
406 .get(&region.to_tinystr().to_unvalidated())
407 {
408 // Skip if regions are empty
409 if let Some(default_region) = regions.get(0) {
410 let mut maximized = LanguageIdentifier {
411 language: locale.id.language,
412 script: locale.id.script,
413 region: None,
414 variants: Variants::default(),
415 };
416
417 locale.id.region = Some(
418 match (
419 self.expander.as_ref().maximize(&mut maximized),
420 maximized.region,
421 ) {
422 (TransformResult::Modified, Some(candidate))
423 if regions.iter().any(|x| x == candidate) =>
424 {
425 candidate
426 }
427 _ => default_region,
428 },
429 );
430 result = TransformResult::Modified;
431 continue;
432 }
433 }
434 }
435
436 if !locale.id.variants.is_empty() {
437 let mut modified = Vec::with_capacity(0);
438 for (idx, &variant) in locale.id.variants.iter().enumerate() {
439 if let Some(&updated) = self
440 .aliases
441 .get()
442 .variant
443 .get(&variant.to_tinystr().to_unvalidated())
444 {
445 if modified.is_empty() {
446 modified = locale.id.variants.to_vec();
447 }
448 #[expect(clippy::indexing_slicing)]
449 let _ = core::mem::replace(&mut modified[idx], updated);
450 }
451 }
452
453 if !modified.is_empty() {
454 modified.sort();
455 modified.dedup();
456 locale.id.variants = Variants::from_vec_unchecked(modified);
457 result = TransformResult::Modified;
458 continue;
459 }
460 }
461
462 // Nothing matched in this iteration, we're done.
463 break;
464 }
465
466 if !locale.extensions.transform.is_empty() || !locale.extensions.unicode.is_empty() {
467 self.canonicalize_extensions(&mut locale.extensions, &mut result);
468 }
469 result
470 }
471
472 fn canonicalize_extensions(&self, extensions: &mut Extensions, result: &mut TransformResult) {
473 // Handle Locale extensions in their own loops, because these rules do not interact
474 // with each other.
475 if let Some(ref mut lang) = extensions.transform.lang {
476 while uts35_check_language_rules(lang, &self.aliases) == TransformResult::Modified {
477 *result = TransformResult::Modified;
478 }
479 }
480
481 if !extensions.unicode.keywords.is_empty() {
482 for key in [key!("rg"), key!("sd")] {
483 if let Some(value) = extensions.unicode.keywords.get_mut(&key)
484 && let Some(only_value) = value.as_single_subtag()
485 && let Some(modified_value) = self
486 .aliases
487 .get()
488 .subdivision
489 .get(&only_value.to_tinystr().resize().to_unvalidated())
490 && let Ok(modified_value) = modified_value.parse()
491 {
492 *value = modified_value;
493 *result = TransformResult::Modified;
494 }
495 }
496 }
497 }
498
499 fn canonicalize_language_variant_fallbacks(&self, lid: &mut LanguageIdentifier) -> bool {
500 // These language/variant comibnations have around 20 rules
501 for LanguageStrStrPair(lang, raw_variants, raw_to) in self
502 .aliases
503 .get()
504 .language_variants
505 .iter()
506 .map(zerofrom::ZeroFrom::zero_from)
507 {
508 let raw_variants = raw_variants.split('-');
509 // if is_iter_sorted(raw_variants.clone()) { // can we sort at construction?
510 if uts35_rule_matches(lid, lang, None, None, raw_variants.clone())
511 && let Ok(to) = raw_to.parse()
512 {
513 uts35_replacement(
514 lid,
515 !lang.is_unknown(),
516 false,
517 false,
518 Some(raw_variants),
519 &to,
520 );
521 return true;
522 }
523 }
524 false
525 }
526
527 fn canonicalize_absolute_language_fallbacks(&self, lid: &mut LanguageIdentifier) -> bool {
528 for StrStrPair(raw_from, raw_to) in self
529 .aliases
530 .get()
531 .language
532 .iter()
533 .map(zerofrom::ZeroFrom::zero_from)
534 {
535 if let Ok(from) = raw_from.parse::<LanguageIdentifier>()
536 && uts35_rule_matches(
537 lid,
538 from.language,
539 from.script,
540 from.region,
541 from.variants.iter().map(Variant::as_str),
542 )
543 && let Ok(to) = raw_to.parse()
544 {
545 uts35_replacement(
546 lid,
547 !from.language.is_unknown(),
548 from.script.is_some(),
549 from.region.is_some(),
550 Some(from.variants.iter().map(Variant::as_str)),
551 &to,
552 );
553 return true;
554 }
555 }
556 false
557 }
558 }
559
560 #[cfg(test)]
561 mod test {
562 use super::*;
563
564 #[test]
565 fn test_uts35_rule_matches() {
566 for (source, rule, result) in [
567 ("ja", "und", true),
568 ("und-heploc-hepburn", "und-hepburn", true),
569 ("ja-heploc-hepburn", "und-hepburn", true),
570 ("ja-hepburn", "und-hepburn-heploc", false),
571 ] {
572 let source = source.parse().unwrap();
573 let rule = rule.parse::<LanguageIdentifier>().unwrap();
574 assert_eq!(
575 uts35_rule_matches(
576 &source,
577 rule.language,
578 rule.script,
579 rule.region,
580 rule.variants.iter().map(Variant::as_str),
581 ),
582 result,
583 "{source}"
584 );
585 }
586 }
587
588 #[test]
589 fn test_uts35_replacement() {
590 for (locale, rule_0, rule_1, result) in [
591 (
592 "ja-Latn-fonipa-hepburn-heploc",
593 "und-hepburn-heploc",
594 "und-alalc97",
595 "ja-Latn-alalc97-fonipa",
596 ),
597 ("sgn-DD", "und-DD", "und-DE", "sgn-DE"),
598 ("sgn-DE", "sgn-DE", "gsg", "gsg"),
599 ] {
600 let mut locale: Locale = locale.parse().unwrap();
601 let rule_0 = rule_0.parse::<LanguageIdentifier>().unwrap();
602 let rule_1 = rule_1.parse().unwrap();
603 let result = result.parse::<Locale>().unwrap();
604 uts35_replacement(
605 &mut locale.id,
606 !rule_0.language.is_unknown(),
607 rule_0.script.is_some(),
608 rule_0.region.is_some(),
609 Some(rule_0.variants.iter().map(Variant::as_str)),
610 &rule_1,
611 );
612 assert_eq!(result, locale);
613 }
614 }
615 }