1 // Copyright 2012 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
7 // Collation table generator.
8 // Data read from the web.
28 "golang.org/x/text/collate"
29 "golang.org/x/text/collate/build"
30 "golang.org/x/text/internal/colltab"
31 "golang.org/x/text/internal/gen"
32 "golang.org/x/text/language"
33 "golang.org/x/text/unicode/cldr"
37 test = flag.Bool("test", false,
38 "test existing tables; can be used to compare web data with package data.")
39 short = flag.Bool("short", false, `Use "short" alternatives, when available.`)
40 draft = flag.Bool("draft", false, `Use draft versions, when available.`)
41 tags = flag.String("tags", "", "build tags to be included after +build directive")
42 pkg = flag.String("package", "collate",
43 "the name of the package in which the generated file is to be included")
45 tables = flagStringSetAllowAll("tables", "collate", "collate,chars",
46 "comma-spearated list of tables to generate.")
47 exclude = flagStringSet("exclude", "zh2", "",
48 "comma-separated list of languages to exclude.")
49 include = flagStringSet("include", "", "",
50 "comma-separated list of languages to include. Include trumps exclude.")
51 // TODO: Not included: unihan gb2312han zhuyin big5han (for size reasons)
52 // TODO: Not included: traditional (buggy for Bengali)
53 types = flagStringSetAllowAll("types", "standard,phonebook,phonetic,reformed,pinyin,stroke", "",
54 "comma-separated list of types that should be included.")
57 // stringSet implements an ordered set based on a list. It implements flag.Value
58 // to allow a set to be specified as a comma-separated list.
59 type stringSet struct {
62 dirty bool // needs compaction if true
67 func flagStringSet(name, def, allowed, usage string) *stringSet {
70 usage += fmt.Sprintf(" (allowed values: any of %s)", allowed)
71 ss.allowed = &stringSet{}
72 failOnError(ss.allowed.Set(allowed))
75 flag.Var(ss, name, usage)
79 func flagStringSetAllowAll(name, def, allowed, usage string) *stringSet {
80 ss := &stringSet{allowAll: true}
82 flag.Var(ss, name, usage+fmt.Sprintf(` Use "all" to select all.`))
84 ss.allowed = &stringSet{}
85 failOnError(ss.allowed.Set(allowed))
86 flag.Var(ss, name, usage+fmt.Sprintf(` (allowed values: "all" or any of %s)`, allowed))
92 func (ss stringSet) Len() int {
96 func (ss stringSet) String() string {
97 return strings.Join(ss.s, ",")
100 func (ss *stringSet) Set(s string) error {
101 if ss.allowAll && s == "all" {
107 for _, s := range strings.Split(s, ",") {
108 if s := strings.TrimSpace(s); s != "" {
109 if ss.allowed != nil && !ss.allowed.contains(s) {
110 return fmt.Errorf("unsupported value %q; must be one of %s", s, ss.allowed)
119 func (ss *stringSet) add(s string) {
120 ss.s = append(ss.s, s)
124 func (ss *stringSet) values() []string {
129 func (ss *stringSet) contains(s string) bool {
133 for _, v := range ss.s {
141 func (ss *stringSet) compact() {
148 for i := 1; i < len(a); i++ {
158 func skipLang(l string) bool {
159 if include.Len() > 0 {
160 return !include.contains(l)
162 return exclude.contains(l)
165 // altInclude returns a list of alternatives (for the LDML alt attribute)
166 // in order of preference. An empty string in this list indicates the
168 func altInclude() []string {
171 l = append(l, "short")
174 // TODO: handle draft using cldr.SetDraftLevel
176 l = append(l, "proposed")
181 func failOnError(e error) {
187 func openArchive() *zip.Reader {
188 f := gen.OpenCLDRCoreZip()
189 buffer, err := ioutil.ReadAll(f)
192 archive, err := zip.NewReader(bytes.NewReader(buffer), int64(len(buffer)))
197 // parseUCA parses a Default Unicode Collation Element Table of the format
198 // specified in http://www.unicode.org/reports/tr10/#File_Format.
199 // It returns the variable top.
200 func parseUCA(builder *build.Builder) {
203 for _, f := range openArchive().File {
204 if strings.HasSuffix(f.Name, "allkeys_CLDR.txt") {
209 log.Fatal("File allkeys_CLDR.txt not found in archive.")
213 scanner := bufio.NewScanner(r)
214 colelem := regexp.MustCompile(`\[([.*])([0-9A-F.]+)\]`)
215 for i := 1; scanner.Scan(); i++ {
216 line := scanner.Text()
217 if len(line) == 0 || line[0] == '#' {
223 case strings.HasPrefix(line[1:], "version "):
224 a := strings.Split(line[1:], " ")
225 if a[1] != gen.UnicodeVersion() {
226 log.Fatalf("incompatible version %s; want %s", a[1], gen.UnicodeVersion())
228 case strings.HasPrefix(line[1:], "backwards "):
229 log.Fatalf("%d: unsupported option backwards", i)
231 log.Printf("%d: unknown option %s", i, line[1:])
235 part := strings.Split(line, " ; ")
237 log.Fatalf("%d: production rule without ';': %v", i, line)
240 for _, v := range strings.Split(part[0], " ") {
244 lhs = append(lhs, rune(convHex(i, v)))
249 for i, m := range colelem.FindAllStringSubmatch(part[1], -1) {
252 for _, h := range strings.Split(m[2], ".") {
253 elem = append(elem, convHex(i, h))
256 vars = append(vars, i)
258 rhs = append(rhs, elem)
260 if len(part[1]) < n+3 || part[1][n+1] != '#' {
261 log.Fatalf("%d: expected comment; found %s", i, part[1][n:])
264 testInput.add(string(lhs))
266 failOnError(builder.Add(lhs, rhs, vars))
269 if scanner.Err() != nil {
270 log.Fatal(scanner.Err())
274 func convHex(line int, s string) int {
275 r, e := strconv.ParseInt(s, 16, 32)
277 log.Fatalf("%d: %v", line, e)
282 var testInput = stringSet{}
284 var charRe = regexp.MustCompile(`&#x([0-9A-F]*);`)
285 var tagRe = regexp.MustCompile(`<([a-z_]*) */>`)
287 var mainLocales = []string{}
289 // charsets holds a list of exemplar characters per category.
290 type charSets map[string][]string
292 func (p charSets) fprint(w io.Writer) {
293 fmt.Fprintln(w, "[exN]string{")
294 for i, k := range []string{"", "contractions", "punctuation", "auxiliary", "currencySymbol", "index"} {
295 if set := p[k]; len(set) != 0 {
296 fmt.Fprintf(w, "\t\t%d: %q,\n", i, strings.Join(set, " "))
299 fmt.Fprintln(w, "\t},")
302 var localeChars = make(map[string]charSets)
304 const exemplarHeader = `
305 type exemplarType int
307 exCharacters exemplarType = iota
317 func printExemplarCharacters(w io.Writer) {
318 fmt.Fprintln(w, exemplarHeader)
319 fmt.Fprintln(w, "var exemplarCharacters = map[string][exN]string{")
320 for _, loc := range mainLocales {
321 fmt.Fprintf(w, "\t%q: ", loc)
322 localeChars[loc].fprint(w)
327 func decodeCLDR(d *cldr.Decoder) *cldr.CLDR {
328 r := gen.OpenCLDRCoreZip()
329 data, err := d.DecodeZip(r)
334 // parseMain parses XML files in the main directory of the CLDR core.zip file.
337 d.SetDirFilter("main")
338 d.SetSectionFilter("characters")
339 data := decodeCLDR(d)
340 for _, loc := range data.Locales() {
341 x := data.RawLDML(loc)
342 if skipLang(x.Identity.Language.Type) {
345 if x.Characters != nil {
346 x, _ = data.LDML(loc)
347 loc = language.Make(loc).String()
348 for _, ec := range x.Characters.ExemplarCharacters {
352 if _, ok := localeChars[loc]; !ok {
353 mainLocales = append(mainLocales, loc)
354 localeChars[loc] = make(charSets)
356 localeChars[loc][ec.Type] = parseCharacters(ec.Data())
362 func parseCharacters(chars string) []string {
363 parseSingle := func(s string) (r rune, tail string, escaped bool) {
365 return rune(s[1]), s[2:], true
367 r, sz := utf8.DecodeRuneInString(s)
368 return r, s[sz:], false
370 chars = strings.TrimSpace(chars)
371 if n := len(chars) - 1; chars[n] == ']' && chars[0] == '[' {
375 var r, last, end rune
377 if chars[0] == '{' { // character sequence
379 for chars = chars[1:]; len(chars) > 0; {
380 r, chars, _ = parseSingle(chars)
385 log.Fatalf("space not supported in sequence %q", chars)
389 list = append(list, string(buf))
391 } else { // single character
393 r, chars, escaped = parseSingle(chars)
395 if r == '-' && !escaped {
397 log.Fatal("'-' should be preceded by a character")
399 end, chars, _ = parseSingle(chars)
400 for ; last <= end; last++ {
401 list = append(list, string(last))
405 list = append(list, string(r))
414 var fileRe = regexp.MustCompile(`.*/collation/(.*)\.xml`)
416 // typeMap translates legacy type keys to their BCP47 equivalent.
417 var typeMap = map[string]string{
418 "phonebook": "phonebk",
419 "traditional": "trad",
422 // parseCollation parses XML files in the collation directory of the CLDR core.zip file.
423 func parseCollation(b *build.Builder) {
425 d.SetDirFilter("collation")
426 data := decodeCLDR(d)
427 for _, loc := range data.Locales() {
428 x, err := data.LDML(loc)
430 if skipLang(x.Identity.Language.Type) {
433 cs := x.Collations.Collation
434 sl := cldr.MakeSlice(&cs)
435 if len(types.s) == 0 {
436 sl.SelectAnyOf("type", x.Collations.Default())
437 } else if !types.all {
438 sl.SelectAnyOf("type", types.s...)
440 sl.SelectOnePerGroup("alt", altInclude())
442 for _, c := range cs {
443 id, err := language.Parse(loc)
445 fmt.Fprintf(os.Stderr, "invalid locale: %q", err)
448 // Support both old- and new-style defaults.
450 if x.Collations.DefaultCollation == nil {
451 d = x.Collations.Default()
453 d = x.Collations.DefaultCollation.Data()
455 // We assume tables are being built either for search or collation,
456 // but not both. For search the default is always "search".
457 if d != c.Type && c.Type != "search" {
460 typ = typeMap[c.Type]
462 id, err = id.SetTypeForKey("co", typ)
466 c.Process(processor{t})
471 type processor struct {
475 func (p processor) Reset(anchor string, before int) (err error) {
477 err = p.t.SetAnchorBefore(anchor)
479 err = p.t.SetAnchor(anchor)
485 func (p processor) Insert(level int, str, context, extend string) error {
490 // TODO: mimic bug in old maketables: remove.
491 err := p.t.Insert(colltab.Level(level-1), str, context+extend)
496 func (p processor) Index(id string) {
499 func testCollator(c *collate.Collator) {
500 c0 := collate.New(language.Und)
502 // iterator over all characters for all locales and check
503 // whether Key is equal.
504 buf := collate.Buffer{}
506 // Add all common and not too uncommon runes to the test set.
507 for i := rune(0); i < 0x30000; i++ {
508 testInput.add(string(i))
510 for i := rune(0xE0000); i < 0xF0000; i++ {
511 testInput.add(string(i))
513 for _, str := range testInput.values() {
514 k0 := c0.KeyFromString(&buf, str)
515 k := c.KeyFromString(&buf, str)
516 if !bytes.Equal(k0, k) {
517 failOnError(fmt.Errorf("test:%U: keys differ (%x vs %x)", []rune(str), k0, k))
526 b := build.NewBuilder()
528 if tables.contains("chars") {
537 testCollator(collate.NewFromTable(c))
541 gen.WriteUnicodeVersion(w)
542 gen.WriteCLDRVersion(w)
544 if tables.contains("collate") {
548 if tables.contains("chars") {
549 printExemplarCharacters(w)
551 gen.WriteGoFile("tables.go", *pkg, w.Bytes())