gen.go 42 KB

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