1use super::*;
8use alloc::format;
9use alloc::string::String;
10use alloc::vec;
11use alloc::vec::Vec;
12
13#[derive(Clone, Debug, PartialEq, Eq)]
14struct LangId {
15 lang: String,
16 script: Option<String>,
17 region: Option<String>,
18 variants: Vec<String>,
19}
20
21#[derive(Clone, Debug)]
22struct LocaleId {
23 base: LangId,
24 t_lang: Option<LangId>,
25 t_fields: Vec<(String, String)>,
26 u_attrs: Vec<String>,
27 u_keywords: Vec<(String, String)>,
28 other_exts: Vec<(char, Vec<String>)>,
29 private_use: Vec<String>,
30}
31
32fn is_alpha(s: &str) -> bool {
33 !s.is_empty() && s.bytes().all(|b| b.is_ascii_alphabetic())
34}
35
36fn is_alnum(s: &str) -> bool {
37 !s.is_empty() && s.bytes().all(|b| b.is_ascii_alphanumeric())
38}
39
40fn is_digit(s: &str) -> bool {
41 !s.is_empty() && s.bytes().all(|b| b.is_ascii_digit())
42}
43
44fn is_lang_subtag(s: &str) -> bool {
45 let n = s.len();
46 is_alpha(s) && ((2..=3).contains(&n) || (5..=8).contains(&n))
47}
48
49fn is_script_subtag(s: &str) -> bool {
50 s.len() == 4 && is_alpha(s)
51}
52
53fn is_region_subtag(s: &str) -> bool {
54 (s.len() == 2 && is_alpha(s)) || (s.len() == 3 && is_digit(s))
55}
56
57fn is_variant_subtag(s: &str) -> bool {
58 if !is_alnum(s) {
59 return false;
60 }
61 let first_digit = s.bytes().next().is_some_and(|b| b.is_ascii_digit());
62 (5..=8).contains(&s.len()) || (s.len() == 4 && first_digit)
63}
64
65fn is_type_subtag(s: &str) -> bool {
66 (3..=8).contains(&s.len()) && is_alnum(s)
67}
68
69fn is_ukey(s: &str) -> bool {
70 let mut b = s.bytes();
71 match (b.next(), b.next(), b.next()) {
72 (Some(a), Some(c), None) => a.is_ascii_alphanumeric() && c.is_ascii_alphabetic(),
73 _ => false,
74 }
75}
76
77fn is_tkey(s: &str) -> bool {
78 let mut b = s.bytes();
79 match (b.next(), b.next(), b.next()) {
80 (Some(a), Some(c), None) => a.is_ascii_alphabetic() && c.is_ascii_digit(),
81 _ => false,
82 }
83}
84
85fn titlecase(s: &str) -> String {
86 let mut c = s.to_ascii_lowercase();
87 if let Some(f) = c.get_mut(0..1) {
88 f.make_ascii_uppercase();
89 }
90 c
91}
92
93fn parse_lang_id(parts: &[&str], idx: &mut usize) -> Result<LangId, &'static str> {
94 let Some(&lang) = parts.get(*idx) else {
95 return Err("Missing language subtag");
96 };
97 if !is_lang_subtag(lang) {
98 return Err("Invalid language subtag");
99 }
100 *idx += 1;
101
102 let mut script = None;
103 if let Some(&p) = parts.get(*idx) {
104 if is_script_subtag(p) {
105 script = Some(titlecase(p));
106 *idx += 1;
107 }
108 }
109
110 let mut region = None;
111 if let Some(&p) = parts.get(*idx) {
112 if is_region_subtag(p) {
113 region = Some(p.to_ascii_uppercase());
114 *idx += 1;
115 }
116 }
117
118 let mut variants: Vec<String> = Vec::new();
119 while let Some(&p) = parts.get(*idx) {
120 if is_variant_subtag(p) {
121 let low = p.to_ascii_lowercase();
122 if variants.contains(&low) {
123 return Err("Duplicate variant subtag");
124 }
125 variants.push(low);
126 *idx += 1;
127 } else {
128 break;
129 }
130 }
131
132 Ok(LangId {
133 lang: lang.to_ascii_lowercase(),
134 script,
135 region,
136 variants,
137 })
138}
139
140fn parse_locale_id(s: &str) -> Result<LocaleId, &'static str> {
141 if s.is_empty() || !s.is_ascii() {
142 return Err("Invalid locale string");
143 }
144 let parts: Vec<&str> = s.split('-').collect();
145 if parts.iter().any(|p| p.is_empty()) {
146 return Err("Empty subtag in locale string");
147 }
148
149 let mut idx = 0usize;
150 let base = parse_lang_id(&parts, &mut idx)?;
151
152 let mut seen_singletons: Vec<char> = Vec::new();
153 let mut t_lang: Option<LangId> = None;
154 let mut t_fields: Vec<(String, String)> = Vec::new();
155 let mut u_attrs: Vec<String> = Vec::new();
156 let mut u_keywords: Vec<(String, String)> = Vec::new();
157 let mut other_exts: Vec<(char, Vec<String>)> = Vec::new();
158 let mut private_use: Vec<String> = Vec::new();
159
160 while let Some(&p) = parts.get(idx) {
161 if p.len() != 1 || !is_alnum(p) {
162 return Err("Unexpected subtag in locale string");
163 }
164 let singleton = p.bytes().next().unwrap_or(b' ').to_ascii_lowercase() as char;
165 idx += 1;
166
167 if singleton == 'x' {
168 if idx >= parts.len() {
169 return Err("Incomplete private-use subtag");
170 }
171 while let Some(&sub) = parts.get(idx) {
172 if !(1..=8).contains(&sub.len()) || !is_alnum(sub) {
173 return Err("Invalid private-use subtag");
174 }
175 private_use.push(sub.to_ascii_lowercase());
176 idx += 1;
177 }
178 break;
179 }
180
181 if seen_singletons.contains(&singleton) {
182 return Err("Duplicate extension singleton");
183 }
184 seen_singletons.push(singleton);
185
186 if singleton == 'u' {
187 let start = idx;
188 while let Some(&sub) = parts.get(idx) {
189 if sub.len() == 1 {
190 break;
191 }
192 if is_ukey(sub) {
193 let key = sub.to_ascii_lowercase();
194 idx += 1;
195 let mut val_parts: Vec<String> = Vec::new();
196 while let Some(&tp) = parts.get(idx) {
197 if tp.len() == 1 || is_ukey(tp) {
198 break;
199 }
200 if !is_type_subtag(tp) {
201 return Err("Invalid unicode extension type");
202 }
203 val_parts.push(tp.to_ascii_lowercase());
204 idx += 1;
205 }
206 let val = val_parts.join("-");
207 if !u_keywords.iter().any(|(k, _)| k == &key) {
208 u_keywords.push((key, val));
209 }
210 } else if is_type_subtag(sub) && u_keywords.is_empty() {
211 let attr = sub.to_ascii_lowercase();
212 if !u_attrs.contains(&attr) {
213 u_attrs.push(attr);
214 }
215 idx += 1;
216 } else {
217 return Err("Invalid unicode extension subtag");
218 }
219 }
220 if idx == start {
221 return Err("Empty unicode extension");
222 }
223 } else if singleton == 't' {
224 let start = idx;
225 if let Some(&sub) = parts.get(idx) {
226 if is_lang_subtag(sub) {
227 t_lang = Some(parse_lang_id(&parts, &mut idx)?);
228 }
229 }
230 while let Some(&sub) = parts.get(idx) {
231 if sub.len() == 1 {
232 break;
233 }
234 if !is_tkey(sub) {
235 return Err("Invalid transformed extension subtag");
236 }
237 let tkey = sub.to_ascii_lowercase();
238 idx += 1;
239 let mut val_parts: Vec<String> = Vec::new();
240 while let Some(&tp) = parts.get(idx) {
241 if tp.len() == 1 || is_tkey(tp) {
242 break;
243 }
244 if !is_type_subtag(tp) {
245 return Err("Invalid transformed extension value");
246 }
247 val_parts.push(tp.to_ascii_lowercase());
248 idx += 1;
249 }
250 if val_parts.is_empty() {
251 return Err("Missing transformed extension value");
252 }
253 if !t_fields.iter().any(|(k, _)| k == &tkey) {
254 t_fields.push((tkey, val_parts.join("-")));
255 }
256 }
257 if idx == start {
258 return Err("Empty transformed extension");
259 }
260 } else {
261 let start = idx;
262 let mut subtags: Vec<String> = Vec::new();
263 while let Some(&sub) = parts.get(idx) {
264 if sub.len() == 1 {
265 break;
266 }
267 if !(2..=8).contains(&sub.len()) || !is_alnum(sub) {
268 return Err("Invalid extension subtag");
269 }
270 subtags.push(sub.to_ascii_lowercase());
271 idx += 1;
272 }
273 if idx == start {
274 return Err("Empty extension");
275 }
276 other_exts.push((singleton, subtags));
277 }
278 }
279
280 Ok(LocaleId {
281 base,
282 t_lang,
283 t_fields,
284 u_attrs,
285 u_keywords,
286 other_exts,
287 private_use,
288 })
289}
290
291fn canonicalize_lang_alias(lang: &str) -> Option<&'static str> {
292 Some(match lang {
293 "aar" => "aa",
294 "ces" => "cs",
295 "cym" => "cy",
296 "deu" => "de",
297 "ell" => "el",
298 "eng" => "en",
299 "eus" => "eu",
300 "fas" => "fa",
301 "fra" => "fr",
302 "heb" => "he",
303 "hye" => "hy",
304 "in" => "id",
305 "isl" => "is",
306 "iw" => "he",
307 "ji" => "yi",
308 "jpn" => "ja",
309 "jw" => "jv",
310 "kat" => "ka",
311 "kor" => "ko",
312 "mkd" => "mk",
313 "mo" => "ro",
314 "mri" => "mi",
315 "msa" => "ms",
316 "mya" => "my",
317 "nld" => "nl",
318 "pol" => "pl",
319 "por" => "pt",
320 "ron" => "ro",
321 "rus" => "ru",
322 "slk" => "sk",
323 "spa" => "es",
324 "sqi" => "sq",
325 "swe" => "sv",
326 "tha" => "th",
327 "tur" => "tr",
328 "ukr" => "uk",
329 "vie" => "vi",
330 "zho" => "zh",
331 "prs" => "fa",
332 "sh" => "sr-Latn",
333 "scc" => "sr",
334 "scr" => "hr",
335 "no" => "nb",
336 "tl" => "fil",
337 "mol" => "ro",
338 _ => return None,
339 })
340}
341
342fn canonicalize_region_alias(region: &str, script: Option<&str>) -> Option<&'static str> {
343 Some(match region {
344 "SU" => {
345 if script == Some("Armn") {
346 "AM"
347 } else {
348 "RU"
349 }
350 }
351 "TP" => "TL",
352 "YU" => "RS",
353 "DD" => "DE",
354 "ZR" => "CD",
355 "BU" => "MM",
356 "CS" => "RS",
357 "UK" => "GB",
358 "FX" => "FR",
359 "RH" => "ZW",
360 "YD" => "YE",
361 "NH" => "VU",
362 "HV" => "BF",
363 "CT" => "KI",
364 "DY" => "BJ",
365 "FQ" => "AQ",
366 "JT" => "UM",
367 "MI" => "UM",
368 "NQ" => "AQ",
369 "PC" => "FM",
370 "PU" => "UM",
371 "PZ" => "PA",
372 "VD" => "VN",
373 "WK" => "UM",
374 "AN" => "CW",
375 "004" => "AF",
377 "036" => "AU",
378 "124" => "CA",
379 "156" => "CN",
380 "250" => "FR",
381 "276" => "DE",
382 "356" => "IN",
383 "380" => "IT",
384 "392" => "JP",
385 "410" => "KR",
386 "484" => "MX",
387 "528" => "NL",
388 "554" => "NZ",
389 "616" => "PL",
390 "643" => "RU",
391 "724" => "ES",
392 "752" => "SE",
393 "756" => "CH",
394 "764" => "TH",
395 "792" => "TR",
396 "826" => "GB",
397 "840" => "US",
398 _ => return None,
399 })
400}
401
402fn canonicalize_lang_id(lid: &mut LangId) {
403 lid.lang.make_ascii_lowercase();
404 if let Some(sc) = &mut lid.script {
405 *sc = titlecase(sc);
406 if sc == "Qaai" {
407 *sc = String::from("Zinh");
408 }
409 }
410 if let Some(rg) = &mut lid.region {
411 rg.make_ascii_uppercase();
412 if let Some(repl) = canonicalize_region_alias(rg, lid.script.as_deref()) {
413 *rg = String::from(repl);
414 }
415 }
416 for v in &mut lid.variants {
417 v.make_ascii_lowercase();
418 }
419 lid.variants.sort();
420 lid.variants.dedup();
421
422 let variant_rules: &[(&str, &str, &str)] = &[
424 ("art", "lojban", "jbo"),
425 ("cel", "gaulish", "xtg"),
426 ("zh", "guoyu", "zh"),
427 ("zh", "hakka", "hak"),
428 ("zh", "xiang", "hsn"),
429 ("hy", "arevela", "hy"),
430 ("hy", "arevmda", "hyw"),
431 ];
432 for &(l, var, repl) in variant_rules {
433 if lid.lang == l {
434 if let Some(pos) = lid.variants.iter().position(|x| x == var) {
435 lid.variants.remove(pos);
436 lid.lang = String::from(repl);
437 break;
438 }
439 }
440 }
441
442 if let Some(pos) = lid.variants.iter().position(|x| x == "heploc") {
443 lid.variants[pos] = String::from("alalc97");
444 lid.variants.sort();
445 lid.variants.dedup();
446 }
447
448 if let Some(repl) = canonicalize_lang_alias(&lid.lang) {
449 if let Some((nl, ns)) = repl.split_once('-') {
450 lid.lang = String::from(nl);
451 if lid.script.is_none() {
452 lid.script = Some(String::from(ns));
453 }
454 } else {
455 lid.lang = String::from(repl);
456 }
457 }
458}
459
460fn canonicalize_u_value(key: &str, val: &str) -> String {
461 let low = val.to_ascii_lowercase();
462 if low == "true" {
463 return String::new();
464 }
465 if low == "yes" && matches!(key, "kb" | "kc" | "kh" | "kk" | "kn") {
466 return String::new();
467 }
468 match (key, low.as_str()) {
469 ("ca", "islamicc") => String::from("islamic-civil"),
470 ("ca", "ethiopic-amete-alem") => String::from("ethioaa"),
471 ("kb" | "kc" | "kh" | "kk" | "kn", "no") => String::from("false"),
472 ("ks", "primary") => String::from("level1"),
473 ("ks", "secondary") => String::from("level2"),
474 ("ks", "tertiary") => String::from("level3"),
475 ("ks", "quaternary") => String::from("level4"),
476 ("ms", "imperial") => String::from("uksystem"),
477 ("tz", "cnsha") => String::from("cnhgh"),
478 ("tz", "cnckg") => String::from("cnsha"),
479 ("rg", "cn11") => String::from("cnbj"),
480 _ => low,
481 }
482}
483
484fn canonicalize_locale_id(loc: &mut LocaleId) {
485 canonicalize_lang_id(&mut loc.base);
486 if let Some(tl) = &mut loc.t_lang {
487 canonicalize_lang_id(tl);
488 }
489 loc.t_fields.sort_by(|a, b| a.0.cmp(&b.0));
490
491 loc.u_attrs.sort();
492 loc.u_attrs.dedup();
493 for (k, v) in &mut loc.u_keywords {
494 *v = canonicalize_u_value(k, v);
495 }
496 loc.u_keywords.sort_by(|a, b| a.0.cmp(&b.0));
497 loc.other_exts.sort_by_key(|a| a.0);
498}
499
500impl LangId {
501 fn format_to_string(&self) -> String {
502 let mut out = self.lang.clone();
503 if let Some(sc) = &self.script {
504 out.push('-');
505 out.push_str(sc);
506 }
507 if let Some(rg) = &self.region {
508 out.push('-');
509 out.push_str(rg);
510 }
511 for v in &self.variants {
512 out.push('-');
513 out.push_str(v);
514 }
515 out
516 }
517}
518
519impl LocaleId {
520 fn format_to_string(&self) -> String {
521 let mut out = self.base.format_to_string();
522 let mut ext_blocks: Vec<(char, String)> = Vec::new();
523 for (ch, subs) in &self.other_exts {
524 ext_blocks.push((*ch, format!("{}-{}", ch, subs.join("-"))));
525 }
526 if self.t_lang.is_some() || !self.t_fields.is_empty() {
527 let mut segs: Vec<String> = vec![String::from("t")];
528 if let Some(tl) = &self.t_lang {
529 segs.push(tl.format_to_string().to_ascii_lowercase());
530 }
531 for (k, v) in &self.t_fields {
532 segs.push(k.clone());
533 segs.push(v.clone());
534 }
535 ext_blocks.push(('t', segs.join("-")));
536 }
537 if !self.u_attrs.is_empty() || !self.u_keywords.is_empty() {
538 let mut segs: Vec<String> = vec![String::from("u")];
539 for attr in &self.u_attrs {
540 segs.push(attr.clone());
541 }
542 for (k, v) in &self.u_keywords {
543 segs.push(k.clone());
544 if !v.is_empty() {
545 segs.push(v.clone());
546 }
547 }
548 ext_blocks.push(('u', segs.join("-")));
549 }
550 ext_blocks.sort_by_key(|a| a.0);
551 for (_, blk) in ext_blocks {
552 out.push('-');
553 out.push_str(&blk);
554 }
555 if !self.private_use.is_empty() {
556 out.push_str("-x-");
557 out.push_str(&self.private_use.join("-"));
558 }
559 out
560 }
561
562 fn u_keyword(&self, key: &str) -> Option<&str> {
563 self.u_keywords
564 .iter()
565 .find(|(k, _)| k == key)
566 .map(|(_, v)| v.as_str())
567 }
568
569 fn set_u_keyword(&mut self, key: &str, val: String) {
570 let canon = canonicalize_u_value(key, &val);
571 if let Some(entry) = self.u_keywords.iter_mut().find(|(k, _)| k == key) {
572 entry.1 = canon;
573 } else {
574 self.u_keywords.push((String::from(key), canon));
575 self.u_keywords.sort_by(|a, b| a.0.cmp(&b.0));
576 }
577 }
578}
579
580const LIKELY_SUBTAGS: &[(&str, &str, &str, &str, &str, &str)] = &[
583 ("und", "", "", "en", "Latn", "US"),
585 ("und", "Latn", "", "en", "Latn", "US"),
586 ("und", "Arab", "", "ar", "Arab", "EG"),
587 ("und", "Armn", "", "hy", "Armn", "AM"),
588 ("und", "Beng", "", "bn", "Beng", "BD"),
589 ("und", "Cyrl", "", "ru", "Cyrl", "RU"),
590 ("und", "Deva", "", "hi", "Deva", "IN"),
591 ("und", "Ethi", "", "am", "Ethi", "ET"),
592 ("und", "Geor", "", "ka", "Geor", "GE"),
593 ("und", "Grek", "", "el", "Grek", "GR"),
594 ("und", "Gujr", "", "gu", "Gujr", "IN"),
595 ("und", "Guru", "", "pa", "Guru", "IN"),
596 ("und", "Hang", "", "ko", "Hang", "KR"),
597 ("und", "Hani", "", "zh", "Hani", "CN"),
598 ("und", "Hans", "", "zh", "Hans", "CN"),
599 ("und", "Hant", "", "zh", "Hant", "TW"),
600 ("und", "Hebr", "", "he", "Hebr", "IL"),
601 ("und", "Hira", "", "ja", "Hira", "JP"),
602 ("und", "Jpan", "", "ja", "Jpan", "JP"),
603 ("und", "Kana", "", "ja", "Kana", "JP"),
604 ("und", "Khmr", "", "km", "Khmr", "KH"),
605 ("und", "Knda", "", "kn", "Knda", "IN"),
606 ("und", "Kore", "", "ko", "Kore", "KR"),
607 ("und", "Laoo", "", "lo", "Laoo", "LA"),
608 ("und", "Mlym", "", "ml", "Mlym", "IN"),
609 ("und", "Mymr", "", "my", "Mymr", "MM"),
610 ("und", "Orya", "", "or", "Orya", "IN"),
611 ("und", "Sinh", "", "si", "Sinh", "LK"),
612 ("und", "Taml", "", "ta", "Taml", "IN"),
613 ("und", "Telu", "", "te", "Telu", "IN"),
614 ("und", "Thai", "", "th", "Thai", "TH"),
615 ("und", "Cyrl", "RO", "bg", "Cyrl", "RO"),
616 ("und", "", "001", "en", "Latn", "001"),
617 ("und", "", "150", "en", "Latn", "150"),
618 ("und", "", "419", "es", "Latn", "419"),
619 ("und", "", "AQ", "en", "Latn", "AQ"),
620 ("und", "", "AT", "de", "Latn", "AT"),
621 ("und", "", "AU", "en", "Latn", "AU"),
622 ("und", "", "BE", "nl", "Latn", "BE"),
623 ("und", "", "BR", "pt", "Latn", "BR"),
624 ("und", "", "CA", "en", "Latn", "CA"),
625 ("und", "", "CH", "de", "Latn", "CH"),
626 ("und", "", "CN", "zh", "Hans", "CN"),
627 ("und", "", "CW", "pap", "Latn", "CW"),
628 ("und", "", "CZ", "cs", "Latn", "CZ"),
629 ("und", "", "DE", "de", "Latn", "DE"),
630 ("und", "", "DK", "da", "Latn", "DK"),
631 ("und", "", "EG", "ar", "Arab", "EG"),
632 ("und", "", "ES", "es", "Latn", "ES"),
633 ("und", "", "FI", "fi", "Latn", "FI"),
634 ("und", "", "FR", "fr", "Latn", "FR"),
635 ("und", "", "GB", "en", "Latn", "GB"),
636 ("und", "", "GR", "el", "Grek", "GR"),
637 ("und", "", "HK", "zh", "Hant", "HK"),
638 ("und", "", "ID", "id", "Latn", "ID"),
639 ("und", "", "IL", "he", "Hebr", "IL"),
640 ("und", "", "IN", "hi", "Deva", "IN"),
641 ("und", "", "IR", "fa", "Arab", "IR"),
642 ("und", "", "IT", "it", "Latn", "IT"),
643 ("und", "", "JP", "ja", "Jpan", "JP"),
644 ("und", "", "KR", "ko", "Kore", "KR"),
645 ("und", "", "MX", "es", "Latn", "MX"),
646 ("und", "", "NL", "nl", "Latn", "NL"),
647 ("und", "", "NO", "nb", "Latn", "NO"),
648 ("und", "", "PL", "pl", "Latn", "PL"),
649 ("und", "", "PT", "pt", "Latn", "PT"),
650 ("und", "", "RO", "ro", "Latn", "RO"),
651 ("und", "", "RU", "ru", "Cyrl", "RU"),
652 ("und", "", "SA", "ar", "Arab", "SA"),
653 ("und", "", "SE", "sv", "Latn", "SE"),
654 ("und", "", "TH", "th", "Thai", "TH"),
655 ("und", "", "TR", "tr", "Latn", "TR"),
656 ("und", "", "TW", "zh", "Hant", "TW"),
657 ("und", "", "UA", "uk", "Cyrl", "UA"),
658 ("und", "", "US", "en", "Latn", "US"),
659 ("und", "", "VN", "vi", "Latn", "VN"),
660 ("aa", "", "", "aa", "Latn", "ET"),
662 ("aae", "", "", "aae", "Latn", "IT"),
663 ("af", "", "", "af", "Latn", "ZA"),
664 ("am", "", "", "am", "Ethi", "ET"),
665 ("ar", "", "", "ar", "Arab", "EG"),
666 ("az", "", "", "az", "Latn", "AZ"),
667 ("az", "Arab", "", "az", "Arab", "IR"),
668 ("az", "Cyrl", "", "az", "Cyrl", "AZ"),
669 ("be", "", "", "be", "Cyrl", "BY"),
670 ("bg", "", "", "bg", "Cyrl", "BG"),
671 ("bn", "", "", "bn", "Beng", "BD"),
672 ("bs", "", "", "bs", "Latn", "BA"),
673 ("bs", "Cyrl", "", "bs", "Cyrl", "BA"),
674 ("ca", "", "", "ca", "Latn", "ES"),
675 ("cs", "", "", "cs", "Latn", "CZ"),
676 ("cy", "", "", "cy", "Latn", "GB"),
677 ("da", "", "", "da", "Latn", "DK"),
678 ("de", "", "", "de", "Latn", "DE"),
679 ("el", "", "", "el", "Grek", "GR"),
680 ("en", "", "", "en", "Latn", "US"),
681 ("en", "Dsrt", "", "en", "Dsrt", "US"),
682 ("en", "Shaw", "", "en", "Shaw", "GB"),
683 ("es", "", "", "es", "Latn", "ES"),
684 ("et", "", "", "et", "Latn", "EE"),
685 ("eu", "", "", "eu", "Latn", "ES"),
686 ("fa", "", "", "fa", "Arab", "IR"),
687 ("fi", "", "", "fi", "Latn", "FI"),
688 ("fil", "", "", "fil", "Latn", "PH"),
689 ("fr", "", "", "fr", "Latn", "FR"),
690 ("ga", "", "", "ga", "Latn", "IE"),
691 ("gl", "", "", "gl", "Latn", "ES"),
692 ("gu", "", "", "gu", "Gujr", "IN"),
693 ("hak", "", "", "hak", "Hans", "CN"),
694 ("he", "", "", "he", "Hebr", "IL"),
695 ("hi", "", "", "hi", "Deva", "IN"),
696 ("hr", "", "", "hr", "Latn", "HR"),
697 ("hsn", "", "", "hsn", "Hans", "CN"),
698 ("hu", "", "", "hu", "Latn", "HU"),
699 ("hy", "", "", "hy", "Armn", "AM"),
700 ("hyw", "", "", "hyw", "Armn", "AM"),
701 ("id", "", "", "id", "Latn", "ID"),
702 ("is", "", "", "is", "Latn", "IS"),
703 ("it", "", "", "it", "Latn", "IT"),
704 ("ja", "", "", "ja", "Jpan", "JP"),
705 ("jbo", "", "", "jbo", "Latn", "001"),
706 ("ka", "", "", "ka", "Geor", "GE"),
707 ("kk", "", "", "kk", "Cyrl", "KZ"),
708 ("km", "", "", "km", "Khmr", "KH"),
709 ("kn", "", "", "kn", "Knda", "IN"),
710 ("ko", "", "", "ko", "Kore", "KR"),
711 ("ku", "", "", "ku", "Latn", "TR"),
712 ("ky", "", "", "ky", "Cyrl", "KG"),
713 ("lo", "", "", "lo", "Laoo", "LA"),
714 ("lt", "", "", "lt", "Latn", "LT"),
715 ("lv", "", "", "lv", "Latn", "LV"),
716 ("mi", "", "", "mi", "Latn", "NZ"),
717 ("mk", "", "", "mk", "Cyrl", "MK"),
718 ("ml", "", "", "ml", "Mlym", "IN"),
719 ("mn", "", "", "mn", "Cyrl", "MN"),
720 ("mr", "", "", "mr", "Deva", "IN"),
721 ("ms", "", "", "ms", "Latn", "MY"),
722 ("my", "", "", "my", "Mymr", "MM"),
723 ("nb", "", "", "nb", "Latn", "NO"),
724 ("ne", "", "", "ne", "Deva", "NP"),
725 ("nl", "", "", "nl", "Latn", "NL"),
726 ("nn", "", "", "nn", "Latn", "NO"),
727 ("pa", "", "", "pa", "Guru", "IN"),
728 ("pa", "Arab", "", "pa", "Arab", "PK"),
729 ("pa", "", "PK", "pa", "Arab", "PK"),
730 ("pap", "", "", "pap", "Latn", "CW"),
731 ("pl", "", "", "pl", "Latn", "PL"),
732 ("pt", "", "", "pt", "Latn", "BR"),
733 ("ro", "", "", "ro", "Latn", "RO"),
734 ("ru", "", "", "ru", "Cyrl", "RU"),
735 ("si", "", "", "si", "Sinh", "LK"),
736 ("sk", "", "", "sk", "Latn", "SK"),
737 ("sl", "", "", "sl", "Latn", "SI"),
738 ("sq", "", "", "sq", "Latn", "AL"),
739 ("sr", "", "", "sr", "Cyrl", "RS"),
740 ("sr", "Latn", "", "sr", "Latn", "RS"),
741 ("sv", "", "", "sv", "Latn", "SE"),
742 ("sw", "", "", "sw", "Latn", "TZ"),
743 ("ta", "", "", "ta", "Taml", "IN"),
744 ("te", "", "", "te", "Telu", "IN"),
745 ("th", "", "", "th", "Thai", "TH"),
746 ("tr", "", "", "tr", "Latn", "TR"),
747 ("uk", "", "", "uk", "Cyrl", "UA"),
748 ("ur", "", "", "ur", "Arab", "PK"),
749 ("uz", "", "", "uz", "Latn", "UZ"),
750 ("uz", "Arab", "", "uz", "Arab", "AF"),
751 ("uz", "Cyrl", "", "uz", "Cyrl", "UZ"),
752 ("vi", "", "", "vi", "Latn", "VN"),
753 ("xtg", "", "", "xtg", "", ""),
754 ("yi", "", "", "yi", "Hebr", "001"),
755 ("zh", "", "", "zh", "Hans", "CN"),
756 ("zh", "Hant", "", "zh", "Hant", "TW"),
757 ("zh", "", "HK", "zh", "Hant", "HK"),
758 ("zh", "", "MO", "zh", "Hant", "MO"),
759 ("zh", "", "TW", "zh", "Hant", "TW"),
760 ("zu", "", "", "zu", "Latn", "ZA"),
761];
762
763fn lookup_likely(lang: &str, script: &str, region: &str) -> Option<(&'static str, &'static str, &'static str)> {
764 for &(l, s, r, ol, os, or_) in LIKELY_SUBTAGS {
765 if l == lang && s == script && r == region {
766 return Some((ol, os, or_));
767 }
768 }
769 None
770}
771
772fn add_likely_subtags_lang(lid: &LangId) -> Option<LangId> {
773 let l = lid.lang.as_str();
774 let s = lid.script.as_deref().unwrap_or("");
775 let r = lid.region.as_deref().unwrap_or("");
776
777 if l != "und" && !s.is_empty() && !r.is_empty() {
778 return Some(lid.clone());
779 }
780
781 let matched = lookup_likely(l, s, r)
782 .or_else(|| if !s.is_empty() { lookup_likely(l, s, "") } else { None })
783 .or_else(|| if !r.is_empty() { lookup_likely(l, "", r) } else { None })
784 .or_else(|| if l != "und" { lookup_likely(l, "", "") } else { None })
785 .or_else(|| {
786 if l == "und" {
787 if !s.is_empty() {
788 lookup_likely("und", s, "")
789 } else {
790 None
791 }
792 .or_else(|| if !r.is_empty() { lookup_likely("und", "", r) } else { None })
793 .or_else(|| lookup_likely("und", "", ""))
794 } else {
795 None
796 }
797 });
798
799 let (ml, ms, mr) = matched?;
800 if ml.is_empty() || (ms.is_empty() && mr.is_empty()) {
801 return None;
802 }
803
804 let out_lang = if l != "und" { String::from(l) } else { String::from(ml) };
805 let out_script = if !s.is_empty() {
806 Some(String::from(s))
807 } else if !ms.is_empty() {
808 Some(String::from(ms))
809 } else {
810 None
811 };
812 let out_region = if !r.is_empty() {
813 Some(String::from(r))
814 } else if !mr.is_empty() {
815 Some(String::from(mr))
816 } else {
817 None
818 };
819
820 Some(LangId {
821 lang: out_lang,
822 script: out_script,
823 region: out_region,
824 variants: lid.variants.clone(),
825 })
826}
827
828fn remove_likely_subtags_lang(lid: &LangId) -> LangId {
829 let Some(max) = add_likely_subtags_lang(lid) else {
830 return lid.clone();
831 };
832 let trial1 = LangId {
833 lang: max.lang.clone(),
834 script: None,
835 region: None,
836 variants: lid.variants.clone(),
837 };
838 if add_likely_subtags_lang(&trial1).as_ref() == Some(&max) {
839 return trial1;
840 }
841 if max.region.is_some() {
842 let trial2 = LangId {
843 lang: max.lang.clone(),
844 script: None,
845 region: max.region.clone(),
846 variants: lid.variants.clone(),
847 };
848 if add_likely_subtags_lang(&trial2).as_ref() == Some(&max) {
849 return trial2;
850 }
851 }
852 if max.script.is_some() {
853 let trial3 = LangId {
854 lang: max.lang.clone(),
855 script: max.script.clone(),
856 region: None,
857 variants: lid.variants.clone(),
858 };
859 if add_likely_subtags_lang(&trial3).as_ref() == Some(&max) {
860 return trial3;
861 }
862 }
863 max
864}
865
866pub(crate) fn get_locale_slot(v: &Value) -> Option<String> {
869 let Value::Object(o) = v else { return None };
870 o.borrow()
871 .rare
872 .as_ref()
873 .and_then(|r| r.intl_locale.as_ref().map(|s| String::from(&**s)))
874}
875
876fn require_locale(it: &mut Interp, this: &Value, method: &str) -> Result<LocaleId, Value> {
877 let Some(tag) = get_locale_slot(this) else {
878 return Err(it.type_error(format!("Method {} called on incompatible receiver", method)));
879 };
880 parse_locale_id(&tag).map_err(|_| it.range_error("Invalid locale"))
881}
882
883fn get_string_option(
884 it: &mut Interp,
885 opts: &Value,
886 key: &str,
887 allowed: &[&str],
888) -> Result<Option<String>, Value> {
889 let v = match opts {
890 Value::Undefined => return Ok(None),
891 Value::Object(_) => it.get_property(opts, key)?,
892 _ => Value::Undefined,
893 };
894 if matches!(v, Value::Undefined) {
895 return Ok(None);
896 }
897 let s = it.to_string_value(v)?;
898 if !allowed.is_empty() && !allowed.contains(&s.as_str()) {
899 return Err(it.range_error(format!(
900 "Value {} out of range for Intl.Locale options property {}",
901 s, key
902 )));
903 }
904 Ok(Some(s))
905}
906
907fn get_bool_option(it: &mut Interp, opts: &Value, key: &str) -> Result<Option<bool>, Value> {
908 let v = match opts {
909 Value::Undefined => return Ok(None),
910 Value::Object(_) => it.get_property(opts, key)?,
911 _ => Value::Undefined,
912 };
913 if matches!(v, Value::Undefined) {
914 return Ok(None);
915 }
916 Ok(Some(v.truthy()))
917}
918
919fn is_unicode_type(s: &str) -> bool {
920 if s.is_empty() || !s.is_ascii() {
921 return false;
922 }
923 s.split('-').all(is_type_subtag)
924}
925
926fn weekday_to_uvalue(s: &str) -> &str {
927 match s {
928 "0" | "7" => "sun",
929 "1" => "mon",
930 "2" => "tue",
931 "3" => "wed",
932 "4" => "thu",
933 "5" => "fri",
934 "6" => "sat",
935 _ => s,
936 }
937}
938
939fn make_locale_object(it: &mut Interp, tag: String) -> Value {
940 let proto = it
941 .global
942 .borrow()
943 .vars
944 .get("Intl")
945 .and_then(|v| match v {
946 Value::Object(intl) => match intl.borrow().props.get("Locale") {
947 Some(Value::Object(ctor)) => match ctor.borrow().props.get("prototype") {
948 Some(Value::Object(p)) => Some(p.clone()),
949 _ => None,
950 },
951 _ => None,
952 },
953 _ => None,
954 });
955 let obj = Obj::plain();
956 {
957 let mut b = obj.borrow_mut();
958 b.proto = proto;
959 b.rare_data_mut().intl_locale = Some(Rc::from(tag));
960 }
961 Value::Object(obj)
962}
963
964pub(crate) fn canonicalize_unicode_locale_tag(tag: &str) -> Result<String, &'static str> {
965 let mut loc = parse_locale_id(tag)?;
966 canonicalize_locale_id(&mut loc);
967 Ok(loc.format_to_string())
968}
969
970pub(crate) struct TagParts {
972 pub base: String,
974 pub lang: String,
975 pub region: Option<String>,
976 pub u_keywords: Vec<(String, String)>,
978}
979
980pub(crate) fn split_tag(tag: &str) -> Option<TagParts> {
982 let loc = parse_locale_id(tag).ok()?;
983 Some(TagParts {
984 base: loc.base.format_to_string(),
985 lang: loc.base.lang.clone(),
986 region: loc.base.region.clone(),
987 u_keywords: loc.u_keywords,
988 })
989}
990
991pub(crate) fn canonicalize_u_keyword_value(key: &str, val: &str) -> String {
993 canonicalize_u_value(key, val)
994}
995
996pub(crate) fn is_unicode_type_sequence(s: &str) -> bool {
998 is_unicode_type(s)
999}
1000
1001pub(crate) fn canonicalize_language_id(s: &str) -> Option<String> {
1003 let mut loc = parse_locale_id(s).ok()?;
1004 if loc.t_lang.is_some()
1005 || !loc.t_fields.is_empty()
1006 || !loc.u_attrs.is_empty()
1007 || !loc.u_keywords.is_empty()
1008 || !loc.other_exts.is_empty()
1009 || !loc.private_use.is_empty()
1010 {
1011 return None;
1012 }
1013 canonicalize_locale_id(&mut loc);
1014 Some(loc.format_to_string())
1015}
1016
1017pub(crate) fn intl_locale_ctor(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
1020 let Some(nt) = it.take_pending_new_target() else {
1021 return Err(it.type_error("Constructor Intl.Locale requires 'new'"));
1022 };
1023
1024 let proto = if matches!(nt, Value::Object(_)) {
1026 match it.get_property(&nt, "prototype")? {
1027 Value::Object(p) => Some(p),
1028 _ => None,
1029 }
1030 } else {
1031 None
1032 };
1033
1034 let tag_arg = arg(a, 0);
1035 let tag_str = if let Some(slot_tag) = get_locale_slot(&tag_arg) {
1036 slot_tag
1037 } else {
1038 if tag_arg.type_of() == "symbol" {
1039 return Err(it.type_error("Cannot convert a Symbol value to a string"));
1040 }
1041 match &tag_arg {
1042 Value::Str(s) => String::from(&**s),
1043 Value::Object(_) => it.to_string_value(tag_arg)?,
1044 _ => return Err(it.type_error("First argument to Intl.Locale constructor must be a string or Locale object")),
1045 }
1046 };
1047
1048 let mut loc = parse_locale_id(&tag_str).map_err(|m| it.range_error(m))?;
1049 canonicalize_locale_id(&mut loc);
1050
1051 let opts_arg = arg(a, 1);
1052 let opts = match opts_arg {
1053 Value::Undefined => Value::Undefined,
1054 Value::Null => return Err(it.type_error("Cannot convert null to object")),
1055 Value::Object(_) => opts_arg,
1056 _ => {
1057 Value::Object(Obj::plain())
1059 }
1060 };
1061
1062 let opt_lang = get_string_option(it, &opts, "language", &[])?;
1065 if let Some(ref l) = opt_lang {
1066 if !is_lang_subtag(l) {
1067 return Err(it.range_error(format!("Invalid language option: {}", l)));
1068 }
1069 }
1070 let opt_script = get_string_option(it, &opts, "script", &[])?;
1071 if let Some(ref s) = opt_script {
1072 if !is_script_subtag(s) {
1073 return Err(it.range_error(format!("Invalid script option: {}", s)));
1074 }
1075 }
1076 let opt_region = get_string_option(it, &opts, "region", &[])?;
1077 if let Some(ref r) = opt_region {
1078 if !is_region_subtag(r) {
1079 return Err(it.range_error(format!("Invalid region option: {}", r)));
1080 }
1081 }
1082 let opt_variants = get_string_option(it, &opts, "variants", &[])?;
1083 let parsed_variants = if let Some(ref vs) = opt_variants {
1084 if vs.is_empty() || !vs.is_ascii() {
1085 return Err(it.range_error(format!("Invalid variants option: {}", vs)));
1086 }
1087 let parts: Vec<&str> = vs.split('-').collect();
1088 if parts.iter().any(|p| p.is_empty() || !is_variant_subtag(p)) {
1089 return Err(it.range_error(format!("Invalid variants option: {}", vs)));
1090 }
1091 let mut norm: Vec<String> = Vec::with_capacity(parts.len());
1092 for p in parts {
1093 let low = p.to_ascii_lowercase();
1094 if norm.contains(&low) {
1095 return Err(it.range_error(format!("Duplicate variant in options: {}", vs)));
1096 }
1097 norm.push(low);
1098 }
1099 Some(norm)
1100 } else {
1101 None
1102 };
1103
1104 let opt_ca = get_string_option(it, &opts, "calendar", &[])?;
1105 if let Some(ref c) = opt_ca {
1106 if !is_unicode_type(c) {
1107 return Err(it.range_error(format!("Invalid calendar option: {}", c)));
1108 }
1109 }
1110 let opt_co = get_string_option(it, &opts, "collation", &[])?;
1111 if let Some(ref c) = opt_co {
1112 if !is_unicode_type(c) {
1113 return Err(it.range_error(format!("Invalid collation option: {}", c)));
1114 }
1115 }
1116 let opt_fw = get_string_option(it, &opts, "firstDayOfWeek", &[])?.map(|raw| {
1117 String::from(weekday_to_uvalue(&raw))
1118 });
1119 if let Some(ref fw) = opt_fw {
1120 if !is_unicode_type(fw) {
1121 return Err(it.range_error(format!("Invalid firstDayOfWeek option: {}", fw)));
1122 }
1123 }
1124 let opt_hc = get_string_option(it, &opts, "hourCycle", &["h11", "h12", "h23", "h24"])?;
1125 let opt_kf = get_string_option(it, &opts, "caseFirst", &["upper", "lower", "false"])?;
1126 let opt_kn = get_bool_option(it, &opts, "numeric")?;
1127 let opt_nu = get_string_option(it, &opts, "numberingSystem", &[])?;
1128 if let Some(ref nu) = opt_nu {
1129 if !is_unicode_type(nu) {
1130 return Err(it.range_error(format!("Invalid numberingSystem option: {}", nu)));
1131 }
1132 }
1133
1134 if let Some(l) = opt_lang {
1136 loc.base.lang = l.to_ascii_lowercase();
1137 }
1138 if let Some(s) = opt_script {
1139 loc.base.script = Some(titlecase(&s));
1140 }
1141 if let Some(r) = opt_region {
1142 loc.base.region = Some(r.to_ascii_uppercase());
1143 }
1144 if let Some(vs) = parsed_variants {
1145 loc.base.variants = vs;
1146 }
1147
1148 if let Some(ca) = opt_ca {
1150 loc.set_u_keyword("ca", ca);
1151 }
1152 if let Some(co) = opt_co {
1153 loc.set_u_keyword("co", co);
1154 }
1155 if let Some(fw) = opt_fw {
1156 loc.set_u_keyword("fw", fw);
1157 }
1158 if let Some(hc) = opt_hc {
1159 loc.set_u_keyword("hc", hc);
1160 }
1161 if let Some(kf) = opt_kf {
1162 loc.set_u_keyword("kf", kf);
1163 }
1164 if let Some(kn) = opt_kn {
1165 loc.set_u_keyword("kn", String::from(if kn { "true" } else { "false" }));
1166 }
1167 if let Some(nu) = opt_nu {
1168 loc.set_u_keyword("nu", nu);
1169 }
1170
1171 canonicalize_locale_id(&mut loc);
1172 let final_tag = loc.format_to_string();
1173
1174 if let Value::Object(o) = &this {
1175 let mut b = o.borrow_mut();
1176 if let Some(p) = proto {
1177 b.proto = Some(p);
1178 }
1179 b.rare_data_mut().intl_locale = Some(Rc::from(final_tag));
1180 drop(b);
1181 return Ok(this);
1182 }
1183 Ok(make_locale_object(it, final_tag))
1184}
1185
1186fn locale_get_base_name(it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> {
1189 let loc = require_locale(it, &this, "get Intl.Locale.prototype.baseName")?;
1190 Ok(Value::str(loc.base.format_to_string()))
1191}
1192
1193fn locale_get_language(it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> {
1194 let loc = require_locale(it, &this, "get Intl.Locale.prototype.language")?;
1195 Ok(Value::str(loc.base.lang))
1196}
1197
1198fn locale_get_script(it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> {
1199 let loc = require_locale(it, &this, "get Intl.Locale.prototype.script")?;
1200 Ok(loc.base.script.map(Value::str).unwrap_or(Value::Undefined))
1201}
1202
1203fn locale_get_region(it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> {
1204 let loc = require_locale(it, &this, "get Intl.Locale.prototype.region")?;
1205 Ok(loc.base.region.map(Value::str).unwrap_or(Value::Undefined))
1206}
1207
1208fn locale_get_variants(it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> {
1209 let loc = require_locale(it, &this, "get Intl.Locale.prototype.variants")?;
1210 if loc.base.variants.is_empty() {
1211 Ok(Value::Undefined)
1212 } else {
1213 Ok(Value::str(loc.base.variants.join("-")))
1214 }
1215}
1216
1217fn locale_get_calendar(it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> {
1218 let loc = require_locale(it, &this, "get Intl.Locale.prototype.calendar")?;
1219 Ok(loc.u_keyword("ca").map(Value::str).unwrap_or(Value::Undefined))
1220}
1221
1222fn locale_get_case_first(it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> {
1223 let loc = require_locale(it, &this, "get Intl.Locale.prototype.caseFirst")?;
1224 Ok(loc.u_keyword("kf").map(Value::str).unwrap_or(Value::Undefined))
1225}
1226
1227fn locale_get_collation(it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> {
1228 let loc = require_locale(it, &this, "get Intl.Locale.prototype.collation")?;
1229 Ok(loc.u_keyword("co").map(Value::str).unwrap_or(Value::Undefined))
1230}
1231
1232fn locale_get_first_day_of_week(it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> {
1233 let loc = require_locale(it, &this, "get Intl.Locale.prototype.firstDayOfWeek")?;
1234 Ok(loc.u_keyword("fw").map(Value::str).unwrap_or(Value::Undefined))
1235}
1236
1237fn locale_get_hour_cycle(it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> {
1238 let loc = require_locale(it, &this, "get Intl.Locale.prototype.hourCycle")?;
1239 Ok(loc.u_keyword("hc").map(Value::str).unwrap_or(Value::Undefined))
1240}
1241
1242fn locale_get_numbering_system(it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> {
1243 let loc = require_locale(it, &this, "get Intl.Locale.prototype.numberingSystem")?;
1244 Ok(loc.u_keyword("nu").map(Value::str).unwrap_or(Value::Undefined))
1245}
1246
1247fn locale_get_numeric(it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> {
1248 let loc = require_locale(it, &this, "get Intl.Locale.prototype.numeric")?;
1249 let val = matches!(loc.u_keyword("kn"), Some(""));
1250 Ok(Value::Bool(val))
1251}
1252
1253fn locale_to_string(it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> {
1256 let Some(tag) = get_locale_slot(&this) else {
1257 return Err(it.type_error("Method Intl.Locale.prototype.toString called on incompatible receiver"));
1258 };
1259 Ok(Value::str(tag))
1260}
1261
1262fn locale_maximize(it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> {
1263 let mut loc = require_locale(it, &this, "Intl.Locale.prototype.maximize")?;
1264 if let Some(max_base) = add_likely_subtags_lang(&loc.base) {
1265 loc.base = max_base;
1266 }
1267 Ok(make_locale_object(it, loc.format_to_string()))
1268}
1269
1270fn locale_minimize(it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> {
1271 let mut loc = require_locale(it, &this, "Intl.Locale.prototype.minimize")?;
1272 loc.base = remove_likely_subtags_lang(&loc.base);
1273 Ok(make_locale_object(it, loc.format_to_string()))
1274}
1275
1276fn effective_region(loc: &LocaleId) -> Option<String> {
1279 if let Some(rg) = loc.u_keyword("rg") {
1280 if rg.len() >= 2 {
1281 if let Some(sub) = rg.get(0..2) {
1282 if is_alpha(sub) {
1283 return Some(sub.to_ascii_uppercase());
1284 }
1285 }
1286 }
1287 }
1288 if let Some(r) = &loc.base.region {
1289 return Some(r.clone());
1290 }
1291 if let Some(sd) = loc.u_keyword("sd") {
1292 if sd.len() >= 2 {
1293 if let Some(sub) = sd.get(0..2) {
1294 if is_alpha(sub) {
1295 return Some(sub.to_ascii_uppercase());
1296 }
1297 }
1298 }
1299 }
1300 add_likely_subtags_lang(&loc.base).and_then(|m| m.region)
1301}
1302
1303fn locale_get_calendars(it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> {
1304 let loc = require_locale(it, &this, "Intl.Locale.prototype.getCalendars")?;
1305 let mut cals: Vec<&str> = Vec::new();
1306 if let Some(ca) = loc.u_keyword("ca") {
1307 if !ca.is_empty() {
1308 let arr = Obj::array(vec![Value::str(ca)]);
1309 return Ok(Value::Object(arr));
1310 }
1311 }
1312 let region = effective_region(&loc);
1313 match region.as_deref() {
1314 Some("JP") => cals.extend_from_slice(&["gregory", "japanese"]),
1315 Some("TH") => cals.extend_from_slice(&["buddhist", "gregory"]),
1316 Some("TW") => cals.extend_from_slice(&["gregory", "roc", "chinese"]),
1317 Some("SA") => cals.extend_from_slice(&["islamic-umalqura", "gregory", "islamic-rgsa"]),
1318 Some("IR") | Some("AF") => cals.extend_from_slice(&["persian", "gregory", "islamic"]),
1319 Some("IL") => cals.extend_from_slice(&["gregory", "hebrew"]),
1320 Some("ET") => cals.extend_from_slice(&["gregory", "ethiopic"]),
1321 _ => cals.push("gregory"),
1322 }
1323 Ok(Value::Object(Obj::array(cals.into_iter().map(Value::str).collect())))
1324}
1325
1326fn locale_get_collations(it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> {
1327 let loc = require_locale(it, &this, "Intl.Locale.prototype.getCollations")?;
1328 if let Some(co) = loc.u_keyword("co") {
1329 return Ok(Value::Object(Obj::array(vec![Value::str(co)])));
1330 }
1331 let list: &[&str] = match loc.base.lang.as_str() {
1332 "zh" => &["emoji", "eor", "pinyin", "stroke", "zhuyin"],
1333 "ja" => &["emoji", "eor", "unihan"],
1334 "de" => &["emoji", "eor", "phonebk"],
1335 "es" => &["emoji", "eor", "traditional"],
1336 _ => &["emoji", "eor"],
1337 };
1338 Ok(Value::Object(Obj::array(list.iter().copied().map(Value::str).collect())))
1339}
1340
1341fn locale_get_hour_cycles(it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> {
1342 let loc = require_locale(it, &this, "Intl.Locale.prototype.getHourCycles")?;
1343 if let Some(hc) = loc.u_keyword("hc") {
1344 if matches!(hc, "h11" | "h12" | "h23" | "h24") {
1345 return Ok(Value::Object(Obj::array(vec![Value::str(hc)])));
1346 }
1347 }
1348 let region = effective_region(&loc);
1349 let hcs: &[&str] = match (loc.base.lang.as_str(), region.as_deref()) {
1350 ("fr", Some("CA")) => &["h23"],
1351 ("en", Some("001")) => &["h12"],
1352 (_, Some("US") | Some("CA") | Some("AU") | Some("PH") | Some("IN")) => &["h12"],
1353 (_, Some("JP")) => &["h23", "h11"],
1354 _ => &["h23"],
1355 };
1356 Ok(Value::Object(Obj::array(hcs.iter().copied().map(Value::str).collect())))
1357}
1358
1359fn locale_get_numbering_systems(it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> {
1360 let loc = require_locale(it, &this, "Intl.Locale.prototype.getNumberingSystems")?;
1361 if let Some(nu) = loc.u_keyword("nu") {
1362 return Ok(Value::Object(Obj::array(vec![Value::str(nu)])));
1363 }
1364 let nus: &[&str] = match loc.base.lang.as_str() {
1365 "ar" => &["arab", "latn"],
1366 "fa" | "ps" => &["arabext", "latn"],
1367 "bn" => &["beng"],
1368 "th" => &["latn", "thai"],
1369 _ => &["latn"],
1370 };
1371 Ok(Value::Object(Obj::array(nus.iter().copied().map(Value::str).collect())))
1372}
1373
1374fn locale_get_text_info(it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> {
1375 let loc = require_locale(it, &this, "Intl.Locale.prototype.getTextInfo")?;
1376 let script = loc
1377 .base
1378 .script
1379 .clone()
1380 .or_else(|| add_likely_subtags_lang(&loc.base).and_then(|m| m.script));
1381 let dir = match script.as_deref() {
1382 Some("Zyyy" | "Zinh" | "Zzzz" | "Brai" | "Zxxx") => None,
1383 Some(
1384 "Arab" | "Aran" | "Hebr" | "Syrc" | "Thaa" | "Nkoo" | "Adlm" | "Samr" | "Mand"
1385 | "Mend" | "Rohg" | "Yezi" | "Armi" | "Avst" | "Chrs" | "Egyp" | "Elym" | "Hatr"
1386 | "Khar" | "Lydi" | "Mani" | "Merc" | "Mero" | "Narb" | "Nbat" | "Orkh" | "Palm"
1387 | "Phli" | "Phlp" | "Phnx" | "Prti" | "Sarb" | "Sogd" | "Sogo" | "Hung" | "Garay",
1388 ) => Some("rtl"),
1389 Some(sc) if is_script_subtag(sc) => {
1390 if matches!(
1392 sc,
1393 "Latn" | "Cyrl" | "Grek" | "Armn" | "Geor" | "Hans" | "Hant" | "Hani" | "Jpan"
1394 | "Hira" | "Kana" | "Hang" | "Kore" | "Deva" | "Beng" | "Guru" | "Gujr" | "Orya"
1395 | "Taml" | "Telu" | "Knda" | "Mlym" | "Sinh" | "Thai" | "Laoo" | "Tibt" | "Mymr"
1396 | "Khmr" | "Ethi" | "Cher" | "Cans" | "Ogam" | "Runr" | "Tglg" | "Dsrt" | "Shaw"
1397 ) {
1398 Some("ltr")
1399 } else {
1400 None
1401 }
1402 }
1403 _ => None,
1404 };
1405 let obj = Obj::plain();
1406 if let Some(d) = dir {
1407 obj.borrow_mut().props.insert("direction".into(), Value::str(d));
1408 } else {
1409 obj.borrow_mut().props.insert("direction".into(), Value::Undefined);
1410 }
1411 Ok(Value::Object(obj))
1412}
1413
1414fn locale_get_time_zones(it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> {
1415 let loc = require_locale(it, &this, "Intl.Locale.prototype.getTimeZones")?;
1416 let Some(region) = loc.base.region.as_deref() else {
1417 return Ok(Value::Undefined);
1418 };
1419 let tzs: &[&str] = match region {
1420 "US" => &[
1421 "America/Adak",
1422 "America/Anchorage",
1423 "America/Boise",
1424 "America/Chicago",
1425 "America/Denver",
1426 "America/Detroit",
1427 "America/Los_Angeles",
1428 "America/New_York",
1429 "America/Phoenix",
1430 "Pacific/Honolulu",
1431 ],
1432 "JP" => &["Asia/Tokyo"],
1433 "GB" => &["Europe/London"],
1434 "DE" => &["Europe/Berlin", "Europe/Busingen"],
1435 "FR" => &["Europe/Paris"],
1436 "CN" => &["Asia/Shanghai", "Asia/Urumqi"],
1437 "KR" => &["Asia/Seoul"],
1438 "TW" => &["Asia/Taipei"],
1439 "CA" => &[
1440 "America/Edmonton",
1441 "America/Halifax",
1442 "America/St_Johns",
1443 "America/Toronto",
1444 "America/Vancouver",
1445 "America/Winnipeg",
1446 ],
1447 "AU" => &[
1448 "Australia/Adelaide",
1449 "Australia/Brisbane",
1450 "Australia/Darwin",
1451 "Australia/Hobart",
1452 "Australia/Melbourne",
1453 "Australia/Perth",
1454 "Australia/Sydney",
1455 ],
1456 "IN" => &["Asia/Calcutta"],
1457 "RU" => &["Asia/Vladivostok", "Asia/Yekaterinburg", "Europe/Moscow"],
1458 "BR" => &["America/Manaus", "America/Sao_Paulo"],
1459 "ES" => &["Atlantic/Canary", "Europe/Madrid"],
1460 "IT" => &["Europe/Rome"],
1461 "NL" => &["Europe/Amsterdam"],
1462 "SE" => &["Europe/Stockholm"],
1463 "CH" => &["Europe/Zurich"],
1464 "AT" => &["Europe/Vienna"],
1465 "RO" => &["Europe/Bucharest"],
1466 "BG" => &["Europe/Sofia"],
1467 "IL" => &["Asia/Jerusalem"],
1468 "SA" => &["Asia/Riyadh"],
1469 "IR" => &["Asia/Tehran"],
1470 "EG" => &["Africa/Cairo"],
1471 "TH" => &["Asia/Bangkok"],
1472 "VN" => &["Asia/Saigon"],
1473 "ID" => &["Asia/Jakarta", "Asia/Makassar", "Asia/Jayapura"],
1474 _ => return Ok(Value::Undefined),
1475 };
1476 Ok(Value::Object(Obj::array(tzs.iter().copied().map(Value::str).collect())))
1477}
1478
1479fn locale_get_week_info(it: &mut Interp, this: Value, _a: &[Value]) -> Result<Value, Value> {
1480 let loc = require_locale(it, &this, "Intl.Locale.prototype.getWeekInfo")?;
1481 let region = effective_region(&loc);
1482 let (mut first_day, weekend): (u8, &[u8]) = match region.as_deref() {
1483 Some("US") | Some("CA") | Some("JP") | Some("BR") | Some("CN") | Some("TW")
1484 | Some("HK") | Some("MO") | Some("KR") | Some("MX") | Some("TH")
1485 | Some("SG") | Some("PH") | Some("ID") | Some("ZA") => (7, &[6, 7]),
1486 Some("IN") => (7, &[7]),
1487 Some("IL") => (7, &[5, 6]),
1488 Some("SA") | Some("AE") | Some("EG") | Some("KW") | Some("QA") | Some("BH")
1489 | Some("OM") | Some("JO") | Some("DZ") | Some("SD") | Some("SY") | Some("YE")
1490 | Some("IQ") | Some("LY") => (7, &[5, 6]),
1491 Some("AF") => (6, &[4, 5]),
1492 Some("IR") => (6, &[5]),
1493 Some("BD") => (7, &[5, 6]),
1494 _ => (1, &[6, 7]),
1495 };
1496
1497 if let Some(fw) = loc.u_keyword("fw") {
1498 match fw {
1499 "mon" => first_day = 1,
1500 "tue" => first_day = 2,
1501 "wed" => first_day = 3,
1502 "thu" => first_day = 4,
1503 "fri" => first_day = 5,
1504 "sat" => first_day = 6,
1505 "sun" => first_day = 7,
1506 _ => {}
1507 }
1508 }
1509
1510 let obj = Obj::plain();
1511 {
1512 let mut b = obj.borrow_mut();
1513 b.props.insert("firstDay".into(), Value::Number(first_day as f64));
1514 let we = Obj::array(weekend.iter().map(|&d| Value::Number(d as f64)).collect());
1515 b.props.insert("weekend".into(), Value::Object(we));
1516 }
1517 Ok(Value::Object(obj))
1518}
1519
1520pub(crate) fn create_intl_locale_constructor() -> Value {
1523 let proto = Obj::plain();
1524 let acc_attr = PropertyAttributes {
1525 writable: false,
1526 enumerable: false,
1527 configurable: true,
1528 };
1529 let method_attr = PropertyAttributes {
1530 writable: true,
1531 enumerable: false,
1532 configurable: true,
1533 };
1534
1535 let getters: &[(&str, &str, NativeFn)] = &[
1536 ("baseName", "get baseName", locale_get_base_name),
1537 ("language", "get language", locale_get_language),
1538 ("script", "get script", locale_get_script),
1539 ("region", "get region", locale_get_region),
1540 ("variants", "get variants", locale_get_variants),
1541 ("calendar", "get calendar", locale_get_calendar),
1542 ("caseFirst", "get caseFirst", locale_get_case_first),
1543 ("collation", "get collation", locale_get_collation),
1544 ("firstDayOfWeek", "get firstDayOfWeek", locale_get_first_day_of_week),
1545 ("hourCycle", "get hourCycle", locale_get_hour_cycle),
1546 ("numberingSystem", "get numberingSystem", locale_get_numbering_system),
1547 ("numeric", "get numeric", locale_get_numeric),
1548 ];
1549
1550 let methods: &[(&str, &str, NativeFn)] = &[
1551 ("maximize", "Intl.Locale.prototype.maximize", locale_maximize),
1552 ("minimize", "Intl.Locale.prototype.minimize", locale_minimize),
1553 ("toString", "Intl.Locale.prototype.toString", locale_to_string),
1554 ("getCalendars", "Intl.Locale.prototype.getCalendars", locale_get_calendars),
1555 ("getCollations", "Intl.Locale.prototype.getCollations", locale_get_collations),
1556 ("getHourCycles", "Intl.Locale.prototype.getHourCycles", locale_get_hour_cycles),
1557 ("getNumberingSystems", "Intl.Locale.prototype.getNumberingSystems", locale_get_numbering_systems),
1558 ("getTextInfo", "Intl.Locale.prototype.getTextInfo", locale_get_text_info),
1559 ("getTimeZones", "Intl.Locale.prototype.getTimeZones", locale_get_time_zones),
1560 ("getWeekInfo", "Intl.Locale.prototype.getWeekInfo", locale_get_week_info),
1561 ];
1562
1563 let ctor = Obj::native("Intl.Locale", intl_locale_ctor);
1564 {
1565 let mut pb = proto.borrow_mut();
1566 for &(prop, fn_name, func) in getters {
1567 pb.insert_accessor(
1568 prop,
1569 Accessor {
1570 get: Some(nv(fn_name, func)),
1571 set: None,
1572 },
1573 );
1574 pb.insert_attr(prop, acc_attr);
1575 }
1576 for &(prop, fn_name, func) in methods {
1577 pb.props.insert(prop.into(), nv(fn_name, func));
1578 pb.insert_attr(prop, method_attr);
1579 }
1580 pb.props.insert("Symbol(Symbol.toStringTag)".into(), Value::str("Intl.Locale"));
1581 pb.insert_attr("Symbol(Symbol.toStringTag)", acc_attr);
1582 pb.props.insert("constructor".into(), Value::Object(ctor.clone()));
1583 pb.insert_attr("constructor", method_attr);
1584 }
1585
1586 {
1587 let mut cb = ctor.borrow_mut();
1588 cb.props.insert("prototype".into(), Value::Object(proto));
1589 cb.insert_attr(
1590 "prototype",
1591 PropertyAttributes {
1592 writable: false,
1593 enumerable: false,
1594 configurable: false,
1595 },
1596 );
1597 }
1598 Value::Object(ctor)
1599}