"""Writes locales.rs from CLDR's JSON release: the languages with plural rules and every locale's percent affixes. Usage: locales.py """ import json import re import sys import zipfile def rust(s): return '"' + "".join(c if " " <= c <= "~" and c not in '"\\' else f"\\u{{{ord(c):x}}}" for c in s) + '"' def affixes(numbers, numsys): pattern = numbers[f"percentFormats-numberSystem-{numsys}"]["standard"].split(";")[0].replace("'", "") sign = numbers[f"symbols-numberSystem-{numsys}"]["percentSign"] number = re.search(r"[#0,.]+", pattern) return pattern[: number.start()].replace("%", sign), pattern[number.end() :].replace("%", sign) def main(): path, version = sys.argv[1], sys.argv[2] found = {} with zipfile.ZipFile(path) as z: plurals = json.loads(z.read("cldr-core/supplemental/plurals.json"))["supplemental"]["plurals-type-cardinal"] languages = sorted(l for l in plurals if l != "root" and "-" not in l) for name in z.namelist(): m = re.fullmatch(r"cldr-numbers-full/main/([^/]+)/numbers\.json", name) if not m or m.group(1) == "root": continue locale = m.group(1) numbers = json.loads(z.read(name))["main"][locale]["numbers"] found[(locale, True)] = affixes(numbers, "latn") default = numbers["defaultNumberingSystem"] if default != "latn": found[(locale, False)] = affixes(numbers, default) # Kept only where the lookup by dropping trailing subtags would find something else. kept = {} for (locale, latin), value in sorted(found.items(), key=lambda e: (e[0][0].count("-"), e[0])): parts = locale.split("-") inherited = ("", "%") for n in range(len(parts) - 1, 0, -1): if ("-".join(parts[:n]), latin) in kept: inherited = kept[("-".join(parts[:n]), latin)] break if value != inherited: kept[(locale, latin)] = value print(f"// @generated by generate.sh from Unicode CLDR {version} (Unicode License).") print() print("/// The languages CLDR has plural rules for; the baked data has them all.") print("pub(crate) const PLURAL_LANGUAGES: &[&str] = &[") for i in range(0, len(languages), 16): print(" " + ", ".join(rust(l) for l in languages[i : i + 16]) + ",") print("];") print() print("/// Percent signs around the number (CLDR's standard percent pattern and sign): locale, Latin") print("/// digits or the locale's own, text before the number, text after it. A locale missing here") print("/// takes its parent's by dropping trailing subtags, then `{n}%`.") print("pub(crate) const PERCENT: &[(&str, bool, &str, &str)] = &[") for (locale, latin), (before, after) in sorted(kept.items()): print(f" ({rust(locale)}, {str(latin).lower()}, {rust(before)}, {rust(after)}),") print("];") main()