gen.go 42 KB

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