25'ten fazla konu seçemezsiniz Konular bir harf veya rakamla başlamalı, kısa çizgiler ('-') içerebilir ve en fazla 35 karakter uzunluğunda olabilir.
 
 
 

1636 satır
46 KiB

  1. // Copyright 2013 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.
  4. // +build ignore
  5. // Language tag table generator.
  6. // Data read from the web.
  7. package main
  8. import (
  9. "bufio"
  10. "flag"
  11. "fmt"
  12. "io"
  13. "io/ioutil"
  14. "log"
  15. "math"
  16. "reflect"
  17. "regexp"
  18. "sort"
  19. "strconv"
  20. "strings"
  21. "golang.org/x/text/internal/gen"
  22. "golang.org/x/text/internal/tag"
  23. "golang.org/x/text/unicode/cldr"
  24. )
  25. var (
  26. test = flag.Bool("test",
  27. false,
  28. "test existing tables; can be used to compare web data with package data.")
  29. outputFile = flag.String("output",
  30. "tables.go",
  31. "output file for generated tables")
  32. )
  33. var comment = []string{
  34. `
  35. lang holds an alphabetically sorted list of ISO-639 language identifiers.
  36. All entries are 4 bytes. The index of the identifier (divided by 4) is the language tag.
  37. For 2-byte language identifiers, the two successive bytes have the following meaning:
  38. - if the first letter of the 2- and 3-letter ISO codes are the same:
  39. the second and third letter of the 3-letter ISO code.
  40. - otherwise: a 0 and a by 2 bits right-shifted index into altLangISO3.
  41. For 3-byte language identifiers the 4th byte is 0.`,
  42. `
  43. langNoIndex is a bit vector of all 3-letter language codes that are not used as an index
  44. in lookup tables. The language ids for these language codes are derived directly
  45. from the letters and are not consecutive.`,
  46. `
  47. altLangISO3 holds an alphabetically sorted list of 3-letter language code alternatives
  48. to 2-letter language codes that cannot be derived using the method described above.
  49. Each 3-letter code is followed by its 1-byte langID.`,
  50. `
  51. altLangIndex is used to convert indexes in altLangISO3 to langIDs.`,
  52. `
  53. langAliasMap maps langIDs to their suggested replacements.`,
  54. `
  55. script is an alphabetically sorted list of ISO 15924 codes. The index
  56. of the script in the string, divided by 4, is the internal scriptID.`,
  57. `
  58. isoRegionOffset needs to be added to the index of regionISO to obtain the regionID
  59. for 2-letter ISO codes. (The first isoRegionOffset regionIDs are reserved for
  60. the UN.M49 codes used for groups.)`,
  61. `
  62. regionISO holds a list of alphabetically sorted 2-letter ISO region codes.
  63. Each 2-letter codes is followed by two bytes with the following meaning:
  64. - [A-Z}{2}: the first letter of the 2-letter code plus these two
  65. letters form the 3-letter ISO code.
  66. - 0, n: index into altRegionISO3.`,
  67. `
  68. regionTypes defines the status of a region for various standards.`,
  69. `
  70. m49 maps regionIDs to UN.M49 codes. The first isoRegionOffset entries are
  71. codes indicating collections of regions.`,
  72. `
  73. m49Index gives indexes into fromM49 based on the three most significant bits
  74. of a 10-bit UN.M49 code. To search an UN.M49 code in fromM49, search in
  75. fromM49[m49Index[msb39(code)]:m49Index[msb3(code)+1]]
  76. for an entry where the first 7 bits match the 7 lsb of the UN.M49 code.
  77. The region code is stored in the 9 lsb of the indexed value.`,
  78. `
  79. fromM49 contains entries to map UN.M49 codes to regions. See m49Index for details.`,
  80. `
  81. altRegionISO3 holds a list of 3-letter region codes that cannot be
  82. mapped to 2-letter codes using the default algorithm. This is a short list.`,
  83. `
  84. altRegionIDs holds a list of regionIDs the positions of which match those
  85. of the 3-letter ISO codes in altRegionISO3.`,
  86. `
  87. variantNumSpecialized is the number of specialized variants in variants.`,
  88. `
  89. suppressScript is an index from langID to the dominant script for that language,
  90. if it exists. If a script is given, it should be suppressed from the language tag.`,
  91. `
  92. likelyLang is a lookup table, indexed by langID, for the most likely
  93. scripts and regions given incomplete information. If more entries exist for a
  94. given language, region and script are the index and size respectively
  95. of the list in likelyLangList.`,
  96. `
  97. likelyLangList holds lists info associated with likelyLang.`,
  98. `
  99. likelyRegion is a lookup table, indexed by regionID, for the most likely
  100. languages and scripts given incomplete information. If more entries exist
  101. for a given regionID, lang and script are the index and size respectively
  102. of the list in likelyRegionList.
  103. TODO: exclude containers and user-definable regions from the list.`,
  104. `
  105. likelyRegionList holds lists info associated with likelyRegion.`,
  106. `
  107. likelyScript is a lookup table, indexed by scriptID, for the most likely
  108. languages and regions given a script.`,
  109. `
  110. matchLang holds pairs of langIDs of base languages that are typically
  111. mutually intelligible. Each pair is associated with a confidence and
  112. whether the intelligibility goes one or both ways.`,
  113. `
  114. matchScript holds pairs of scriptIDs where readers of one script
  115. can typically also read the other. Each is associated with a confidence.`,
  116. `
  117. nRegionGroups is the number of region groups.`,
  118. `
  119. regionInclusion maps region identifiers to sets of regions in regionInclusionBits,
  120. where each set holds all groupings that are directly connected in a region
  121. containment graph.`,
  122. `
  123. regionInclusionBits is an array of bit vectors where every vector represents
  124. a set of region groupings. These sets are used to compute the distance
  125. between two regions for the purpose of language matching.`,
  126. `
  127. regionInclusionNext marks, for each entry in regionInclusionBits, the set of
  128. all groups that are reachable from the groups set in the respective entry.`,
  129. }
  130. // TODO: consider changing some of these structures to tries. This can reduce
  131. // memory, but may increase the need for memory allocations. This could be
  132. // mitigated if we can piggyback on language tags for common cases.
  133. func failOnError(e error) {
  134. if e != nil {
  135. log.Panic(e)
  136. }
  137. }
  138. type setType int
  139. const (
  140. Indexed setType = 1 + iota // all elements must be of same size
  141. Linear
  142. )
  143. type stringSet struct {
  144. s []string
  145. sorted, frozen bool
  146. // We often need to update values after the creation of an index is completed.
  147. // We include a convenience map for keeping track of this.
  148. update map[string]string
  149. typ setType // used for checking.
  150. }
  151. func (ss *stringSet) clone() stringSet {
  152. c := *ss
  153. c.s = append([]string(nil), c.s...)
  154. return c
  155. }
  156. func (ss *stringSet) setType(t setType) {
  157. if ss.typ != t && ss.typ != 0 {
  158. log.Panicf("type %d cannot be assigned as it was already %d", t, ss.typ)
  159. }
  160. }
  161. // parse parses a whitespace-separated string and initializes ss with its
  162. // components.
  163. func (ss *stringSet) parse(s string) {
  164. scan := bufio.NewScanner(strings.NewReader(s))
  165. scan.Split(bufio.ScanWords)
  166. for scan.Scan() {
  167. ss.add(scan.Text())
  168. }
  169. }
  170. func (ss *stringSet) assertChangeable() {
  171. if ss.frozen {
  172. log.Panic("attempt to modify a frozen stringSet")
  173. }
  174. }
  175. func (ss *stringSet) add(s string) {
  176. ss.assertChangeable()
  177. ss.s = append(ss.s, s)
  178. ss.sorted = ss.frozen
  179. }
  180. func (ss *stringSet) freeze() {
  181. ss.compact()
  182. ss.frozen = true
  183. }
  184. func (ss *stringSet) compact() {
  185. if ss.sorted {
  186. return
  187. }
  188. a := ss.s
  189. sort.Strings(a)
  190. k := 0
  191. for i := 1; i < len(a); i++ {
  192. if a[k] != a[i] {
  193. a[k+1] = a[i]
  194. k++
  195. }
  196. }
  197. ss.s = a[:k+1]
  198. ss.sorted = ss.frozen
  199. }
  200. type funcSorter struct {
  201. fn func(a, b string) bool
  202. sort.StringSlice
  203. }
  204. func (s funcSorter) Less(i, j int) bool {
  205. return s.fn(s.StringSlice[i], s.StringSlice[j])
  206. }
  207. func (ss *stringSet) sortFunc(f func(a, b string) bool) {
  208. ss.compact()
  209. sort.Sort(funcSorter{f, sort.StringSlice(ss.s)})
  210. }
  211. func (ss *stringSet) remove(s string) {
  212. ss.assertChangeable()
  213. if i, ok := ss.find(s); ok {
  214. copy(ss.s[i:], ss.s[i+1:])
  215. ss.s = ss.s[:len(ss.s)-1]
  216. }
  217. }
  218. func (ss *stringSet) replace(ol, nu string) {
  219. ss.s[ss.index(ol)] = nu
  220. ss.sorted = ss.frozen
  221. }
  222. func (ss *stringSet) index(s string) int {
  223. ss.setType(Indexed)
  224. i, ok := ss.find(s)
  225. if !ok {
  226. if i < len(ss.s) {
  227. log.Panicf("find: item %q is not in list. Closest match is %q.", s, ss.s[i])
  228. }
  229. log.Panicf("find: item %q is not in list", s)
  230. }
  231. return i
  232. }
  233. func (ss *stringSet) find(s string) (int, bool) {
  234. ss.compact()
  235. i := sort.SearchStrings(ss.s, s)
  236. return i, i != len(ss.s) && ss.s[i] == s
  237. }
  238. func (ss *stringSet) slice() []string {
  239. ss.compact()
  240. return ss.s
  241. }
  242. func (ss *stringSet) updateLater(v, key string) {
  243. if ss.update == nil {
  244. ss.update = map[string]string{}
  245. }
  246. ss.update[v] = key
  247. }
  248. // join joins the string and ensures that all entries are of the same length.
  249. func (ss *stringSet) join() string {
  250. ss.setType(Indexed)
  251. n := len(ss.s[0])
  252. for _, s := range ss.s {
  253. if len(s) != n {
  254. log.Panicf("join: not all entries are of the same length: %q", s)
  255. }
  256. }
  257. ss.s = append(ss.s, strings.Repeat("\xff", n))
  258. return strings.Join(ss.s, "")
  259. }
  260. // ianaEntry holds information for an entry in the IANA Language Subtag Repository.
  261. // All types use the same entry.
  262. // See http://tools.ietf.org/html/bcp47#section-5.1 for a description of the various
  263. // fields.
  264. type ianaEntry struct {
  265. typ string
  266. description []string
  267. scope string
  268. added string
  269. preferred string
  270. deprecated string
  271. suppressScript string
  272. macro string
  273. prefix []string
  274. }
  275. type builder struct {
  276. w *gen.CodeWriter
  277. hw io.Writer // MultiWriter for w and w.Hash
  278. data *cldr.CLDR
  279. supp *cldr.SupplementalData
  280. // indices
  281. locale stringSet // common locales
  282. lang stringSet // canonical language ids (2 or 3 letter ISO codes) with data
  283. langNoIndex stringSet // 3-letter ISO codes with no associated data
  284. script stringSet // 4-letter ISO codes
  285. region stringSet // 2-letter ISO or 3-digit UN M49 codes
  286. variant stringSet // 4-8-alphanumeric variant code.
  287. // Region codes that are groups with their corresponding group IDs.
  288. groups map[int]index
  289. // langInfo
  290. registry map[string]*ianaEntry
  291. }
  292. type index uint
  293. func newBuilder(w *gen.CodeWriter) *builder {
  294. r := gen.OpenCLDRCoreZip()
  295. defer r.Close()
  296. d := &cldr.Decoder{}
  297. data, err := d.DecodeZip(r)
  298. failOnError(err)
  299. b := builder{
  300. w: w,
  301. hw: io.MultiWriter(w, w.Hash),
  302. data: data,
  303. supp: data.Supplemental(),
  304. }
  305. b.parseRegistry()
  306. return &b
  307. }
  308. func (b *builder) parseRegistry() {
  309. r := gen.OpenIANAFile("assignments/language-subtag-registry")
  310. defer r.Close()
  311. b.registry = make(map[string]*ianaEntry)
  312. scan := bufio.NewScanner(r)
  313. scan.Split(bufio.ScanWords)
  314. var record *ianaEntry
  315. for more := scan.Scan(); more; {
  316. key := scan.Text()
  317. more = scan.Scan()
  318. value := scan.Text()
  319. switch key {
  320. case "Type:":
  321. record = &ianaEntry{typ: value}
  322. case "Subtag:", "Tag:":
  323. if s := strings.SplitN(value, "..", 2); len(s) > 1 {
  324. for a := s[0]; a <= s[1]; a = inc(a) {
  325. b.addToRegistry(a, record)
  326. }
  327. } else {
  328. b.addToRegistry(value, record)
  329. }
  330. case "Suppress-Script:":
  331. record.suppressScript = value
  332. case "Added:":
  333. record.added = value
  334. case "Deprecated:":
  335. record.deprecated = value
  336. case "Macrolanguage:":
  337. record.macro = value
  338. case "Preferred-Value:":
  339. record.preferred = value
  340. case "Prefix:":
  341. record.prefix = append(record.prefix, value)
  342. case "Scope:":
  343. record.scope = value
  344. case "Description:":
  345. buf := []byte(value)
  346. for more = scan.Scan(); more; more = scan.Scan() {
  347. b := scan.Bytes()
  348. if b[0] == '%' || b[len(b)-1] == ':' {
  349. break
  350. }
  351. buf = append(buf, ' ')
  352. buf = append(buf, b...)
  353. }
  354. record.description = append(record.description, string(buf))
  355. continue
  356. default:
  357. continue
  358. }
  359. more = scan.Scan()
  360. }
  361. if scan.Err() != nil {
  362. log.Panic(scan.Err())
  363. }
  364. }
  365. func (b *builder) addToRegistry(key string, entry *ianaEntry) {
  366. if info, ok := b.registry[key]; ok {
  367. if info.typ != "language" || entry.typ != "extlang" {
  368. log.Fatalf("parseRegistry: tag %q already exists", key)
  369. }
  370. } else {
  371. b.registry[key] = entry
  372. }
  373. }
  374. var commentIndex = make(map[string]string)
  375. func init() {
  376. for _, s := range comment {
  377. key := strings.TrimSpace(strings.SplitN(s, " ", 2)[0])
  378. commentIndex[key] = s
  379. }
  380. }
  381. func (b *builder) comment(name string) {
  382. if s := commentIndex[name]; len(s) > 0 {
  383. b.w.WriteComment(s)
  384. } else {
  385. fmt.Fprintln(b.w)
  386. }
  387. }
  388. func (b *builder) pf(f string, x ...interface{}) {
  389. fmt.Fprintf(b.hw, f, x...)
  390. fmt.Fprint(b.hw, "\n")
  391. }
  392. func (b *builder) p(x ...interface{}) {
  393. fmt.Fprintln(b.hw, x...)
  394. }
  395. func (b *builder) addSize(s int) {
  396. b.w.Size += s
  397. b.pf("// Size: %d bytes", s)
  398. }
  399. func (b *builder) writeConst(name string, x interface{}) {
  400. b.comment(name)
  401. b.w.WriteConst(name, x)
  402. }
  403. // writeConsts computes f(v) for all v in values and writes the results
  404. // as constants named _v to a single constant block.
  405. func (b *builder) writeConsts(f func(string) int, values ...string) {
  406. b.pf("const (")
  407. for _, v := range values {
  408. b.pf("\t_%s = %v", v, f(v))
  409. }
  410. b.pf(")")
  411. }
  412. // writeType writes the type of the given value, which must be a struct.
  413. func (b *builder) writeType(value interface{}) {
  414. b.comment(reflect.TypeOf(value).Name())
  415. b.w.WriteType(value)
  416. }
  417. func (b *builder) writeSlice(name string, ss interface{}) {
  418. b.writeSliceAddSize(name, 0, ss)
  419. }
  420. func (b *builder) writeSliceAddSize(name string, extraSize int, ss interface{}) {
  421. b.comment(name)
  422. b.w.Size += extraSize
  423. v := reflect.ValueOf(ss)
  424. t := v.Type().Elem()
  425. b.pf("// Size: %d bytes, %d elements", v.Len()*int(t.Size())+extraSize, v.Len())
  426. fmt.Fprintf(b.w, "var %s = ", name)
  427. b.w.WriteArray(ss)
  428. b.p()
  429. }
  430. type fromTo struct {
  431. from, to uint16
  432. }
  433. func (b *builder) writeSortedMap(name string, ss *stringSet, index func(s string) uint16) {
  434. ss.sortFunc(func(a, b string) bool {
  435. return index(a) < index(b)
  436. })
  437. m := []fromTo{}
  438. for _, s := range ss.s {
  439. m = append(m, fromTo{index(s), index(ss.update[s])})
  440. }
  441. b.writeSlice(name, m)
  442. }
  443. const base = 'z' - 'a' + 1
  444. func strToInt(s string) uint {
  445. v := uint(0)
  446. for i := 0; i < len(s); i++ {
  447. v *= base
  448. v += uint(s[i] - 'a')
  449. }
  450. return v
  451. }
  452. // converts the given integer to the original ASCII string passed to strToInt.
  453. // len(s) must match the number of characters obtained.
  454. func intToStr(v uint, s []byte) {
  455. for i := len(s) - 1; i >= 0; i-- {
  456. s[i] = byte(v%base) + 'a'
  457. v /= base
  458. }
  459. }
  460. func (b *builder) writeBitVector(name string, ss []string) {
  461. vec := make([]uint8, int(math.Ceil(math.Pow(base, float64(len(ss[0])))/8)))
  462. for _, s := range ss {
  463. v := strToInt(s)
  464. vec[v/8] |= 1 << (v % 8)
  465. }
  466. b.writeSlice(name, vec)
  467. }
  468. // TODO: convert this type into a list or two-stage trie.
  469. func (b *builder) writeMapFunc(name string, m map[string]string, f func(string) uint16) {
  470. b.comment(name)
  471. v := reflect.ValueOf(m)
  472. sz := v.Len() * (2 + int(v.Type().Key().Size()))
  473. for _, k := range m {
  474. sz += len(k)
  475. }
  476. b.addSize(sz)
  477. keys := []string{}
  478. b.pf(`var %s = map[string]uint16{`, name)
  479. for k := range m {
  480. keys = append(keys, k)
  481. }
  482. sort.Strings(keys)
  483. for _, k := range keys {
  484. b.pf("\t%q: %v,", k, f(m[k]))
  485. }
  486. b.p("}")
  487. }
  488. func (b *builder) writeMap(name string, m interface{}) {
  489. b.comment(name)
  490. v := reflect.ValueOf(m)
  491. sz := v.Len() * (2 + int(v.Type().Key().Size()) + int(v.Type().Elem().Size()))
  492. b.addSize(sz)
  493. f := strings.FieldsFunc(fmt.Sprintf("%#v", m), func(r rune) bool {
  494. return strings.IndexRune("{}, ", r) != -1
  495. })
  496. sort.Strings(f[1:])
  497. b.pf(`var %s = %s{`, name, f[0])
  498. for _, kv := range f[1:] {
  499. b.pf("\t%s,", kv)
  500. }
  501. b.p("}")
  502. }
  503. func (b *builder) langIndex(s string) uint16 {
  504. if s == "und" {
  505. return 0
  506. }
  507. if i, ok := b.lang.find(s); ok {
  508. return uint16(i)
  509. }
  510. return uint16(strToInt(s)) + uint16(len(b.lang.s))
  511. }
  512. // inc advances the string to its lexicographical successor.
  513. func inc(s string) string {
  514. const maxTagLength = 4
  515. var buf [maxTagLength]byte
  516. intToStr(strToInt(strings.ToLower(s))+1, buf[:len(s)])
  517. for i := 0; i < len(s); i++ {
  518. if s[i] <= 'Z' {
  519. buf[i] -= 'a' - 'A'
  520. }
  521. }
  522. return string(buf[:len(s)])
  523. }
  524. func (b *builder) parseIndices() {
  525. meta := b.supp.Metadata
  526. for k, v := range b.registry {
  527. var ss *stringSet
  528. switch v.typ {
  529. case "language":
  530. if len(k) == 2 || v.suppressScript != "" || v.scope == "special" {
  531. b.lang.add(k)
  532. continue
  533. } else {
  534. ss = &b.langNoIndex
  535. }
  536. case "region":
  537. ss = &b.region
  538. case "script":
  539. ss = &b.script
  540. case "variant":
  541. ss = &b.variant
  542. default:
  543. continue
  544. }
  545. ss.add(k)
  546. }
  547. // Include any language for which there is data.
  548. for _, lang := range b.data.Locales() {
  549. if x := b.data.RawLDML(lang); false ||
  550. x.LocaleDisplayNames != nil ||
  551. x.Characters != nil ||
  552. x.Delimiters != nil ||
  553. x.Measurement != nil ||
  554. x.Dates != nil ||
  555. x.Numbers != nil ||
  556. x.Units != nil ||
  557. x.ListPatterns != nil ||
  558. x.Collations != nil ||
  559. x.Segmentations != nil ||
  560. x.Rbnf != nil ||
  561. x.Annotations != nil ||
  562. x.Metadata != nil {
  563. from := strings.Split(lang, "_")
  564. if lang := from[0]; lang != "root" {
  565. b.lang.add(lang)
  566. }
  567. }
  568. }
  569. // Include locales for plural rules, which uses a different structure.
  570. for _, plurals := range b.data.Supplemental().Plurals {
  571. for _, rules := range plurals.PluralRules {
  572. for _, lang := range strings.Split(rules.Locales, " ") {
  573. if lang = strings.Split(lang, "_")[0]; lang != "root" {
  574. b.lang.add(lang)
  575. }
  576. }
  577. }
  578. }
  579. // Include languages in likely subtags.
  580. for _, m := range b.supp.LikelySubtags.LikelySubtag {
  581. from := strings.Split(m.From, "_")
  582. b.lang.add(from[0])
  583. }
  584. // Include ISO-639 alpha-3 bibliographic entries.
  585. for _, a := range meta.Alias.LanguageAlias {
  586. if a.Reason == "bibliographic" {
  587. b.langNoIndex.add(a.Type)
  588. }
  589. }
  590. // Include regions in territoryAlias (not all are in the IANA registry!)
  591. for _, reg := range b.supp.Metadata.Alias.TerritoryAlias {
  592. if len(reg.Type) == 2 {
  593. b.region.add(reg.Type)
  594. }
  595. }
  596. for _, s := range b.lang.s {
  597. if len(s) == 3 {
  598. b.langNoIndex.remove(s)
  599. }
  600. }
  601. b.writeConst("numLanguages", len(b.lang.slice())+len(b.langNoIndex.slice()))
  602. b.writeConst("numScripts", len(b.script.slice()))
  603. b.writeConst("numRegions", len(b.region.slice()))
  604. // Add dummy codes at the start of each list to represent "unspecified".
  605. b.lang.add("---")
  606. b.script.add("----")
  607. b.region.add("---")
  608. // common locales
  609. b.locale.parse(meta.DefaultContent.Locales)
  610. }
  611. func (b *builder) computeRegionGroups() {
  612. b.groups = make(map[int]index)
  613. // Create group indices.
  614. for i := 1; b.region.s[i][0] < 'A'; i++ { // Base M49 indices on regionID.
  615. b.groups[i] = index(len(b.groups))
  616. }
  617. for _, g := range b.supp.TerritoryContainment.Group {
  618. group := b.region.index(g.Type)
  619. if _, ok := b.groups[group]; !ok {
  620. b.groups[group] = index(len(b.groups))
  621. }
  622. }
  623. if len(b.groups) > 32 {
  624. log.Fatalf("only 32 groups supported, found %d", len(b.groups))
  625. }
  626. b.writeConst("nRegionGroups", len(b.groups))
  627. }
  628. var langConsts = []string{
  629. "af", "am", "ar", "az", "bg", "bn", "ca", "cs", "da", "de", "el", "en", "es",
  630. "et", "fa", "fi", "fil", "fr", "gu", "he", "hi", "hr", "hu", "hy", "id", "is",
  631. "it", "ja", "ka", "kk", "km", "kn", "ko", "ky", "lo", "lt", "lv", "mk", "ml",
  632. "mn", "mo", "mr", "ms", "mul", "my", "nb", "ne", "nl", "no", "pa", "pl", "pt",
  633. "ro", "ru", "sh", "si", "sk", "sl", "sq", "sr", "sv", "sw", "ta", "te", "th",
  634. "tl", "tn", "tr", "uk", "ur", "uz", "vi", "zh", "zu",
  635. // constants for grandfathered tags (if not already defined)
  636. "jbo", "ami", "bnn", "hak", "tlh", "lb", "nv", "pwn", "tao", "tay", "tsu",
  637. "nn", "sfb", "vgt", "sgg", "cmn", "nan", "hsn",
  638. }
  639. // writeLanguage generates all tables needed for language canonicalization.
  640. func (b *builder) writeLanguage() {
  641. meta := b.supp.Metadata
  642. b.writeConst("nonCanonicalUnd", b.lang.index("und"))
  643. b.writeConsts(func(s string) int { return int(b.langIndex(s)) }, langConsts...)
  644. b.writeConst("langPrivateStart", b.langIndex("qaa"))
  645. b.writeConst("langPrivateEnd", b.langIndex("qtz"))
  646. // Get language codes that need to be mapped (overlong 3-letter codes,
  647. // deprecated 2-letter codes, legacy and grandfathered tags.)
  648. langAliasMap := stringSet{}
  649. aliasTypeMap := map[string]langAliasType{}
  650. // altLangISO3 get the alternative ISO3 names that need to be mapped.
  651. altLangISO3 := stringSet{}
  652. // Add dummy start to avoid the use of index 0.
  653. altLangISO3.add("---")
  654. altLangISO3.updateLater("---", "aa")
  655. lang := b.lang.clone()
  656. for _, a := range meta.Alias.LanguageAlias {
  657. if a.Replacement == "" {
  658. a.Replacement = "und"
  659. }
  660. // TODO: support mapping to tags
  661. repl := strings.SplitN(a.Replacement, "_", 2)[0]
  662. if a.Reason == "overlong" {
  663. if len(a.Replacement) == 2 && len(a.Type) == 3 {
  664. lang.updateLater(a.Replacement, a.Type)
  665. }
  666. } else if len(a.Type) <= 3 {
  667. switch a.Reason {
  668. case "macrolanguage":
  669. aliasTypeMap[a.Type] = langMacro
  670. case "deprecated":
  671. // handled elsewhere
  672. continue
  673. case "bibliographic", "legacy":
  674. if a.Type == "no" {
  675. continue
  676. }
  677. aliasTypeMap[a.Type] = langLegacy
  678. default:
  679. log.Fatalf("new %s alias: %s", a.Reason, a.Type)
  680. }
  681. langAliasMap.add(a.Type)
  682. langAliasMap.updateLater(a.Type, repl)
  683. }
  684. }
  685. // Manually add the mapping of "nb" (Norwegian) to its macro language.
  686. // This can be removed if CLDR adopts this change.
  687. langAliasMap.add("nb")
  688. langAliasMap.updateLater("nb", "no")
  689. aliasTypeMap["nb"] = langMacro
  690. for k, v := range b.registry {
  691. // Also add deprecated values for 3-letter ISO codes, which CLDR omits.
  692. if v.typ == "language" && v.deprecated != "" && v.preferred != "" {
  693. langAliasMap.add(k)
  694. langAliasMap.updateLater(k, v.preferred)
  695. aliasTypeMap[k] = langDeprecated
  696. }
  697. }
  698. // Fix CLDR mappings.
  699. lang.updateLater("tl", "tgl")
  700. lang.updateLater("sh", "hbs")
  701. lang.updateLater("mo", "mol")
  702. lang.updateLater("no", "nor")
  703. lang.updateLater("tw", "twi")
  704. lang.updateLater("nb", "nob")
  705. lang.updateLater("ak", "aka")
  706. // Ensure that each 2-letter code is matched with a 3-letter code.
  707. for _, v := range lang.s[1:] {
  708. s, ok := lang.update[v]
  709. if !ok {
  710. if s, ok = lang.update[langAliasMap.update[v]]; !ok {
  711. continue
  712. }
  713. lang.update[v] = s
  714. }
  715. if v[0] != s[0] {
  716. altLangISO3.add(s)
  717. altLangISO3.updateLater(s, v)
  718. }
  719. }
  720. // Complete canonialized language tags.
  721. lang.freeze()
  722. for i, v := range lang.s {
  723. // We can avoid these manual entries by using the IANI registry directly.
  724. // Seems easier to update the list manually, as changes are rare.
  725. // The panic in this loop will trigger if we miss an entry.
  726. add := ""
  727. if s, ok := lang.update[v]; ok {
  728. if s[0] == v[0] {
  729. add = s[1:]
  730. } else {
  731. add = string([]byte{0, byte(altLangISO3.index(s))})
  732. }
  733. } else if len(v) == 3 {
  734. add = "\x00"
  735. } else {
  736. log.Panicf("no data for long form of %q", v)
  737. }
  738. lang.s[i] += add
  739. }
  740. b.writeConst("lang", tag.Index(lang.join()))
  741. b.writeConst("langNoIndexOffset", len(b.lang.s))
  742. // space of all valid 3-letter language identifiers.
  743. b.writeBitVector("langNoIndex", b.langNoIndex.slice())
  744. altLangIndex := []uint16{}
  745. for i, s := range altLangISO3.slice() {
  746. altLangISO3.s[i] += string([]byte{byte(len(altLangIndex))})
  747. if i > 0 {
  748. idx := b.lang.index(altLangISO3.update[s])
  749. altLangIndex = append(altLangIndex, uint16(idx))
  750. }
  751. }
  752. b.writeConst("altLangISO3", tag.Index(altLangISO3.join()))
  753. b.writeSlice("altLangIndex", altLangIndex)
  754. b.writeSortedMap("langAliasMap", &langAliasMap, b.langIndex)
  755. types := make([]langAliasType, len(langAliasMap.s))
  756. for i, s := range langAliasMap.s {
  757. types[i] = aliasTypeMap[s]
  758. }
  759. b.writeSlice("langAliasTypes", types)
  760. }
  761. var scriptConsts = []string{
  762. "Latn", "Hani", "Hans", "Hant", "Qaaa", "Qaai", "Qabx", "Zinh", "Zyyy",
  763. "Zzzz",
  764. }
  765. func (b *builder) writeScript() {
  766. b.writeConsts(b.script.index, scriptConsts...)
  767. b.writeConst("script", tag.Index(b.script.join()))
  768. supp := make([]uint8, len(b.lang.slice()))
  769. for i, v := range b.lang.slice()[1:] {
  770. if sc := b.registry[v].suppressScript; sc != "" {
  771. supp[i+1] = uint8(b.script.index(sc))
  772. }
  773. }
  774. b.writeSlice("suppressScript", supp)
  775. // There is only one deprecated script in CLDR. This value is hard-coded.
  776. // We check here if the code must be updated.
  777. for _, a := range b.supp.Metadata.Alias.ScriptAlias {
  778. if a.Type != "Qaai" {
  779. log.Panicf("unexpected deprecated stript %q", a.Type)
  780. }
  781. }
  782. }
  783. func parseM49(s string) int16 {
  784. if len(s) == 0 {
  785. return 0
  786. }
  787. v, err := strconv.ParseUint(s, 10, 10)
  788. failOnError(err)
  789. return int16(v)
  790. }
  791. var regionConsts = []string{
  792. "001", "419", "BR", "CA", "ES", "GB", "MD", "PT", "UK", "US",
  793. "ZZ", "XA", "XC", "XK", // Unofficial tag for Kosovo.
  794. }
  795. func (b *builder) writeRegion() {
  796. b.writeConsts(b.region.index, regionConsts...)
  797. isoOffset := b.region.index("AA")
  798. m49map := make([]int16, len(b.region.slice()))
  799. fromM49map := make(map[int16]int)
  800. altRegionISO3 := ""
  801. altRegionIDs := []uint16{}
  802. b.writeConst("isoRegionOffset", isoOffset)
  803. // 2-letter region lookup and mapping to numeric codes.
  804. regionISO := b.region.clone()
  805. regionISO.s = regionISO.s[isoOffset:]
  806. regionISO.sorted = false
  807. regionTypes := make([]byte, len(b.region.s))
  808. // Is the region valid BCP 47?
  809. for s, e := range b.registry {
  810. if len(s) == 2 && s == strings.ToUpper(s) {
  811. i := b.region.index(s)
  812. for _, d := range e.description {
  813. if strings.Contains(d, "Private use") {
  814. regionTypes[i] = iso3166UserAssgined
  815. }
  816. }
  817. regionTypes[i] |= bcp47Region
  818. }
  819. }
  820. // Is the region a valid ccTLD?
  821. r := gen.OpenIANAFile("domains/root/db")
  822. defer r.Close()
  823. buf, err := ioutil.ReadAll(r)
  824. failOnError(err)
  825. re := regexp.MustCompile(`"/domains/root/db/([a-z]{2}).html"`)
  826. for _, m := range re.FindAllSubmatch(buf, -1) {
  827. i := b.region.index(strings.ToUpper(string(m[1])))
  828. regionTypes[i] |= ccTLD
  829. }
  830. b.writeSlice("regionTypes", regionTypes)
  831. iso3Set := make(map[string]int)
  832. update := func(iso2, iso3 string) {
  833. i := regionISO.index(iso2)
  834. if j, ok := iso3Set[iso3]; !ok && iso3[0] == iso2[0] {
  835. regionISO.s[i] += iso3[1:]
  836. iso3Set[iso3] = -1
  837. } else {
  838. if ok && j >= 0 {
  839. regionISO.s[i] += string([]byte{0, byte(j)})
  840. } else {
  841. iso3Set[iso3] = len(altRegionISO3)
  842. regionISO.s[i] += string([]byte{0, byte(len(altRegionISO3))})
  843. altRegionISO3 += iso3
  844. altRegionIDs = append(altRegionIDs, uint16(isoOffset+i))
  845. }
  846. }
  847. }
  848. for _, tc := range b.supp.CodeMappings.TerritoryCodes {
  849. i := regionISO.index(tc.Type) + isoOffset
  850. if d := m49map[i]; d != 0 {
  851. log.Panicf("%s found as a duplicate UN.M49 code of %03d", tc.Numeric, d)
  852. }
  853. m49 := parseM49(tc.Numeric)
  854. m49map[i] = m49
  855. if r := fromM49map[m49]; r == 0 {
  856. fromM49map[m49] = i
  857. } else if r != i {
  858. dep := b.registry[regionISO.s[r-isoOffset]].deprecated
  859. if t := b.registry[tc.Type]; t != nil && dep != "" && (t.deprecated == "" || t.deprecated > dep) {
  860. fromM49map[m49] = i
  861. }
  862. }
  863. }
  864. for _, ta := range b.supp.Metadata.Alias.TerritoryAlias {
  865. if len(ta.Type) == 3 && ta.Type[0] <= '9' && len(ta.Replacement) == 2 {
  866. from := parseM49(ta.Type)
  867. if r := fromM49map[from]; r == 0 {
  868. fromM49map[from] = regionISO.index(ta.Replacement) + isoOffset
  869. }
  870. }
  871. }
  872. for _, tc := range b.supp.CodeMappings.TerritoryCodes {
  873. if len(tc.Alpha3) == 3 {
  874. update(tc.Type, tc.Alpha3)
  875. }
  876. }
  877. // This entries are not included in territoryCodes. Mostly 3-letter variants
  878. // of deleted codes and an entry for QU.
  879. for _, m := range []struct{ iso2, iso3 string }{
  880. {"CT", "CTE"},
  881. {"DY", "DHY"},
  882. {"HV", "HVO"},
  883. {"JT", "JTN"},
  884. {"MI", "MID"},
  885. {"NH", "NHB"},
  886. {"NQ", "ATN"},
  887. {"PC", "PCI"},
  888. {"PU", "PUS"},
  889. {"PZ", "PCZ"},
  890. {"RH", "RHO"},
  891. {"VD", "VDR"},
  892. {"WK", "WAK"},
  893. // These three-letter codes are used for others as well.
  894. {"FQ", "ATF"},
  895. } {
  896. update(m.iso2, m.iso3)
  897. }
  898. for i, s := range regionISO.s {
  899. if len(s) != 4 {
  900. regionISO.s[i] = s + " "
  901. }
  902. }
  903. b.writeConst("regionISO", tag.Index(regionISO.join()))
  904. b.writeConst("altRegionISO3", altRegionISO3)
  905. b.writeSlice("altRegionIDs", altRegionIDs)
  906. // Create list of deprecated regions.
  907. // TODO: consider inserting SF -> FI. Not included by CLDR, but is the only
  908. // Transitionally-reserved mapping not included.
  909. regionOldMap := stringSet{}
  910. // Include regions in territoryAlias (not all are in the IANA registry!)
  911. for _, reg := range b.supp.Metadata.Alias.TerritoryAlias {
  912. if len(reg.Type) == 2 && reg.Reason == "deprecated" && len(reg.Replacement) == 2 {
  913. regionOldMap.add(reg.Type)
  914. regionOldMap.updateLater(reg.Type, reg.Replacement)
  915. i, _ := regionISO.find(reg.Type)
  916. j, _ := regionISO.find(reg.Replacement)
  917. if k := m49map[i+isoOffset]; k == 0 {
  918. m49map[i+isoOffset] = m49map[j+isoOffset]
  919. }
  920. }
  921. }
  922. b.writeSortedMap("regionOldMap", &regionOldMap, func(s string) uint16 {
  923. return uint16(b.region.index(s))
  924. })
  925. // 3-digit region lookup, groupings.
  926. for i := 1; i < isoOffset; i++ {
  927. m := parseM49(b.region.s[i])
  928. m49map[i] = m
  929. fromM49map[m] = i
  930. }
  931. b.writeSlice("m49", m49map)
  932. const (
  933. searchBits = 7
  934. regionBits = 9
  935. )
  936. if len(m49map) >= 1<<regionBits {
  937. log.Fatalf("Maximum number of regions exceeded: %d > %d", len(m49map), 1<<regionBits)
  938. }
  939. m49Index := [9]int16{}
  940. fromM49 := []uint16{}
  941. m49 := []int{}
  942. for k, _ := range fromM49map {
  943. m49 = append(m49, int(k))
  944. }
  945. sort.Ints(m49)
  946. for _, k := range m49[1:] {
  947. val := (k & (1<<searchBits - 1)) << regionBits
  948. fromM49 = append(fromM49, uint16(val|fromM49map[int16(k)]))
  949. m49Index[1:][k>>searchBits] = int16(len(fromM49))
  950. }
  951. b.writeSlice("m49Index", m49Index)
  952. b.writeSlice("fromM49", fromM49)
  953. }
  954. const (
  955. // TODO: put these lists in regionTypes as user data? Could be used for
  956. // various optimizations and refinements and could be exposed in the API.
  957. iso3166Except = "AC CP DG EA EU FX IC SU TA UK"
  958. iso3166Trans = "AN BU CS NT TP YU ZR" // SF is not in our set of Regions.
  959. // DY and RH are actually not deleted, but indeterminately reserved.
  960. iso3166DelCLDR = "CT DD DY FQ HV JT MI NH NQ PC PU PZ RH VD WK YD"
  961. )
  962. const (
  963. iso3166UserAssgined = 1 << iota
  964. ccTLD
  965. bcp47Region
  966. )
  967. func find(list []string, s string) int {
  968. for i, t := range list {
  969. if t == s {
  970. return i
  971. }
  972. }
  973. return -1
  974. }
  975. // writeVariants generates per-variant information and creates a map from variant
  976. // name to index value. We assign index values such that sorting multiple
  977. // variants by index value will result in the correct order.
  978. // There are two types of variants: specialized and general. Specialized variants
  979. // are only applicable to certain language or language-script pairs. Generalized
  980. // variants apply to any language. Generalized variants always sort after
  981. // specialized variants. We will therefore always assign a higher index value
  982. // to a generalized variant than any other variant. Generalized variants are
  983. // sorted alphabetically among themselves.
  984. // Specialized variants may also sort after other specialized variants. Such
  985. // variants will be ordered after any of the variants they may follow.
  986. // We assume that if a variant x is followed by a variant y, then for any prefix
  987. // p of x, p-x is a prefix of y. This allows us to order tags based on the
  988. // maximum of the length of any of its prefixes.
  989. // TODO: it is possible to define a set of Prefix values on variants such that
  990. // a total order cannot be defined to the point that this algorithm breaks.
  991. // In other words, we cannot guarantee the same order of variants for the
  992. // future using the same algorithm or for non-compliant combinations of
  993. // variants. For this reason, consider using simple alphabetic sorting
  994. // of variants and ignore Prefix restrictions altogether.
  995. func (b *builder) writeVariant() {
  996. generalized := stringSet{}
  997. specialized := stringSet{}
  998. specializedExtend := stringSet{}
  999. // Collate the variants by type and check assumptions.
  1000. for _, v := range b.variant.slice() {
  1001. e := b.registry[v]
  1002. if len(e.prefix) == 0 {
  1003. generalized.add(v)
  1004. continue
  1005. }
  1006. c := strings.Split(e.prefix[0], "-")
  1007. hasScriptOrRegion := false
  1008. if len(c) > 1 {
  1009. _, hasScriptOrRegion = b.script.find(c[1])
  1010. if !hasScriptOrRegion {
  1011. _, hasScriptOrRegion = b.region.find(c[1])
  1012. }
  1013. }
  1014. if len(c) == 1 || len(c) == 2 && hasScriptOrRegion {
  1015. // Variant is preceded by a language.
  1016. specialized.add(v)
  1017. continue
  1018. }
  1019. // Variant is preceded by another variant.
  1020. specializedExtend.add(v)
  1021. prefix := c[0] + "-"
  1022. if hasScriptOrRegion {
  1023. prefix += c[1]
  1024. }
  1025. for _, p := range e.prefix {
  1026. // Verify that the prefix minus the last element is a prefix of the
  1027. // predecessor element.
  1028. i := strings.LastIndex(p, "-")
  1029. pred := b.registry[p[i+1:]]
  1030. if find(pred.prefix, p[:i]) < 0 {
  1031. log.Fatalf("prefix %q for variant %q not consistent with predecessor spec", p, v)
  1032. }
  1033. // The sorting used below does not work in the general case. It works
  1034. // if we assume that variants that may be followed by others only have
  1035. // prefixes of the same length. Verify this.
  1036. count := strings.Count(p[:i], "-")
  1037. for _, q := range pred.prefix {
  1038. if c := strings.Count(q, "-"); c != count {
  1039. log.Fatalf("variant %q preceding %q has a prefix %q of size %d; want %d", p[i+1:], v, q, c, count)
  1040. }
  1041. }
  1042. if !strings.HasPrefix(p, prefix) {
  1043. log.Fatalf("prefix %q of variant %q should start with %q", p, v, prefix)
  1044. }
  1045. }
  1046. }
  1047. // Sort extended variants.
  1048. a := specializedExtend.s
  1049. less := func(v, w string) bool {
  1050. // Sort by the maximum number of elements.
  1051. maxCount := func(s string) (max int) {
  1052. for _, p := range b.registry[s].prefix {
  1053. if c := strings.Count(p, "-"); c > max {
  1054. max = c
  1055. }
  1056. }
  1057. return
  1058. }
  1059. if cv, cw := maxCount(v), maxCount(w); cv != cw {
  1060. return cv < cw
  1061. }
  1062. // Sort by name as tie breaker.
  1063. return v < w
  1064. }
  1065. sort.Sort(funcSorter{less, sort.StringSlice(a)})
  1066. specializedExtend.frozen = true
  1067. // Create index from variant name to index.
  1068. variantIndex := make(map[string]uint8)
  1069. add := func(s []string) {
  1070. for _, v := range s {
  1071. variantIndex[v] = uint8(len(variantIndex))
  1072. }
  1073. }
  1074. add(specialized.slice())
  1075. add(specializedExtend.s)
  1076. numSpecialized := len(variantIndex)
  1077. add(generalized.slice())
  1078. if n := len(variantIndex); n > 255 {
  1079. log.Fatalf("maximum number of variants exceeded: was %d; want <= 255", n)
  1080. }
  1081. b.writeMap("variantIndex", variantIndex)
  1082. b.writeConst("variantNumSpecialized", numSpecialized)
  1083. }
  1084. func (b *builder) writeLanguageInfo() {
  1085. }
  1086. // writeLikelyData writes tables that are used both for finding parent relations and for
  1087. // language matching. Each entry contains additional bits to indicate the status of the
  1088. // data to know when it cannot be used for parent relations.
  1089. func (b *builder) writeLikelyData() {
  1090. const (
  1091. isList = 1 << iota
  1092. scriptInFrom
  1093. regionInFrom
  1094. )
  1095. type ( // generated types
  1096. likelyScriptRegion struct {
  1097. region uint16
  1098. script uint8
  1099. flags uint8
  1100. }
  1101. likelyLangScript struct {
  1102. lang uint16
  1103. script uint8
  1104. flags uint8
  1105. }
  1106. likelyLangRegion struct {
  1107. lang uint16
  1108. region uint16
  1109. }
  1110. // likelyTag is used for getting likely tags for group regions, where
  1111. // the likely region might be a region contained in the group.
  1112. likelyTag struct {
  1113. lang uint16
  1114. region uint16
  1115. script uint8
  1116. }
  1117. )
  1118. var ( // generated variables
  1119. likelyRegionGroup = make([]likelyTag, len(b.groups))
  1120. likelyLang = make([]likelyScriptRegion, len(b.lang.s))
  1121. likelyRegion = make([]likelyLangScript, len(b.region.s))
  1122. likelyScript = make([]likelyLangRegion, len(b.script.s))
  1123. likelyLangList = []likelyScriptRegion{}
  1124. likelyRegionList = []likelyLangScript{}
  1125. )
  1126. type fromTo struct {
  1127. from, to []string
  1128. }
  1129. langToOther := map[int][]fromTo{}
  1130. regionToOther := map[int][]fromTo{}
  1131. for _, m := range b.supp.LikelySubtags.LikelySubtag {
  1132. from := strings.Split(m.From, "_")
  1133. to := strings.Split(m.To, "_")
  1134. if len(to) != 3 {
  1135. log.Fatalf("invalid number of subtags in %q: found %d, want 3", m.To, len(to))
  1136. }
  1137. if len(from) > 3 {
  1138. log.Fatalf("invalid number of subtags: found %d, want 1-3", len(from))
  1139. }
  1140. if from[0] != to[0] && from[0] != "und" {
  1141. log.Fatalf("unexpected language change in expansion: %s -> %s", from, to)
  1142. }
  1143. if len(from) == 3 {
  1144. if from[2] != to[2] {
  1145. log.Fatalf("unexpected region change in expansion: %s -> %s", from, to)
  1146. }
  1147. if from[0] != "und" {
  1148. log.Fatalf("unexpected fully specified from tag: %s -> %s", from, to)
  1149. }
  1150. }
  1151. if len(from) == 1 || from[0] != "und" {
  1152. id := 0
  1153. if from[0] != "und" {
  1154. id = b.lang.index(from[0])
  1155. }
  1156. langToOther[id] = append(langToOther[id], fromTo{from, to})
  1157. } else if len(from) == 2 && len(from[1]) == 4 {
  1158. sid := b.script.index(from[1])
  1159. likelyScript[sid].lang = uint16(b.langIndex(to[0]))
  1160. likelyScript[sid].region = uint16(b.region.index(to[2]))
  1161. } else {
  1162. r := b.region.index(from[len(from)-1])
  1163. if id, ok := b.groups[r]; ok {
  1164. if from[0] != "und" {
  1165. log.Fatalf("region changed unexpectedly: %s -> %s", from, to)
  1166. }
  1167. likelyRegionGroup[id].lang = uint16(b.langIndex(to[0]))
  1168. likelyRegionGroup[id].script = uint8(b.script.index(to[1]))
  1169. likelyRegionGroup[id].region = uint16(b.region.index(to[2]))
  1170. } else {
  1171. regionToOther[r] = append(regionToOther[r], fromTo{from, to})
  1172. }
  1173. }
  1174. }
  1175. b.writeType(likelyLangRegion{})
  1176. b.writeSlice("likelyScript", likelyScript)
  1177. for id := range b.lang.s {
  1178. list := langToOther[id]
  1179. if len(list) == 1 {
  1180. likelyLang[id].region = uint16(b.region.index(list[0].to[2]))
  1181. likelyLang[id].script = uint8(b.script.index(list[0].to[1]))
  1182. } else if len(list) > 1 {
  1183. likelyLang[id].flags = isList
  1184. likelyLang[id].region = uint16(len(likelyLangList))
  1185. likelyLang[id].script = uint8(len(list))
  1186. for _, x := range list {
  1187. flags := uint8(0)
  1188. if len(x.from) > 1 {
  1189. if x.from[1] == x.to[2] {
  1190. flags = regionInFrom
  1191. } else {
  1192. flags = scriptInFrom
  1193. }
  1194. }
  1195. likelyLangList = append(likelyLangList, likelyScriptRegion{
  1196. region: uint16(b.region.index(x.to[2])),
  1197. script: uint8(b.script.index(x.to[1])),
  1198. flags: flags,
  1199. })
  1200. }
  1201. }
  1202. }
  1203. // TODO: merge suppressScript data with this table.
  1204. b.writeType(likelyScriptRegion{})
  1205. b.writeSlice("likelyLang", likelyLang)
  1206. b.writeSlice("likelyLangList", likelyLangList)
  1207. for id := range b.region.s {
  1208. list := regionToOther[id]
  1209. if len(list) == 1 {
  1210. likelyRegion[id].lang = uint16(b.langIndex(list[0].to[0]))
  1211. likelyRegion[id].script = uint8(b.script.index(list[0].to[1]))
  1212. if len(list[0].from) > 2 {
  1213. likelyRegion[id].flags = scriptInFrom
  1214. }
  1215. } else if len(list) > 1 {
  1216. likelyRegion[id].flags = isList
  1217. likelyRegion[id].lang = uint16(len(likelyRegionList))
  1218. likelyRegion[id].script = uint8(len(list))
  1219. for i, x := range list {
  1220. if len(x.from) == 2 && i != 0 || i > 0 && len(x.from) != 3 {
  1221. log.Fatalf("unspecified script must be first in list: %v at %d", x.from, i)
  1222. }
  1223. x := likelyLangScript{
  1224. lang: uint16(b.langIndex(x.to[0])),
  1225. script: uint8(b.script.index(x.to[1])),
  1226. }
  1227. if len(list[0].from) > 2 {
  1228. x.flags = scriptInFrom
  1229. }
  1230. likelyRegionList = append(likelyRegionList, x)
  1231. }
  1232. }
  1233. }
  1234. b.writeType(likelyLangScript{})
  1235. b.writeSlice("likelyRegion", likelyRegion)
  1236. b.writeSlice("likelyRegionList", likelyRegionList)
  1237. b.writeType(likelyTag{})
  1238. b.writeSlice("likelyRegionGroup", likelyRegionGroup)
  1239. }
  1240. type mutualIntelligibility struct {
  1241. want, have uint16
  1242. conf uint8
  1243. oneway bool
  1244. }
  1245. type scriptIntelligibility struct {
  1246. lang uint16 // langID or 0 if *
  1247. want, have uint8
  1248. conf uint8
  1249. }
  1250. type sortByConf []mutualIntelligibility
  1251. func (l sortByConf) Less(a, b int) bool {
  1252. return l[a].conf > l[b].conf
  1253. }
  1254. func (l sortByConf) Swap(a, b int) {
  1255. l[a], l[b] = l[b], l[a]
  1256. }
  1257. func (l sortByConf) Len() int {
  1258. return len(l)
  1259. }
  1260. // toConf converts a percentage value [0, 100] to a confidence class.
  1261. func toConf(pct uint8) uint8 {
  1262. switch {
  1263. case pct == 100:
  1264. return 3 // Exact
  1265. case pct >= 90:
  1266. return 2 // High
  1267. case pct > 50:
  1268. return 1 // Low
  1269. default:
  1270. return 0 // No
  1271. }
  1272. }
  1273. // writeMatchData writes tables with languages and scripts for which there is
  1274. // mutual intelligibility. The data is based on CLDR's languageMatching data.
  1275. // Note that we use a different algorithm than the one defined by CLDR and that
  1276. // we slightly modify the data. For example, we convert scores to confidence levels.
  1277. // We also drop all region-related data as we use a different algorithm to
  1278. // determine region equivalence.
  1279. func (b *builder) writeMatchData() {
  1280. b.writeType(mutualIntelligibility{})
  1281. b.writeType(scriptIntelligibility{})
  1282. lm := b.supp.LanguageMatching.LanguageMatches
  1283. cldr.MakeSlice(&lm).SelectAnyOf("type", "written")
  1284. matchLang := []mutualIntelligibility{}
  1285. matchScript := []scriptIntelligibility{}
  1286. // Convert the languageMatch entries in lists keyed by desired language.
  1287. for _, m := range lm[0].LanguageMatch {
  1288. // Different versions of CLDR use different separators.
  1289. desired := strings.Replace(m.Desired, "-", "_", -1)
  1290. supported := strings.Replace(m.Supported, "-", "_", -1)
  1291. d := strings.Split(desired, "_")
  1292. s := strings.Split(supported, "_")
  1293. if len(d) != len(s) || len(d) > 2 {
  1294. // Skip all entries with regions and work around CLDR bug.
  1295. continue
  1296. }
  1297. pct, _ := strconv.ParseInt(m.Percent, 10, 8)
  1298. if len(d) == 2 && d[0] == s[0] && len(d[1]) == 4 {
  1299. // language-script pair.
  1300. lang := uint16(0)
  1301. if d[0] != "*" {
  1302. lang = uint16(b.langIndex(d[0]))
  1303. }
  1304. matchScript = append(matchScript, scriptIntelligibility{
  1305. lang: lang,
  1306. want: uint8(b.script.index(d[1])),
  1307. have: uint8(b.script.index(s[1])),
  1308. conf: toConf(uint8(pct)),
  1309. })
  1310. if m.Oneway != "true" {
  1311. matchScript = append(matchScript, scriptIntelligibility{
  1312. lang: lang,
  1313. want: uint8(b.script.index(s[1])),
  1314. have: uint8(b.script.index(d[1])),
  1315. conf: toConf(uint8(pct)),
  1316. })
  1317. }
  1318. } else if len(d) == 1 && d[0] != "*" {
  1319. if pct == 100 {
  1320. // nb == no is already handled by macro mapping. Check there
  1321. // really is only this case.
  1322. if d[0] != "no" || s[0] != "nb" {
  1323. log.Fatalf("unhandled equivalence %s == %s", s[0], d[0])
  1324. }
  1325. continue
  1326. }
  1327. matchLang = append(matchLang, mutualIntelligibility{
  1328. want: uint16(b.langIndex(d[0])),
  1329. have: uint16(b.langIndex(s[0])),
  1330. conf: uint8(pct),
  1331. oneway: m.Oneway == "true",
  1332. })
  1333. } else {
  1334. // TODO: Handle other mappings.
  1335. a := []string{"*;*", "*_*;*_*", "es_MX;es_419"}
  1336. s := strings.Join([]string{desired, supported}, ";")
  1337. if i := sort.SearchStrings(a, s); i == len(a) || a[i] != s {
  1338. log.Printf("%q not handled", s)
  1339. }
  1340. }
  1341. }
  1342. sort.Stable(sortByConf(matchLang))
  1343. // collapse percentage into confidence classes
  1344. for i, m := range matchLang {
  1345. matchLang[i].conf = toConf(m.conf)
  1346. }
  1347. b.writeSlice("matchLang", matchLang)
  1348. b.writeSlice("matchScript", matchScript)
  1349. }
  1350. func (b *builder) writeRegionInclusionData() {
  1351. var (
  1352. // mm holds for each group the set of groups with a distance of 1.
  1353. mm = make(map[int][]index)
  1354. // containment holds for each group the transitive closure of
  1355. // containment of other groups.
  1356. containment = make(map[index][]index)
  1357. )
  1358. for _, g := range b.supp.TerritoryContainment.Group {
  1359. group := b.region.index(g.Type)
  1360. groupIdx := b.groups[group]
  1361. for _, mem := range strings.Split(g.Contains, " ") {
  1362. r := b.region.index(mem)
  1363. mm[r] = append(mm[r], groupIdx)
  1364. if g, ok := b.groups[r]; ok {
  1365. mm[group] = append(mm[group], g)
  1366. containment[groupIdx] = append(containment[groupIdx], g)
  1367. }
  1368. }
  1369. }
  1370. regionContainment := make([]uint32, len(b.groups))
  1371. for _, g := range b.groups {
  1372. l := containment[g]
  1373. // Compute the transitive closure of containment.
  1374. for i := 0; i < len(l); i++ {
  1375. l = append(l, containment[l[i]]...)
  1376. }
  1377. // Compute the bitmask.
  1378. regionContainment[g] = 1 << g
  1379. for _, v := range l {
  1380. regionContainment[g] |= 1 << v
  1381. }
  1382. // log.Printf("%d: %X", g, regionContainment[g])
  1383. }
  1384. b.writeSlice("regionContainment", regionContainment)
  1385. regionInclusion := make([]uint8, len(b.region.s))
  1386. bvs := make(map[uint32]index)
  1387. // Make the first bitvector positions correspond with the groups.
  1388. for r, i := range b.groups {
  1389. bv := uint32(1 << i)
  1390. for _, g := range mm[r] {
  1391. bv |= 1 << g
  1392. }
  1393. bvs[bv] = i
  1394. regionInclusion[r] = uint8(bvs[bv])
  1395. }
  1396. for r := 1; r < len(b.region.s); r++ {
  1397. if _, ok := b.groups[r]; !ok {
  1398. bv := uint32(0)
  1399. for _, g := range mm[r] {
  1400. bv |= 1 << g
  1401. }
  1402. if bv == 0 {
  1403. // Pick the world for unspecified regions.
  1404. bv = 1 << b.groups[b.region.index("001")]
  1405. }
  1406. if _, ok := bvs[bv]; !ok {
  1407. bvs[bv] = index(len(bvs))
  1408. }
  1409. regionInclusion[r] = uint8(bvs[bv])
  1410. }
  1411. }
  1412. b.writeSlice("regionInclusion", regionInclusion)
  1413. regionInclusionBits := make([]uint32, len(bvs))
  1414. for k, v := range bvs {
  1415. regionInclusionBits[v] = uint32(k)
  1416. }
  1417. // Add bit vectors for increasingly large distances until a fixed point is reached.
  1418. regionInclusionNext := []uint8{}
  1419. for i := 0; i < len(regionInclusionBits); i++ {
  1420. bits := regionInclusionBits[i]
  1421. next := bits
  1422. for i := uint(0); i < uint(len(b.groups)); i++ {
  1423. if bits&(1<<i) != 0 {
  1424. next |= regionInclusionBits[i]
  1425. }
  1426. }
  1427. if _, ok := bvs[next]; !ok {
  1428. bvs[next] = index(len(bvs))
  1429. regionInclusionBits = append(regionInclusionBits, next)
  1430. }
  1431. regionInclusionNext = append(regionInclusionNext, uint8(bvs[next]))
  1432. }
  1433. b.writeSlice("regionInclusionBits", regionInclusionBits)
  1434. b.writeSlice("regionInclusionNext", regionInclusionNext)
  1435. }
  1436. type parentRel struct {
  1437. lang uint16
  1438. script uint8
  1439. maxScript uint8
  1440. toRegion uint16
  1441. fromRegion []uint16
  1442. }
  1443. func (b *builder) writeParents() {
  1444. b.writeType(parentRel{})
  1445. parents := []parentRel{}
  1446. // Construct parent overrides.
  1447. n := 0
  1448. for _, p := range b.data.Supplemental().ParentLocales.ParentLocale {
  1449. // Skipping non-standard scripts to root is implemented using addTags.
  1450. if p.Parent == "root" {
  1451. continue
  1452. }
  1453. sub := strings.Split(p.Parent, "_")
  1454. parent := parentRel{lang: b.langIndex(sub[0])}
  1455. if len(sub) == 2 {
  1456. // TODO: check that all undefined scripts are indeed Latn in these
  1457. // cases.
  1458. parent.maxScript = uint8(b.script.index("Latn"))
  1459. parent.toRegion = uint16(b.region.index(sub[1]))
  1460. } else {
  1461. parent.script = uint8(b.script.index(sub[1]))
  1462. parent.maxScript = parent.script
  1463. parent.toRegion = uint16(b.region.index(sub[2]))
  1464. }
  1465. for _, c := range strings.Split(p.Locales, " ") {
  1466. region := b.region.index(c[strings.LastIndex(c, "_")+1:])
  1467. parent.fromRegion = append(parent.fromRegion, uint16(region))
  1468. }
  1469. parents = append(parents, parent)
  1470. n += len(parent.fromRegion)
  1471. }
  1472. b.writeSliceAddSize("parents", n*2, parents)
  1473. }
  1474. func main() {
  1475. gen.Init()
  1476. gen.Repackage("gen_common.go", "common.go", "language")
  1477. w := gen.NewCodeWriter()
  1478. defer w.WriteGoFile("tables.go", "language")
  1479. fmt.Fprintln(w, `import "golang.org/x/text/internal/tag"`)
  1480. b := newBuilder(w)
  1481. gen.WriteCLDRVersion(w)
  1482. b.parseIndices()
  1483. b.writeType(fromTo{})
  1484. b.writeLanguage()
  1485. b.writeScript()
  1486. b.writeRegion()
  1487. b.writeVariant()
  1488. // TODO: b.writeLocale()
  1489. b.computeRegionGroups()
  1490. b.writeLikelyData()
  1491. b.writeMatchData()
  1492. b.writeRegionInclusionData()
  1493. b.writeParents()
  1494. }