gen.go 48 KB

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