You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1648 lines
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. // TODO: region inclusion data will probably not be use used in future matchers.
  612. func (b *builder) computeRegionGroups() {
  613. b.groups = make(map[int]index)
  614. // Create group indices.
  615. for i := 1; b.region.s[i][0] < 'A'; i++ { // Base M49 indices on regionID.
  616. b.groups[i] = index(len(b.groups))
  617. }
  618. for _, g := range b.supp.TerritoryContainment.Group {
  619. // Skip UN and EURO zone as they are flattening the containment
  620. // relationship.
  621. if g.Type == "EZ" || g.Type == "UN" {
  622. continue
  623. }
  624. group := b.region.index(g.Type)
  625. if _, ok := b.groups[group]; !ok {
  626. b.groups[group] = index(len(b.groups))
  627. }
  628. }
  629. if len(b.groups) > 32 {
  630. log.Fatalf("only 32 groups supported, found %d", len(b.groups))
  631. }
  632. b.writeConst("nRegionGroups", len(b.groups))
  633. }
  634. var langConsts = []string{
  635. "af", "am", "ar", "az", "bg", "bn", "ca", "cs", "da", "de", "el", "en", "es",
  636. "et", "fa", "fi", "fil", "fr", "gu", "he", "hi", "hr", "hu", "hy", "id", "is",
  637. "it", "ja", "ka", "kk", "km", "kn", "ko", "ky", "lo", "lt", "lv", "mk", "ml",
  638. "mn", "mo", "mr", "ms", "mul", "my", "nb", "ne", "nl", "no", "pa", "pl", "pt",
  639. "ro", "ru", "sh", "si", "sk", "sl", "sq", "sr", "sv", "sw", "ta", "te", "th",
  640. "tl", "tn", "tr", "uk", "ur", "uz", "vi", "zh", "zu",
  641. // constants for grandfathered tags (if not already defined)
  642. "jbo", "ami", "bnn", "hak", "tlh", "lb", "nv", "pwn", "tao", "tay", "tsu",
  643. "nn", "sfb", "vgt", "sgg", "cmn", "nan", "hsn",
  644. }
  645. // writeLanguage generates all tables needed for language canonicalization.
  646. func (b *builder) writeLanguage() {
  647. meta := b.supp.Metadata
  648. b.writeConst("nonCanonicalUnd", b.lang.index("und"))
  649. b.writeConsts(func(s string) int { return int(b.langIndex(s)) }, langConsts...)
  650. b.writeConst("langPrivateStart", b.langIndex("qaa"))
  651. b.writeConst("langPrivateEnd", b.langIndex("qtz"))
  652. // Get language codes that need to be mapped (overlong 3-letter codes,
  653. // deprecated 2-letter codes, legacy and grandfathered tags.)
  654. langAliasMap := stringSet{}
  655. aliasTypeMap := map[string]langAliasType{}
  656. // altLangISO3 get the alternative ISO3 names that need to be mapped.
  657. altLangISO3 := stringSet{}
  658. // Add dummy start to avoid the use of index 0.
  659. altLangISO3.add("---")
  660. altLangISO3.updateLater("---", "aa")
  661. lang := b.lang.clone()
  662. for _, a := range meta.Alias.LanguageAlias {
  663. if a.Replacement == "" {
  664. a.Replacement = "und"
  665. }
  666. // TODO: support mapping to tags
  667. repl := strings.SplitN(a.Replacement, "_", 2)[0]
  668. if a.Reason == "overlong" {
  669. if len(a.Replacement) == 2 && len(a.Type) == 3 {
  670. lang.updateLater(a.Replacement, a.Type)
  671. }
  672. } else if len(a.Type) <= 3 {
  673. switch a.Reason {
  674. case "macrolanguage":
  675. aliasTypeMap[a.Type] = langMacro
  676. case "deprecated":
  677. // handled elsewhere
  678. continue
  679. case "bibliographic", "legacy":
  680. if a.Type == "no" {
  681. continue
  682. }
  683. aliasTypeMap[a.Type] = langLegacy
  684. default:
  685. log.Fatalf("new %s alias: %s", a.Reason, a.Type)
  686. }
  687. langAliasMap.add(a.Type)
  688. langAliasMap.updateLater(a.Type, repl)
  689. }
  690. }
  691. // Manually add the mapping of "nb" (Norwegian) to its macro language.
  692. // This can be removed if CLDR adopts this change.
  693. langAliasMap.add("nb")
  694. langAliasMap.updateLater("nb", "no")
  695. aliasTypeMap["nb"] = langMacro
  696. for k, v := range b.registry {
  697. // Also add deprecated values for 3-letter ISO codes, which CLDR omits.
  698. if v.typ == "language" && v.deprecated != "" && v.preferred != "" {
  699. langAliasMap.add(k)
  700. langAliasMap.updateLater(k, v.preferred)
  701. aliasTypeMap[k] = langDeprecated
  702. }
  703. }
  704. // Fix CLDR mappings.
  705. lang.updateLater("tl", "tgl")
  706. lang.updateLater("sh", "hbs")
  707. lang.updateLater("mo", "mol")
  708. lang.updateLater("no", "nor")
  709. lang.updateLater("tw", "twi")
  710. lang.updateLater("nb", "nob")
  711. lang.updateLater("ak", "aka")
  712. lang.updateLater("bh", "bih")
  713. // Ensure that each 2-letter code is matched with a 3-letter code.
  714. for _, v := range lang.s[1:] {
  715. s, ok := lang.update[v]
  716. if !ok {
  717. if s, ok = lang.update[langAliasMap.update[v]]; !ok {
  718. continue
  719. }
  720. lang.update[v] = s
  721. }
  722. if v[0] != s[0] {
  723. altLangISO3.add(s)
  724. altLangISO3.updateLater(s, v)
  725. }
  726. }
  727. // Complete canonialized language tags.
  728. lang.freeze()
  729. for i, v := range lang.s {
  730. // We can avoid these manual entries by using the IANI registry directly.
  731. // Seems easier to update the list manually, as changes are rare.
  732. // The panic in this loop will trigger if we miss an entry.
  733. add := ""
  734. if s, ok := lang.update[v]; ok {
  735. if s[0] == v[0] {
  736. add = s[1:]
  737. } else {
  738. add = string([]byte{0, byte(altLangISO3.index(s))})
  739. }
  740. } else if len(v) == 3 {
  741. add = "\x00"
  742. } else {
  743. log.Panicf("no data for long form of %q", v)
  744. }
  745. lang.s[i] += add
  746. }
  747. b.writeConst("lang", tag.Index(lang.join()))
  748. b.writeConst("langNoIndexOffset", len(b.lang.s))
  749. // space of all valid 3-letter language identifiers.
  750. b.writeBitVector("langNoIndex", b.langNoIndex.slice())
  751. altLangIndex := []uint16{}
  752. for i, s := range altLangISO3.slice() {
  753. altLangISO3.s[i] += string([]byte{byte(len(altLangIndex))})
  754. if i > 0 {
  755. idx := b.lang.index(altLangISO3.update[s])
  756. altLangIndex = append(altLangIndex, uint16(idx))
  757. }
  758. }
  759. b.writeConst("altLangISO3", tag.Index(altLangISO3.join()))
  760. b.writeSlice("altLangIndex", altLangIndex)
  761. b.writeSortedMap("langAliasMap", &langAliasMap, b.langIndex)
  762. types := make([]langAliasType, len(langAliasMap.s))
  763. for i, s := range langAliasMap.s {
  764. types[i] = aliasTypeMap[s]
  765. }
  766. b.writeSlice("langAliasTypes", types)
  767. }
  768. var scriptConsts = []string{
  769. "Latn", "Hani", "Hans", "Hant", "Qaaa", "Qaai", "Qabx", "Zinh", "Zyyy",
  770. "Zzzz",
  771. }
  772. func (b *builder) writeScript() {
  773. b.writeConsts(b.script.index, scriptConsts...)
  774. b.writeConst("script", tag.Index(b.script.join()))
  775. supp := make([]uint8, len(b.lang.slice()))
  776. for i, v := range b.lang.slice()[1:] {
  777. if sc := b.registry[v].suppressScript; sc != "" {
  778. supp[i+1] = uint8(b.script.index(sc))
  779. }
  780. }
  781. b.writeSlice("suppressScript", supp)
  782. // There is only one deprecated script in CLDR. This value is hard-coded.
  783. // We check here if the code must be updated.
  784. for _, a := range b.supp.Metadata.Alias.ScriptAlias {
  785. if a.Type != "Qaai" {
  786. log.Panicf("unexpected deprecated stript %q", a.Type)
  787. }
  788. }
  789. }
  790. func parseM49(s string) int16 {
  791. if len(s) == 0 {
  792. return 0
  793. }
  794. v, err := strconv.ParseUint(s, 10, 10)
  795. failOnError(err)
  796. return int16(v)
  797. }
  798. var regionConsts = []string{
  799. "001", "419", "BR", "CA", "ES", "GB", "MD", "PT", "UK", "US",
  800. "ZZ", "XA", "XC", "XK", // Unofficial tag for Kosovo.
  801. }
  802. func (b *builder) writeRegion() {
  803. b.writeConsts(b.region.index, regionConsts...)
  804. isoOffset := b.region.index("AA")
  805. m49map := make([]int16, len(b.region.slice()))
  806. fromM49map := make(map[int16]int)
  807. altRegionISO3 := ""
  808. altRegionIDs := []uint16{}
  809. b.writeConst("isoRegionOffset", isoOffset)
  810. // 2-letter region lookup and mapping to numeric codes.
  811. regionISO := b.region.clone()
  812. regionISO.s = regionISO.s[isoOffset:]
  813. regionISO.sorted = false
  814. regionTypes := make([]byte, len(b.region.s))
  815. // Is the region valid BCP 47?
  816. for s, e := range b.registry {
  817. if len(s) == 2 && s == strings.ToUpper(s) {
  818. i := b.region.index(s)
  819. for _, d := range e.description {
  820. if strings.Contains(d, "Private use") {
  821. regionTypes[i] = iso3166UserAssgined
  822. }
  823. }
  824. regionTypes[i] |= bcp47Region
  825. }
  826. }
  827. // Is the region a valid ccTLD?
  828. r := gen.OpenIANAFile("domains/root/db")
  829. defer r.Close()
  830. buf, err := ioutil.ReadAll(r)
  831. failOnError(err)
  832. re := regexp.MustCompile(`"/domains/root/db/([a-z]{2}).html"`)
  833. for _, m := range re.FindAllSubmatch(buf, -1) {
  834. i := b.region.index(strings.ToUpper(string(m[1])))
  835. regionTypes[i] |= ccTLD
  836. }
  837. b.writeSlice("regionTypes", regionTypes)
  838. iso3Set := make(map[string]int)
  839. update := func(iso2, iso3 string) {
  840. i := regionISO.index(iso2)
  841. if j, ok := iso3Set[iso3]; !ok && iso3[0] == iso2[0] {
  842. regionISO.s[i] += iso3[1:]
  843. iso3Set[iso3] = -1
  844. } else {
  845. if ok && j >= 0 {
  846. regionISO.s[i] += string([]byte{0, byte(j)})
  847. } else {
  848. iso3Set[iso3] = len(altRegionISO3)
  849. regionISO.s[i] += string([]byte{0, byte(len(altRegionISO3))})
  850. altRegionISO3 += iso3
  851. altRegionIDs = append(altRegionIDs, uint16(isoOffset+i))
  852. }
  853. }
  854. }
  855. for _, tc := range b.supp.CodeMappings.TerritoryCodes {
  856. i := regionISO.index(tc.Type) + isoOffset
  857. if d := m49map[i]; d != 0 {
  858. log.Panicf("%s found as a duplicate UN.M49 code of %03d", tc.Numeric, d)
  859. }
  860. m49 := parseM49(tc.Numeric)
  861. m49map[i] = m49
  862. if r := fromM49map[m49]; r == 0 {
  863. fromM49map[m49] = i
  864. } else if r != i {
  865. dep := b.registry[regionISO.s[r-isoOffset]].deprecated
  866. if t := b.registry[tc.Type]; t != nil && dep != "" && (t.deprecated == "" || t.deprecated > dep) {
  867. fromM49map[m49] = i
  868. }
  869. }
  870. }
  871. for _, ta := range b.supp.Metadata.Alias.TerritoryAlias {
  872. if len(ta.Type) == 3 && ta.Type[0] <= '9' && len(ta.Replacement) == 2 {
  873. from := parseM49(ta.Type)
  874. if r := fromM49map[from]; r == 0 {
  875. fromM49map[from] = regionISO.index(ta.Replacement) + isoOffset
  876. }
  877. }
  878. }
  879. for _, tc := range b.supp.CodeMappings.TerritoryCodes {
  880. if len(tc.Alpha3) == 3 {
  881. update(tc.Type, tc.Alpha3)
  882. }
  883. }
  884. // This entries are not included in territoryCodes. Mostly 3-letter variants
  885. // of deleted codes and an entry for QU.
  886. for _, m := range []struct{ iso2, iso3 string }{
  887. {"CT", "CTE"},
  888. {"DY", "DHY"},
  889. {"HV", "HVO"},
  890. {"JT", "JTN"},
  891. {"MI", "MID"},
  892. {"NH", "NHB"},
  893. {"NQ", "ATN"},
  894. {"PC", "PCI"},
  895. {"PU", "PUS"},
  896. {"PZ", "PCZ"},
  897. {"RH", "RHO"},
  898. {"VD", "VDR"},
  899. {"WK", "WAK"},
  900. // These three-letter codes are used for others as well.
  901. {"FQ", "ATF"},
  902. } {
  903. update(m.iso2, m.iso3)
  904. }
  905. for i, s := range regionISO.s {
  906. if len(s) != 4 {
  907. regionISO.s[i] = s + " "
  908. }
  909. }
  910. b.writeConst("regionISO", tag.Index(regionISO.join()))
  911. b.writeConst("altRegionISO3", altRegionISO3)
  912. b.writeSlice("altRegionIDs", altRegionIDs)
  913. // Create list of deprecated regions.
  914. // TODO: consider inserting SF -> FI. Not included by CLDR, but is the only
  915. // Transitionally-reserved mapping not included.
  916. regionOldMap := stringSet{}
  917. // Include regions in territoryAlias (not all are in the IANA registry!)
  918. for _, reg := range b.supp.Metadata.Alias.TerritoryAlias {
  919. if len(reg.Type) == 2 && reg.Reason == "deprecated" && len(reg.Replacement) == 2 {
  920. regionOldMap.add(reg.Type)
  921. regionOldMap.updateLater(reg.Type, reg.Replacement)
  922. i, _ := regionISO.find(reg.Type)
  923. j, _ := regionISO.find(reg.Replacement)
  924. if k := m49map[i+isoOffset]; k == 0 {
  925. m49map[i+isoOffset] = m49map[j+isoOffset]
  926. }
  927. }
  928. }
  929. b.writeSortedMap("regionOldMap", &regionOldMap, func(s string) uint16 {
  930. return uint16(b.region.index(s))
  931. })
  932. // 3-digit region lookup, groupings.
  933. for i := 1; i < isoOffset; i++ {
  934. m := parseM49(b.region.s[i])
  935. m49map[i] = m
  936. fromM49map[m] = i
  937. }
  938. b.writeSlice("m49", m49map)
  939. const (
  940. searchBits = 7
  941. regionBits = 9
  942. )
  943. if len(m49map) >= 1<<regionBits {
  944. log.Fatalf("Maximum number of regions exceeded: %d > %d", len(m49map), 1<<regionBits)
  945. }
  946. m49Index := [9]int16{}
  947. fromM49 := []uint16{}
  948. m49 := []int{}
  949. for k, _ := range fromM49map {
  950. m49 = append(m49, int(k))
  951. }
  952. sort.Ints(m49)
  953. for _, k := range m49[1:] {
  954. val := (k & (1<<searchBits - 1)) << regionBits
  955. fromM49 = append(fromM49, uint16(val|fromM49map[int16(k)]))
  956. m49Index[1:][k>>searchBits] = int16(len(fromM49))
  957. }
  958. b.writeSlice("m49Index", m49Index)
  959. b.writeSlice("fromM49", fromM49)
  960. }
  961. const (
  962. // TODO: put these lists in regionTypes as user data? Could be used for
  963. // various optimizations and refinements and could be exposed in the API.
  964. iso3166Except = "AC CP DG EA EU FX IC SU TA UK"
  965. iso3166Trans = "AN BU CS NT TP YU ZR" // SF is not in our set of Regions.
  966. // DY and RH are actually not deleted, but indeterminately reserved.
  967. iso3166DelCLDR = "CT DD DY FQ HV JT MI NH NQ PC PU PZ RH VD WK YD"
  968. )
  969. const (
  970. iso3166UserAssgined = 1 << iota
  971. ccTLD
  972. bcp47Region
  973. )
  974. func find(list []string, s string) int {
  975. for i, t := range list {
  976. if t == s {
  977. return i
  978. }
  979. }
  980. return -1
  981. }
  982. // writeVariants generates per-variant information and creates a map from variant
  983. // name to index value. We assign index values such that sorting multiple
  984. // variants by index value will result in the correct order.
  985. // There are two types of variants: specialized and general. Specialized variants
  986. // are only applicable to certain language or language-script pairs. Generalized
  987. // variants apply to any language. Generalized variants always sort after
  988. // specialized variants. We will therefore always assign a higher index value
  989. // to a generalized variant than any other variant. Generalized variants are
  990. // sorted alphabetically among themselves.
  991. // Specialized variants may also sort after other specialized variants. Such
  992. // variants will be ordered after any of the variants they may follow.
  993. // We assume that if a variant x is followed by a variant y, then for any prefix
  994. // p of x, p-x is a prefix of y. This allows us to order tags based on the
  995. // maximum of the length of any of its prefixes.
  996. // TODO: it is possible to define a set of Prefix values on variants such that
  997. // a total order cannot be defined to the point that this algorithm breaks.
  998. // In other words, we cannot guarantee the same order of variants for the
  999. // future using the same algorithm or for non-compliant combinations of
  1000. // variants. For this reason, consider using simple alphabetic sorting
  1001. // of variants and ignore Prefix restrictions altogether.
  1002. func (b *builder) writeVariant() {
  1003. generalized := stringSet{}
  1004. specialized := stringSet{}
  1005. specializedExtend := stringSet{}
  1006. // Collate the variants by type and check assumptions.
  1007. for _, v := range b.variant.slice() {
  1008. e := b.registry[v]
  1009. if len(e.prefix) == 0 {
  1010. generalized.add(v)
  1011. continue
  1012. }
  1013. c := strings.Split(e.prefix[0], "-")
  1014. hasScriptOrRegion := false
  1015. if len(c) > 1 {
  1016. _, hasScriptOrRegion = b.script.find(c[1])
  1017. if !hasScriptOrRegion {
  1018. _, hasScriptOrRegion = b.region.find(c[1])
  1019. }
  1020. }
  1021. if len(c) == 1 || len(c) == 2 && hasScriptOrRegion {
  1022. // Variant is preceded by a language.
  1023. specialized.add(v)
  1024. continue
  1025. }
  1026. // Variant is preceded by another variant.
  1027. specializedExtend.add(v)
  1028. prefix := c[0] + "-"
  1029. if hasScriptOrRegion {
  1030. prefix += c[1]
  1031. }
  1032. for _, p := range e.prefix {
  1033. // Verify that the prefix minus the last element is a prefix of the
  1034. // predecessor element.
  1035. i := strings.LastIndex(p, "-")
  1036. pred := b.registry[p[i+1:]]
  1037. if find(pred.prefix, p[:i]) < 0 {
  1038. log.Fatalf("prefix %q for variant %q not consistent with predecessor spec", p, v)
  1039. }
  1040. // The sorting used below does not work in the general case. It works
  1041. // if we assume that variants that may be followed by others only have
  1042. // prefixes of the same length. Verify this.
  1043. count := strings.Count(p[:i], "-")
  1044. for _, q := range pred.prefix {
  1045. if c := strings.Count(q, "-"); c != count {
  1046. log.Fatalf("variant %q preceding %q has a prefix %q of size %d; want %d", p[i+1:], v, q, c, count)
  1047. }
  1048. }
  1049. if !strings.HasPrefix(p, prefix) {
  1050. log.Fatalf("prefix %q of variant %q should start with %q", p, v, prefix)
  1051. }
  1052. }
  1053. }
  1054. // Sort extended variants.
  1055. a := specializedExtend.s
  1056. less := func(v, w string) bool {
  1057. // Sort by the maximum number of elements.
  1058. maxCount := func(s string) (max int) {
  1059. for _, p := range b.registry[s].prefix {
  1060. if c := strings.Count(p, "-"); c > max {
  1061. max = c
  1062. }
  1063. }
  1064. return
  1065. }
  1066. if cv, cw := maxCount(v), maxCount(w); cv != cw {
  1067. return cv < cw
  1068. }
  1069. // Sort by name as tie breaker.
  1070. return v < w
  1071. }
  1072. sort.Sort(funcSorter{less, sort.StringSlice(a)})
  1073. specializedExtend.frozen = true
  1074. // Create index from variant name to index.
  1075. variantIndex := make(map[string]uint8)
  1076. add := func(s []string) {
  1077. for _, v := range s {
  1078. variantIndex[v] = uint8(len(variantIndex))
  1079. }
  1080. }
  1081. add(specialized.slice())
  1082. add(specializedExtend.s)
  1083. numSpecialized := len(variantIndex)
  1084. add(generalized.slice())
  1085. if n := len(variantIndex); n > 255 {
  1086. log.Fatalf("maximum number of variants exceeded: was %d; want <= 255", n)
  1087. }
  1088. b.writeMap("variantIndex", variantIndex)
  1089. b.writeConst("variantNumSpecialized", numSpecialized)
  1090. }
  1091. func (b *builder) writeLanguageInfo() {
  1092. }
  1093. // writeLikelyData writes tables that are used both for finding parent relations and for
  1094. // language matching. Each entry contains additional bits to indicate the status of the
  1095. // data to know when it cannot be used for parent relations.
  1096. func (b *builder) writeLikelyData() {
  1097. const (
  1098. isList = 1 << iota
  1099. scriptInFrom
  1100. regionInFrom
  1101. )
  1102. type ( // generated types
  1103. likelyScriptRegion struct {
  1104. region uint16
  1105. script uint8
  1106. flags uint8
  1107. }
  1108. likelyLangScript struct {
  1109. lang uint16
  1110. script uint8
  1111. flags uint8
  1112. }
  1113. likelyLangRegion struct {
  1114. lang uint16
  1115. region uint16
  1116. }
  1117. // likelyTag is used for getting likely tags for group regions, where
  1118. // the likely region might be a region contained in the group.
  1119. likelyTag struct {
  1120. lang uint16
  1121. region uint16
  1122. script uint8
  1123. }
  1124. )
  1125. var ( // generated variables
  1126. likelyRegionGroup = make([]likelyTag, len(b.groups))
  1127. likelyLang = make([]likelyScriptRegion, len(b.lang.s))
  1128. likelyRegion = make([]likelyLangScript, len(b.region.s))
  1129. likelyScript = make([]likelyLangRegion, len(b.script.s))
  1130. likelyLangList = []likelyScriptRegion{}
  1131. likelyRegionList = []likelyLangScript{}
  1132. )
  1133. type fromTo struct {
  1134. from, to []string
  1135. }
  1136. langToOther := map[int][]fromTo{}
  1137. regionToOther := map[int][]fromTo{}
  1138. for _, m := range b.supp.LikelySubtags.LikelySubtag {
  1139. from := strings.Split(m.From, "_")
  1140. to := strings.Split(m.To, "_")
  1141. if len(to) != 3 {
  1142. log.Fatalf("invalid number of subtags in %q: found %d, want 3", m.To, len(to))
  1143. }
  1144. if len(from) > 3 {
  1145. log.Fatalf("invalid number of subtags: found %d, want 1-3", len(from))
  1146. }
  1147. if from[0] != to[0] && from[0] != "und" {
  1148. log.Fatalf("unexpected language change in expansion: %s -> %s", from, to)
  1149. }
  1150. if len(from) == 3 {
  1151. if from[2] != to[2] {
  1152. log.Fatalf("unexpected region change in expansion: %s -> %s", from, to)
  1153. }
  1154. if from[0] != "und" {
  1155. log.Fatalf("unexpected fully specified from tag: %s -> %s", from, to)
  1156. }
  1157. }
  1158. if len(from) == 1 || from[0] != "und" {
  1159. id := 0
  1160. if from[0] != "und" {
  1161. id = b.lang.index(from[0])
  1162. }
  1163. langToOther[id] = append(langToOther[id], fromTo{from, to})
  1164. } else if len(from) == 2 && len(from[1]) == 4 {
  1165. sid := b.script.index(from[1])
  1166. likelyScript[sid].lang = uint16(b.langIndex(to[0]))
  1167. likelyScript[sid].region = uint16(b.region.index(to[2]))
  1168. } else {
  1169. r := b.region.index(from[len(from)-1])
  1170. if id, ok := b.groups[r]; ok {
  1171. if from[0] != "und" {
  1172. log.Fatalf("region changed unexpectedly: %s -> %s", from, to)
  1173. }
  1174. likelyRegionGroup[id].lang = uint16(b.langIndex(to[0]))
  1175. likelyRegionGroup[id].script = uint8(b.script.index(to[1]))
  1176. likelyRegionGroup[id].region = uint16(b.region.index(to[2]))
  1177. } else {
  1178. regionToOther[r] = append(regionToOther[r], fromTo{from, to})
  1179. }
  1180. }
  1181. }
  1182. b.writeType(likelyLangRegion{})
  1183. b.writeSlice("likelyScript", likelyScript)
  1184. for id := range b.lang.s {
  1185. list := langToOther[id]
  1186. if len(list) == 1 {
  1187. likelyLang[id].region = uint16(b.region.index(list[0].to[2]))
  1188. likelyLang[id].script = uint8(b.script.index(list[0].to[1]))
  1189. } else if len(list) > 1 {
  1190. likelyLang[id].flags = isList
  1191. likelyLang[id].region = uint16(len(likelyLangList))
  1192. likelyLang[id].script = uint8(len(list))
  1193. for _, x := range list {
  1194. flags := uint8(0)
  1195. if len(x.from) > 1 {
  1196. if x.from[1] == x.to[2] {
  1197. flags = regionInFrom
  1198. } else {
  1199. flags = scriptInFrom
  1200. }
  1201. }
  1202. likelyLangList = append(likelyLangList, likelyScriptRegion{
  1203. region: uint16(b.region.index(x.to[2])),
  1204. script: uint8(b.script.index(x.to[1])),
  1205. flags: flags,
  1206. })
  1207. }
  1208. }
  1209. }
  1210. // TODO: merge suppressScript data with this table.
  1211. b.writeType(likelyScriptRegion{})
  1212. b.writeSlice("likelyLang", likelyLang)
  1213. b.writeSlice("likelyLangList", likelyLangList)
  1214. for id := range b.region.s {
  1215. list := regionToOther[id]
  1216. if len(list) == 1 {
  1217. likelyRegion[id].lang = uint16(b.langIndex(list[0].to[0]))
  1218. likelyRegion[id].script = uint8(b.script.index(list[0].to[1]))
  1219. if len(list[0].from) > 2 {
  1220. likelyRegion[id].flags = scriptInFrom
  1221. }
  1222. } else if len(list) > 1 {
  1223. likelyRegion[id].flags = isList
  1224. likelyRegion[id].lang = uint16(len(likelyRegionList))
  1225. likelyRegion[id].script = uint8(len(list))
  1226. for i, x := range list {
  1227. if len(x.from) == 2 && i != 0 || i > 0 && len(x.from) != 3 {
  1228. log.Fatalf("unspecified script must be first in list: %v at %d", x.from, i)
  1229. }
  1230. x := likelyLangScript{
  1231. lang: uint16(b.langIndex(x.to[0])),
  1232. script: uint8(b.script.index(x.to[1])),
  1233. }
  1234. if len(list[0].from) > 2 {
  1235. x.flags = scriptInFrom
  1236. }
  1237. likelyRegionList = append(likelyRegionList, x)
  1238. }
  1239. }
  1240. }
  1241. b.writeType(likelyLangScript{})
  1242. b.writeSlice("likelyRegion", likelyRegion)
  1243. b.writeSlice("likelyRegionList", likelyRegionList)
  1244. b.writeType(likelyTag{})
  1245. b.writeSlice("likelyRegionGroup", likelyRegionGroup)
  1246. }
  1247. type mutualIntelligibility struct {
  1248. want, have uint16
  1249. conf uint8
  1250. oneway bool
  1251. }
  1252. type scriptIntelligibility struct {
  1253. lang uint16 // langID or 0 if *
  1254. want, have uint8
  1255. conf uint8
  1256. }
  1257. type sortByConf []mutualIntelligibility
  1258. func (l sortByConf) Less(a, b int) bool {
  1259. return l[a].conf > l[b].conf
  1260. }
  1261. func (l sortByConf) Swap(a, b int) {
  1262. l[a], l[b] = l[b], l[a]
  1263. }
  1264. func (l sortByConf) Len() int {
  1265. return len(l)
  1266. }
  1267. // toConf converts a percentage value [0, 100] to a confidence class.
  1268. func toConf(pct uint8) uint8 {
  1269. switch {
  1270. case pct == 100:
  1271. return 3 // Exact
  1272. case pct >= 90:
  1273. return 2 // High
  1274. case pct > 50:
  1275. return 1 // Low
  1276. default:
  1277. return 0 // No
  1278. }
  1279. }
  1280. // writeMatchData writes tables with languages and scripts for which there is
  1281. // mutual intelligibility. The data is based on CLDR's languageMatching data.
  1282. // Note that we use a different algorithm than the one defined by CLDR and that
  1283. // we slightly modify the data. For example, we convert scores to confidence levels.
  1284. // We also drop all region-related data as we use a different algorithm to
  1285. // determine region equivalence.
  1286. func (b *builder) writeMatchData() {
  1287. b.writeType(mutualIntelligibility{})
  1288. b.writeType(scriptIntelligibility{})
  1289. lm := b.supp.LanguageMatching.LanguageMatches
  1290. cldr.MakeSlice(&lm).SelectAnyOf("type", "written")
  1291. matchLang := []mutualIntelligibility{}
  1292. matchScript := []scriptIntelligibility{}
  1293. // Convert the languageMatch entries in lists keyed by desired language.
  1294. for _, m := range lm[0].LanguageMatch {
  1295. // Different versions of CLDR use different separators.
  1296. desired := strings.Replace(m.Desired, "-", "_", -1)
  1297. supported := strings.Replace(m.Supported, "-", "_", -1)
  1298. d := strings.Split(desired, "_")
  1299. s := strings.Split(supported, "_")
  1300. if len(d) != len(s) || len(d) > 2 {
  1301. // Skip all entries with regions and work around CLDR bug.
  1302. continue
  1303. }
  1304. pct, _ := strconv.ParseInt(m.Percent, 10, 8)
  1305. if len(d) == 2 && d[0] == s[0] && len(d[1]) == 4 {
  1306. // language-script pair.
  1307. lang := uint16(0)
  1308. if d[0] != "*" {
  1309. lang = uint16(b.langIndex(d[0]))
  1310. }
  1311. matchScript = append(matchScript, scriptIntelligibility{
  1312. lang: lang,
  1313. want: uint8(b.script.index(d[1])),
  1314. have: uint8(b.script.index(s[1])),
  1315. conf: toConf(uint8(pct)),
  1316. })
  1317. if m.Oneway != "true" {
  1318. matchScript = append(matchScript, scriptIntelligibility{
  1319. lang: lang,
  1320. want: uint8(b.script.index(s[1])),
  1321. have: uint8(b.script.index(d[1])),
  1322. conf: toConf(uint8(pct)),
  1323. })
  1324. }
  1325. } else if len(d) == 1 && d[0] != "*" {
  1326. if pct == 100 {
  1327. // nb == no is already handled by macro mapping. Check there
  1328. // really is only this case.
  1329. if d[0] != "no" || s[0] != "nb" {
  1330. log.Fatalf("unhandled equivalence %s == %s", s[0], d[0])
  1331. }
  1332. continue
  1333. }
  1334. matchLang = append(matchLang, mutualIntelligibility{
  1335. want: uint16(b.langIndex(d[0])),
  1336. have: uint16(b.langIndex(s[0])),
  1337. conf: uint8(pct),
  1338. oneway: m.Oneway == "true",
  1339. })
  1340. } else {
  1341. // TODO: Handle other mappings.
  1342. a := []string{"*;*", "*_*;*_*", "es_MX;es_419"}
  1343. s := strings.Join([]string{desired, supported}, ";")
  1344. if i := sort.SearchStrings(a, s); i == len(a) || a[i] != s {
  1345. log.Printf("%q not handled", s)
  1346. }
  1347. }
  1348. }
  1349. sort.Stable(sortByConf(matchLang))
  1350. // collapse percentage into confidence classes
  1351. for i, m := range matchLang {
  1352. matchLang[i].conf = toConf(m.conf)
  1353. }
  1354. b.writeSlice("matchLang", matchLang)
  1355. b.writeSlice("matchScript", matchScript)
  1356. }
  1357. func (b *builder) writeRegionInclusionData() {
  1358. var (
  1359. // mm holds for each group the set of groups with a distance of 1.
  1360. mm = make(map[int][]index)
  1361. // containment holds for each group the transitive closure of
  1362. // containment of other groups.
  1363. containment = make(map[index][]index)
  1364. )
  1365. for _, g := range b.supp.TerritoryContainment.Group {
  1366. // Skip UN and EURO zone as they are flattening the containment
  1367. // relationship.
  1368. if g.Type == "EZ" || g.Type == "UN" {
  1369. continue
  1370. }
  1371. group := b.region.index(g.Type)
  1372. groupIdx := b.groups[group]
  1373. for _, mem := range strings.Split(g.Contains, " ") {
  1374. r := b.region.index(mem)
  1375. mm[r] = append(mm[r], groupIdx)
  1376. if g, ok := b.groups[r]; ok {
  1377. mm[group] = append(mm[group], g)
  1378. containment[groupIdx] = append(containment[groupIdx], g)
  1379. }
  1380. }
  1381. }
  1382. regionContainment := make([]uint32, len(b.groups))
  1383. for _, g := range b.groups {
  1384. l := containment[g]
  1385. // Compute the transitive closure of containment.
  1386. for i := 0; i < len(l); i++ {
  1387. l = append(l, containment[l[i]]...)
  1388. }
  1389. // Compute the bitmask.
  1390. regionContainment[g] = 1 << g
  1391. for _, v := range l {
  1392. regionContainment[g] |= 1 << v
  1393. }
  1394. // log.Printf("%d: %X", g, regionContainment[g])
  1395. }
  1396. b.writeSlice("regionContainment", regionContainment)
  1397. regionInclusion := make([]uint8, len(b.region.s))
  1398. bvs := make(map[uint32]index)
  1399. // Make the first bitvector positions correspond with the groups.
  1400. for r, i := range b.groups {
  1401. bv := uint32(1 << i)
  1402. for _, g := range mm[r] {
  1403. bv |= 1 << g
  1404. }
  1405. bvs[bv] = i
  1406. regionInclusion[r] = uint8(bvs[bv])
  1407. }
  1408. for r := 1; r < len(b.region.s); r++ {
  1409. if _, ok := b.groups[r]; !ok {
  1410. bv := uint32(0)
  1411. for _, g := range mm[r] {
  1412. bv |= 1 << g
  1413. }
  1414. if bv == 0 {
  1415. // Pick the world for unspecified regions.
  1416. bv = 1 << b.groups[b.region.index("001")]
  1417. }
  1418. if _, ok := bvs[bv]; !ok {
  1419. bvs[bv] = index(len(bvs))
  1420. }
  1421. regionInclusion[r] = uint8(bvs[bv])
  1422. }
  1423. }
  1424. b.writeSlice("regionInclusion", regionInclusion)
  1425. regionInclusionBits := make([]uint32, len(bvs))
  1426. for k, v := range bvs {
  1427. regionInclusionBits[v] = uint32(k)
  1428. }
  1429. // Add bit vectors for increasingly large distances until a fixed point is reached.
  1430. regionInclusionNext := []uint8{}
  1431. for i := 0; i < len(regionInclusionBits); i++ {
  1432. bits := regionInclusionBits[i]
  1433. next := bits
  1434. for i := uint(0); i < uint(len(b.groups)); i++ {
  1435. if bits&(1<<i) != 0 {
  1436. next |= regionInclusionBits[i]
  1437. }
  1438. }
  1439. if _, ok := bvs[next]; !ok {
  1440. bvs[next] = index(len(bvs))
  1441. regionInclusionBits = append(regionInclusionBits, next)
  1442. }
  1443. regionInclusionNext = append(regionInclusionNext, uint8(bvs[next]))
  1444. }
  1445. b.writeSlice("regionInclusionBits", regionInclusionBits)
  1446. b.writeSlice("regionInclusionNext", regionInclusionNext)
  1447. }
  1448. type parentRel struct {
  1449. lang uint16
  1450. script uint8
  1451. maxScript uint8
  1452. toRegion uint16
  1453. fromRegion []uint16
  1454. }
  1455. func (b *builder) writeParents() {
  1456. b.writeType(parentRel{})
  1457. parents := []parentRel{}
  1458. // Construct parent overrides.
  1459. n := 0
  1460. for _, p := range b.data.Supplemental().ParentLocales.ParentLocale {
  1461. // Skipping non-standard scripts to root is implemented using addTags.
  1462. if p.Parent == "root" {
  1463. continue
  1464. }
  1465. sub := strings.Split(p.Parent, "_")
  1466. parent := parentRel{lang: b.langIndex(sub[0])}
  1467. if len(sub) == 2 {
  1468. // TODO: check that all undefined scripts are indeed Latn in these
  1469. // cases.
  1470. parent.maxScript = uint8(b.script.index("Latn"))
  1471. parent.toRegion = uint16(b.region.index(sub[1]))
  1472. } else {
  1473. parent.script = uint8(b.script.index(sub[1]))
  1474. parent.maxScript = parent.script
  1475. parent.toRegion = uint16(b.region.index(sub[2]))
  1476. }
  1477. for _, c := range strings.Split(p.Locales, " ") {
  1478. region := b.region.index(c[strings.LastIndex(c, "_")+1:])
  1479. parent.fromRegion = append(parent.fromRegion, uint16(region))
  1480. }
  1481. parents = append(parents, parent)
  1482. n += len(parent.fromRegion)
  1483. }
  1484. b.writeSliceAddSize("parents", n*2, parents)
  1485. }
  1486. func main() {
  1487. gen.Init()
  1488. gen.Repackage("gen_common.go", "common.go", "language")
  1489. w := gen.NewCodeWriter()
  1490. defer w.WriteGoFile("tables.go", "language")
  1491. fmt.Fprintln(w, `import "golang.org/x/text/internal/tag"`)
  1492. b := newBuilder(w)
  1493. gen.WriteCLDRVersion(w)
  1494. b.parseIndices()
  1495. b.writeType(fromTo{})
  1496. b.writeLanguage()
  1497. b.writeScript()
  1498. b.writeRegion()
  1499. b.writeVariant()
  1500. // TODO: b.writeLocale()
  1501. b.computeRegionGroups()
  1502. b.writeLikelyData()
  1503. b.writeMatchData()
  1504. b.writeRegionInclusionData()
  1505. b.writeParents()
  1506. }