Switch from Asuka to MyGo, keeping the API client and the feature set: - servers: saved servers, passwordless and password login, proxy, self-signed certificates, per-server device tokens (Keystore), connect form, instance list sheet with switch/disconnect - sessions: virtualized list, search, new session, rename/archive/delete, running indicator, event stream keeps it live - chat: pushed window with system back bar, streaming Markdown via ui/markdown, reasoning and tool rows with image previews, footer menu (read aloud via a Kotlin TTS plugin, copy, fork), user message menu (copy, revert, fork), context usage ring and detail sheet, attachments (photos/files via the document picker), permissions - release builds allow plain http:// LAN servers (Go's net/http dials directly, no cleartext manifest needed) - a local fork of MyGo (third_party/mygo) lowers the Android host's minSdk to 24 (Android 7.0); Go 1.27.4 via mise Version 0.3.0.
506 lines
15 KiB
Go
506 lines
15 KiB
Go
// Command gen writes the data of the Unicode CLDR that package i18n uses,
|
|
// from a pinned release of cldr-json, as Go source: `go generate ./i18n`
|
|
// runs it. It writes tables.go, the plural rules of every language
|
|
// compiled to Go and the parent locales; testdata/plural_samples.txt, the
|
|
// samples CLDR gives of each plural category, which the tests check the
|
|
// compiled rules against; and format_tables.go, what formatting numbers
|
|
// and dates needs of the locales of CLDR's modern coverage (format.go),
|
|
// and relative_tables.go, the patterns of relative times (relative.go).
|
|
//
|
|
// The data comes from the npm packages of cldr-json (cldr-core,
|
|
// cldr-dates-full, cldr-numbers-full and cldr-localenames-full), each
|
|
// checked against its SHA-256: no network data reaches the tables
|
|
// unchecked, and generating them again gives the same files.
|
|
package main
|
|
|
|
import (
|
|
"archive/tar"
|
|
"bytes"
|
|
"compress/gzip"
|
|
"crypto/sha256"
|
|
"encoding/hex"
|
|
"encoding/json"
|
|
"flag"
|
|
"fmt"
|
|
"go/format"
|
|
"io"
|
|
"log"
|
|
"net/http"
|
|
"os"
|
|
"path/filepath"
|
|
"slices"
|
|
"strconv"
|
|
"strings"
|
|
)
|
|
|
|
// The release of CLDR the tables are generated from.
|
|
const cldrVersion = "48.2.0"
|
|
|
|
// cldrPackage is an npm package of cldr-json, pinned by its SHA-256.
|
|
type cldrPackage struct {
|
|
name string
|
|
sha256 string
|
|
}
|
|
|
|
var (
|
|
corePackage = cldrPackage{"cldr-core", "5310e0c7a06c1feb83dc8e54c8584bbe0b9c2ea8320172a18d541986b124585d"}
|
|
datesPackage = cldrPackage{"cldr-dates-full", "0256f1cefeca14f7d515be4872dda48fcdd7e75381430f25aafd0143eae5b430"}
|
|
numbersPackage = cldrPackage{"cldr-numbers-full", "2d17a1453c559a62112caeed52e0bcfe3cb8539c99d239ae7b7ed4d0827679d9"}
|
|
localeNamesPackage = cldrPackage{"cldr-localenames-full", "7f2ac7fd3b5d90f56ad127f9ed5ae67b58b3e556818f55530b9f47bb81bcde57"}
|
|
)
|
|
|
|
func (p cldrPackage) url() string {
|
|
return "https://registry.npmjs.org/" + p.name + "/-/" + p.name + "-" + cldrVersion + ".tgz"
|
|
}
|
|
|
|
func main() {
|
|
log.SetFlags(0)
|
|
log.SetPrefix("gen: ")
|
|
out := flag.String("o", ".", "the directory of package i18n")
|
|
cache := flag.String("cache", "", "a directory of local copies of the tarballs, <name>-<version>.tgz (default: download them)")
|
|
flag.Parse()
|
|
|
|
core, err := readPackage(corePackage, *cache, nil)
|
|
if err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
var plurals struct {
|
|
Supplemental struct {
|
|
Cardinal map[string]map[string]string `json:"plurals-type-cardinal"`
|
|
} `json:"supplemental"`
|
|
}
|
|
var ordinals struct {
|
|
Supplemental struct {
|
|
Ordinal map[string]map[string]string `json:"plurals-type-ordinal"`
|
|
} `json:"supplemental"`
|
|
}
|
|
var parents struct {
|
|
Supplemental struct {
|
|
ParentLocales struct {
|
|
ParentLocale map[string]string `json:"parentLocale"`
|
|
Rules struct {
|
|
ParentLocale map[string]string `json:"parentLocale"`
|
|
} `json:"_localeRules"`
|
|
} `json:"parentLocales"`
|
|
} `json:"supplemental"`
|
|
}
|
|
for name, v := range map[string]any{
|
|
"supplemental/plurals.json": &plurals,
|
|
"supplemental/ordinals.json": &ordinals,
|
|
"supplemental/parentLocales.json": &parents,
|
|
} {
|
|
data, ok := core[name]
|
|
if !ok {
|
|
log.Fatalf("cldr-core has no %s", name)
|
|
}
|
|
if err := json.Unmarshal(data, v); err != nil {
|
|
log.Fatalf("%s: %v", name, err)
|
|
}
|
|
}
|
|
if r := parents.Supplemental.ParentLocales.Rules.ParentLocale; r["nonlikelyScript"] != "root" {
|
|
log.Fatalf("parentLocales: the rule for scripts other than the likely one changed: %v", r)
|
|
}
|
|
|
|
var b bytes.Buffer
|
|
fmt.Fprintf(&b, `// Code generated by go generate (i18n/internal/gen) from CLDR %s. DO NOT EDIT.
|
|
|
|
package i18n
|
|
|
|
// CLDRVersion is the release of the Unicode CLDR the data of the package
|
|
// comes from.
|
|
const CLDRVersion = %q
|
|
|
|
`, cldrVersion, cldrVersion)
|
|
var samples bytes.Buffer
|
|
fmt.Fprintf(&samples, "# The samples of the plural categories of CLDR %s, which TestPluralSamples\n# checks the rules against: kind, languages, category, samples.\n", cldrVersion)
|
|
for _, kind := range []struct {
|
|
name string
|
|
rules map[string]map[string]string
|
|
}{
|
|
{"cardinal", plurals.Supplemental.Cardinal},
|
|
{"ordinal", ordinals.Supplemental.Ordinal},
|
|
} {
|
|
if err := writeRules(&b, &samples, kind.name, kind.rules); err != nil {
|
|
log.Fatalf("%s rules: %v", kind.name, err)
|
|
}
|
|
}
|
|
writeParents(&b, parents.Supplemental.ParentLocales.ParentLocale)
|
|
|
|
src, err := format.Source(b.Bytes())
|
|
if err != nil {
|
|
log.Fatalf("formatting tables.go: %v\n%s", err, b.Bytes())
|
|
}
|
|
if err := os.WriteFile(filepath.Join(*out, "tables.go"), src, 0o644); err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
if err := os.MkdirAll(filepath.Join(*out, "testdata"), 0o755); err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
if err := os.WriteFile(filepath.Join(*out, "testdata", "plural_samples.txt"), samples.Bytes(), 0o644); err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
|
|
if err := writeFormatTables(*out, *cache, core); err != nil {
|
|
log.Fatalf("format tables: %v", err)
|
|
}
|
|
}
|
|
|
|
// readPackage returns the files of a package of cldr-json by their paths
|
|
// in it, those keep reports true for when it is not nil, read from the
|
|
// directory cache when it has the tarball, else downloaded.
|
|
func readPackage(p cldrPackage, cache string, keep func(name string) bool) (map[string][]byte, error) {
|
|
var data []byte
|
|
var err error
|
|
if cache != "" {
|
|
data, err = os.ReadFile(filepath.Join(cache, p.name+"-"+cldrVersion+".tgz"))
|
|
}
|
|
if cache == "" || os.IsNotExist(err) {
|
|
data, err = download(p.url())
|
|
}
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
sum := sha256.Sum256(data)
|
|
if got := hex.EncodeToString(sum[:]); got != p.sha256 {
|
|
return nil, fmt.Errorf("%s %s has SHA-256 %s, want %s", p.name, cldrVersion, got, p.sha256)
|
|
}
|
|
gz, err := gzip.NewReader(bytes.NewReader(data))
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
files := map[string][]byte{}
|
|
tr := tar.NewReader(gz)
|
|
for {
|
|
h, err := tr.Next()
|
|
if err == io.EOF {
|
|
break
|
|
}
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if h.Typeflag != tar.TypeReg {
|
|
continue
|
|
}
|
|
name := strings.TrimPrefix(h.Name, "package/")
|
|
if keep != nil && !keep(name) {
|
|
continue
|
|
}
|
|
body, err := io.ReadAll(tr)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
files[name] = body
|
|
}
|
|
return files, nil
|
|
}
|
|
|
|
func download(url string) ([]byte, error) {
|
|
resp, err := http.Get(url)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer resp.Body.Close()
|
|
if resp.StatusCode != http.StatusOK {
|
|
return nil, fmt.Errorf("%s: %s", url, resp.Status)
|
|
}
|
|
return io.ReadAll(resp.Body)
|
|
}
|
|
|
|
var categories = []string{"zero", "one", "two", "few", "many", "other"}
|
|
|
|
// ruleSet is the rules of the categories of a language, other's empty.
|
|
type ruleSet [6]string
|
|
|
|
// writeRules writes the rules of a kind of plurals as a function that
|
|
// switches on the index of a rule set, the languages and the index of
|
|
// their rule set, and the categories each rule set has. Rule set 0 is
|
|
// the one of languages without rules: Other only.
|
|
func writeRules(b, samples *bytes.Buffer, kind string, data map[string]map[string]string) error {
|
|
sets := []ruleSet{{}}
|
|
masks := []uint8{1 << 5}
|
|
index := map[ruleSet]int{{}: 0}
|
|
langs := slices.Sorted(func(yield func(string) bool) {
|
|
for l := range data {
|
|
if !yield(l) {
|
|
return
|
|
}
|
|
}
|
|
})
|
|
var langIndex []int
|
|
langsOf := map[[2]ruleSet][]string{} // languages by rules and samples
|
|
var keys [][2]ruleSet
|
|
for _, lang := range langs {
|
|
var set, sampleSet ruleSet
|
|
mask := uint8(0)
|
|
for key := range data[lang] {
|
|
if cat, ok := strings.CutPrefix(key, "pluralRule-count-"); !ok || !slices.Contains(categories, cat) {
|
|
return fmt.Errorf("%s: unknown key %q", lang, key)
|
|
}
|
|
}
|
|
for i, cat := range categories {
|
|
rule, ok := data[lang]["pluralRule-count-"+cat]
|
|
if !ok {
|
|
continue
|
|
}
|
|
mask |= 1 << i
|
|
cond, samp, _ := strings.Cut(rule, "@")
|
|
cond = strings.TrimSpace(cond)
|
|
if cat == "other" {
|
|
if cond != "" {
|
|
return fmt.Errorf("%s: other has a condition", lang)
|
|
}
|
|
} else if cond == "" {
|
|
return fmt.Errorf("%s: %s has no condition", lang, cat)
|
|
}
|
|
set[i] = cond
|
|
sampleSet[i] = strings.TrimSpace(samp)
|
|
}
|
|
if mask&(1<<5) == 0 {
|
|
return fmt.Errorf("%s has no other", lang)
|
|
}
|
|
key := [2]ruleSet{set, sampleSet}
|
|
langsOf[key] = append(langsOf[key], lang)
|
|
if !slices.Contains(keys, key) {
|
|
keys = append(keys, key)
|
|
}
|
|
n, ok := index[set]
|
|
if !ok {
|
|
n = len(sets)
|
|
index[set] = n
|
|
sets = append(sets, set)
|
|
masks = append(masks, mask)
|
|
}
|
|
langIndex = append(langIndex, n)
|
|
}
|
|
for _, key := range keys {
|
|
for i, samp := range key[1] {
|
|
if samp != "" {
|
|
fmt.Fprintf(samples, "%s %s %s @%s\n", kind, strings.Join(langsOf[key], ","), categories[i], samp)
|
|
}
|
|
}
|
|
}
|
|
if len(sets) > 256 {
|
|
return fmt.Errorf("%d rule sets do not fit a uint8", len(sets))
|
|
}
|
|
|
|
fmt.Fprintf(b, "// %sRule returns the category of o by the %s rules of rule set r.\n", kind, kind)
|
|
fmt.Fprintf(b, "func %sRule(r uint8, o *Operands) Plural {\n\tswitch r {\n", kind)
|
|
for n, set := range sets {
|
|
if n == 0 {
|
|
continue
|
|
}
|
|
fmt.Fprintf(b, "\tcase %d:\n", n)
|
|
for i, cond := range set[:5] {
|
|
if cond == "" {
|
|
continue
|
|
}
|
|
expr, err := compileCondition(cond)
|
|
if err != nil {
|
|
return fmt.Errorf("%q: %v", cond, err)
|
|
}
|
|
fmt.Fprintf(b, "\t\t// %s\n\t\tif %s {\n\t\t\treturn Plural%s\n\t\t}\n", cond, expr, strings.ToUpper(categories[i][:1])+categories[i][1:])
|
|
}
|
|
}
|
|
b.WriteString("\t}\n\treturn PluralOther\n}\n\n")
|
|
|
|
fmt.Fprintf(b, "// %sLangs are the languages with %s rules, sorted, and %sRules the\n// rule set of each.\n", kind, kind, kind)
|
|
fmt.Fprintf(b, "var %sLangs = [...]string{\n", kind)
|
|
writeStrings(b, langs)
|
|
b.WriteString("}\n\n")
|
|
fmt.Fprintf(b, "var %sRules = [...]uint8{\n", kind)
|
|
writeInts(b, langIndex)
|
|
b.WriteString("}\n\n")
|
|
fmt.Fprintf(b, "// %sCategories are the categories of each rule set, a bit per Plural.\n", kind)
|
|
fmt.Fprintf(b, "var %sCategories = [...]uint8{\n", kind)
|
|
ints := make([]int, len(masks))
|
|
for i, m := range masks {
|
|
ints[i] = int(m)
|
|
}
|
|
writeInts(b, ints)
|
|
b.WriteString("}\n\n")
|
|
return nil
|
|
}
|
|
|
|
func writeStrings(b *bytes.Buffer, list []string) {
|
|
line := "\t"
|
|
for _, s := range list {
|
|
item := strconv.Quote(s) + ", "
|
|
if len(line)+len(item) > 76 {
|
|
b.WriteString(strings.TrimRight(line, " ") + "\n")
|
|
line = "\t"
|
|
}
|
|
line += item
|
|
}
|
|
if line != "\t" {
|
|
b.WriteString(strings.TrimRight(line, " ") + "\n")
|
|
}
|
|
}
|
|
|
|
func writeInts(b *bytes.Buffer, list []int) {
|
|
line := "\t"
|
|
for _, n := range list {
|
|
item := strconv.Itoa(n) + ", "
|
|
if len(line)+len(item) > 76 {
|
|
b.WriteString(strings.TrimRight(line, " ") + "\n")
|
|
line = "\t"
|
|
}
|
|
line += item
|
|
}
|
|
if line != "\t" {
|
|
b.WriteString(strings.TrimRight(line, " ") + "\n")
|
|
}
|
|
}
|
|
|
|
// compileCondition compiles a condition of CLDR's plural rules (UTS #35,
|
|
// Part 3, Plural rules syntax) to a Go expression on o, an *Operands:
|
|
//
|
|
// condition = and_condition ('or' and_condition)*
|
|
// and_condition = relation ('and' relation)*
|
|
// relation = operand ('%' value)? ('=' | '!=') range_list
|
|
// range_list = (range | value) (',' range_list)*
|
|
// range = value'..'value
|
|
//
|
|
// The operand n is the absolute value, which equals a value, or is in a
|
|
// range, only when it is an integer: when its fraction F is 0.
|
|
func compileCondition(cond string) (string, error) {
|
|
var ors []string
|
|
for _, and := range strings.Split(cond, " or ") {
|
|
var rels []relation
|
|
integral := false // a relation needs n to be an integer
|
|
for _, r := range strings.Split(and, " and ") {
|
|
rel, err := parseRelation(strings.TrimSpace(r))
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
integral = integral || rel.onN && !rel.negate
|
|
rels = append(rels, rel)
|
|
}
|
|
var ands []string
|
|
if integral {
|
|
ands = append(ands, "o.F == 0")
|
|
}
|
|
for _, rel := range rels {
|
|
ands = append(ands, rel.expr(!integral))
|
|
}
|
|
ors = append(ors, strings.Join(ands, " && "))
|
|
}
|
|
if len(ors) == 1 {
|
|
return ors[0], nil
|
|
}
|
|
for i, o := range ors {
|
|
if strings.Contains(o, "&&") {
|
|
ors[i] = "(" + o + ")"
|
|
}
|
|
}
|
|
return strings.Join(ors, " || "), nil
|
|
}
|
|
|
|
var operands = map[string]string{
|
|
"n": "o.I", "i": "o.I", "v": "uint64(o.V)", "w": "uint64(o.W)",
|
|
"f": "o.F", "t": "o.T", "c": "uint64(o.C)", "e": "uint64(o.C)",
|
|
}
|
|
|
|
// relation is a relation of a plural rule: whether an operand, or its
|
|
// remainder, is in a list of values and ranges, as Go alternatives.
|
|
type relation struct {
|
|
alts []string
|
|
onN bool // the operand is n
|
|
negate bool // !=
|
|
}
|
|
|
|
// expr returns the relation as a Go expression. A relation on n holds only
|
|
// when n is an integer, which guard checks unless the caller does.
|
|
func (r relation) expr(guard bool) string {
|
|
in := strings.Join(r.alts, " || ")
|
|
if r.onN && guard {
|
|
in = "o.F == 0 && (" + in + ")"
|
|
}
|
|
switch {
|
|
case r.negate:
|
|
return "!(" + in + ")"
|
|
case strings.ContainsAny(in, "|&"):
|
|
return "(" + in + ")"
|
|
}
|
|
return in
|
|
}
|
|
|
|
func parseRelation(rel string) (relation, error) {
|
|
var r relation
|
|
left, right, ok := strings.Cut(rel, "!=")
|
|
if ok {
|
|
r.negate = true
|
|
} else if left, right, ok = strings.Cut(rel, "="); !ok {
|
|
return r, fmt.Errorf("relation %q has no = or !=", rel)
|
|
}
|
|
left, right = strings.TrimSpace(left), strings.TrimSpace(right)
|
|
op, mod, hasMod := strings.Cut(left, "%")
|
|
op = strings.TrimSpace(op)
|
|
x, ok := operands[op]
|
|
if !ok {
|
|
return r, fmt.Errorf("unknown operand %q", op)
|
|
}
|
|
r.onN = op == "n"
|
|
if hasMod {
|
|
m, err := strconv.ParseUint(strings.TrimSpace(mod), 10, 64)
|
|
if err != nil || !powerOfTen(m) {
|
|
// Operands of more than 18 digits keep their remainders by
|
|
// the powers of ten only.
|
|
return r, fmt.Errorf("modulus %q is not a power of ten", mod)
|
|
}
|
|
x = fmt.Sprintf("%s%%%d", x, m)
|
|
}
|
|
for _, v := range strings.Split(right, ",") {
|
|
lo, hi, isRange := strings.Cut(strings.TrimSpace(v), "..")
|
|
a, err := strconv.ParseUint(lo, 10, 64)
|
|
if err != nil {
|
|
return r, fmt.Errorf("bad value %q", lo)
|
|
}
|
|
if !isRange {
|
|
r.alts = append(r.alts, fmt.Sprintf("%s == %d", x, a))
|
|
continue
|
|
}
|
|
z, err := strconv.ParseUint(hi, 10, 64)
|
|
if err != nil || z < a {
|
|
return r, fmt.Errorf("bad range %q", v)
|
|
}
|
|
if a == 0 {
|
|
r.alts = append(r.alts, fmt.Sprintf("%s <= %d", x, z))
|
|
} else {
|
|
r.alts = append(r.alts, fmt.Sprintf("%s >= %d && %s <= %d", x, a, x, z))
|
|
}
|
|
}
|
|
return r, nil
|
|
}
|
|
|
|
func powerOfTen(m uint64) bool {
|
|
for m >= 10 && m%10 == 0 {
|
|
m /= 10
|
|
}
|
|
return m == 1
|
|
}
|
|
|
|
// writeParents writes the parent locales of CLDR, sorted by child: those
|
|
// whose parent is not the one truncation gives. A parent of "und" is the
|
|
// root, "".
|
|
func writeParents(b *bytes.Buffer, parents map[string]string) {
|
|
children := slices.Sorted(func(yield func(string) bool) {
|
|
for c := range parents {
|
|
if !yield(c) {
|
|
return
|
|
}
|
|
}
|
|
})
|
|
values := make([]string, len(children))
|
|
for i, c := range children {
|
|
if p := parents[c]; p != "und" && p != "root" {
|
|
values[i] = p
|
|
}
|
|
}
|
|
b.WriteString("// parentChildren are the locales whose parent CLDR names, sorted, and\n// parentLocales their parents, \"\" for the root.\n")
|
|
b.WriteString("var parentChildren = [...]string{\n")
|
|
writeStrings(b, children)
|
|
b.WriteString("}\n\nvar parentLocales = [...]string{\n")
|
|
writeStrings(b, values)
|
|
b.WriteString("}\n")
|
|
}
|