gen.go 25 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030
  1. // Copyright 2009 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. //go:build ignore
  5. // +build ignore
  6. // Unicode table generator.
  7. // Data read from the web.
  8. package main
  9. import (
  10. "flag"
  11. "fmt"
  12. "log"
  13. "os"
  14. "regexp"
  15. "sort"
  16. "strings"
  17. "unicode"
  18. "golang.org/x/text/internal/gen"
  19. "golang.org/x/text/internal/ucd"
  20. "golang.org/x/text/unicode/rangetable"
  21. )
  22. func main() {
  23. flag.Parse()
  24. setupOutput()
  25. loadChars() // always needed
  26. loadCasefold()
  27. printCategories()
  28. printScriptOrProperty(false)
  29. printScriptOrProperty(true)
  30. printCases()
  31. printLatinProperties()
  32. printCasefold()
  33. printSizes()
  34. flushOutput()
  35. }
  36. func defaultVersion() string {
  37. if v := os.Getenv("UNICODE_VERSION"); v != "" {
  38. return v
  39. }
  40. return unicode.Version
  41. }
  42. var tablelist = flag.String("tables",
  43. "all",
  44. "comma-separated list of which tables to generate; can be letter")
  45. var scriptlist = flag.String("scripts",
  46. "all",
  47. "comma-separated list of which script tables to generate")
  48. var proplist = flag.String("props",
  49. "all",
  50. "comma-separated list of which property tables to generate")
  51. var cases = flag.Bool("cases",
  52. true,
  53. "generate case tables")
  54. var test = flag.Bool("test",
  55. false,
  56. "test existing tables; can be used to compare web data with package data")
  57. var scriptRe = regexp.MustCompile(`^([0-9A-F]+)(\.\.[0-9A-F]+)? *; ([A-Za-z_]+)$`)
  58. var logger = log.New(os.Stderr, "", log.Lshortfile)
  59. var output *gen.CodeWriter
  60. func setupOutput() {
  61. output = gen.NewCodeWriter()
  62. }
  63. func flushOutput() {
  64. output.WriteGoFile("tables.go", "unicode")
  65. }
  66. func printf(format string, args ...interface{}) {
  67. fmt.Fprintf(output, format, args...)
  68. }
  69. func print(args ...interface{}) {
  70. fmt.Fprint(output, args...)
  71. }
  72. func println(args ...interface{}) {
  73. fmt.Fprintln(output, args...)
  74. }
  75. var category = map[string]bool{
  76. // Nd Lu etc.
  77. // We use one-character names to identify merged categories
  78. "L": true, // Lu Ll Lt Lm Lo
  79. "P": true, // Pc Pd Ps Pe Pu Pf Po
  80. "M": true, // Mn Mc Me
  81. "N": true, // Nd Nl No
  82. "S": true, // Sm Sc Sk So
  83. "Z": true, // Zs Zl Zp
  84. "C": true, // Cc Cf Cs Co Cn
  85. }
  86. // This contains only the properties we're interested in.
  87. type Char struct {
  88. codePoint rune // if zero, this index is not a valid code point.
  89. category string
  90. upperCase rune
  91. lowerCase rune
  92. titleCase rune
  93. foldCase rune // simple case folding
  94. caseOrbit rune // next in simple case folding orbit
  95. }
  96. const MaxChar = 0x10FFFF
  97. var chars = make([]Char, MaxChar+1)
  98. var scripts = make(map[string][]rune)
  99. var props = make(map[string][]rune) // a property looks like a script; can share the format
  100. func allCategories() []string {
  101. a := make([]string, 0, len(category))
  102. for k := range category {
  103. a = append(a, k)
  104. }
  105. sort.Strings(a)
  106. return a
  107. }
  108. func all(scripts map[string][]rune) []string {
  109. a := make([]string, 0, len(scripts))
  110. for k := range scripts {
  111. a = append(a, k)
  112. }
  113. sort.Strings(a)
  114. return a
  115. }
  116. func allCatFold(m map[string]map[rune]bool) []string {
  117. a := make([]string, 0, len(m))
  118. for k := range m {
  119. a = append(a, k)
  120. }
  121. sort.Strings(a)
  122. return a
  123. }
  124. func categoryOp(code rune, class uint8) bool {
  125. category := chars[code].category
  126. return len(category) > 0 && category[0] == class
  127. }
  128. func loadChars() {
  129. ucd.Parse(gen.OpenUCDFile("UnicodeData.txt"), func(p *ucd.Parser) {
  130. c := Char{codePoint: p.Rune(0)}
  131. getRune := func(field int) rune {
  132. if p.String(field) == "" {
  133. return 0
  134. }
  135. return p.Rune(field)
  136. }
  137. c.category = p.String(ucd.GeneralCategory)
  138. category[c.category] = true
  139. switch c.category {
  140. case "Nd":
  141. // Decimal digit
  142. p.Int(ucd.NumericValue)
  143. case "Lu":
  144. c.upperCase = getRune(ucd.CodePoint)
  145. c.lowerCase = getRune(ucd.SimpleLowercaseMapping)
  146. c.titleCase = getRune(ucd.SimpleTitlecaseMapping)
  147. case "Ll":
  148. c.upperCase = getRune(ucd.SimpleUppercaseMapping)
  149. c.lowerCase = getRune(ucd.CodePoint)
  150. c.titleCase = getRune(ucd.SimpleTitlecaseMapping)
  151. case "Lt":
  152. c.upperCase = getRune(ucd.SimpleUppercaseMapping)
  153. c.lowerCase = getRune(ucd.SimpleLowercaseMapping)
  154. c.titleCase = getRune(ucd.CodePoint)
  155. default:
  156. c.upperCase = getRune(ucd.SimpleUppercaseMapping)
  157. c.lowerCase = getRune(ucd.SimpleLowercaseMapping)
  158. c.titleCase = getRune(ucd.SimpleTitlecaseMapping)
  159. }
  160. chars[c.codePoint] = c
  161. })
  162. }
  163. func loadCasefold() {
  164. ucd.Parse(gen.OpenUCDFile("CaseFolding.txt"), func(p *ucd.Parser) {
  165. kind := p.String(1)
  166. if kind != "C" && kind != "S" {
  167. // Only care about 'common' and 'simple' foldings.
  168. return
  169. }
  170. p1 := p.Rune(0)
  171. p2 := p.Rune(2)
  172. chars[p1].foldCase = rune(p2)
  173. })
  174. }
  175. var categoryMapping = map[string]string{
  176. "Lu": "Letter, uppercase",
  177. "Ll": "Letter, lowercase",
  178. "Lt": "Letter, titlecase",
  179. "Lm": "Letter, modifier",
  180. "Lo": "Letter, other",
  181. "Mn": "Mark, nonspacing",
  182. "Mc": "Mark, spacing combining",
  183. "Me": "Mark, enclosing",
  184. "Nd": "Number, decimal digit",
  185. "Nl": "Number, letter",
  186. "No": "Number, other",
  187. "Pc": "Punctuation, connector",
  188. "Pd": "Punctuation, dash",
  189. "Ps": "Punctuation, open",
  190. "Pe": "Punctuation, close",
  191. "Pi": "Punctuation, initial quote",
  192. "Pf": "Punctuation, final quote",
  193. "Po": "Punctuation, other",
  194. "Sm": "Symbol, math",
  195. "Sc": "Symbol, currency",
  196. "Sk": "Symbol, modifier",
  197. "So": "Symbol, other",
  198. "Zs": "Separator, space",
  199. "Zl": "Separator, line",
  200. "Zp": "Separator, paragraph",
  201. "Cc": "Other, control",
  202. "Cf": "Other, format",
  203. "Cs": "Other, surrogate",
  204. "Co": "Other, private use",
  205. "Cn": "Other, not assigned",
  206. }
  207. func printCategories() {
  208. if *tablelist == "" {
  209. return
  210. }
  211. // Find out which categories to dump
  212. list := strings.Split(*tablelist, ",")
  213. if *tablelist == "all" {
  214. list = allCategories()
  215. }
  216. if *test {
  217. fullCategoryTest(list)
  218. return
  219. }
  220. println("// Version is the Unicode edition from which the tables are derived.")
  221. printf("const Version = %q\n\n", gen.UnicodeVersion())
  222. if *tablelist == "all" {
  223. println("// Categories is the set of Unicode category tables.")
  224. println("var Categories = map[string] *RangeTable {")
  225. for _, k := range allCategories() {
  226. printf("\t%q: %s,\n", k, k)
  227. }
  228. print("}\n\n")
  229. }
  230. decl := make(sort.StringSlice, len(list))
  231. ndecl := 0
  232. for _, name := range list {
  233. if _, ok := category[name]; !ok {
  234. logger.Fatal("unknown category", name)
  235. }
  236. // We generate an UpperCase name to serve as concise documentation and an _UnderScored
  237. // name to store the data. This stops godoc dumping all the tables but keeps them
  238. // available to clients.
  239. // Cases deserving special comments
  240. varDecl := ""
  241. switch name {
  242. case "C":
  243. varDecl = "\tOther = _C; // Other/C is the set of Unicode control and special characters, category C.\n"
  244. varDecl += "\tC = _C\n"
  245. case "L":
  246. varDecl = "\tLetter = _L; // Letter/L is the set of Unicode letters, category L.\n"
  247. varDecl += "\tL = _L\n"
  248. case "M":
  249. varDecl = "\tMark = _M; // Mark/M is the set of Unicode mark characters, category M.\n"
  250. varDecl += "\tM = _M\n"
  251. case "N":
  252. varDecl = "\tNumber = _N; // Number/N is the set of Unicode number characters, category N.\n"
  253. varDecl += "\tN = _N\n"
  254. case "P":
  255. varDecl = "\tPunct = _P; // Punct/P is the set of Unicode punctuation characters, category P.\n"
  256. varDecl += "\tP = _P\n"
  257. case "S":
  258. varDecl = "\tSymbol = _S; // Symbol/S is the set of Unicode symbol characters, category S.\n"
  259. varDecl += "\tS = _S\n"
  260. case "Z":
  261. varDecl = "\tSpace = _Z; // Space/Z is the set of Unicode space characters, category Z.\n"
  262. varDecl += "\tZ = _Z\n"
  263. case "Nd":
  264. varDecl = "\tDigit = _Nd; // Digit is the set of Unicode characters with the \"decimal digit\" property.\n"
  265. case "Lu":
  266. varDecl = "\tUpper = _Lu; // Upper is the set of Unicode upper case letters.\n"
  267. case "Ll":
  268. varDecl = "\tLower = _Ll; // Lower is the set of Unicode lower case letters.\n"
  269. case "Lt":
  270. varDecl = "\tTitle = _Lt; // Title is the set of Unicode title case letters.\n"
  271. }
  272. if len(name) > 1 {
  273. desc, ok := categoryMapping[name]
  274. if ok {
  275. varDecl += fmt.Sprintf(
  276. "\t%s = _%s; // %s is the set of Unicode characters in category %s (%s).\n",
  277. name, name, name, name, desc)
  278. } else {
  279. varDecl += fmt.Sprintf(
  280. "\t%s = _%s; // %s is the set of Unicode characters in category %s.\n",
  281. name, name, name, name)
  282. }
  283. }
  284. decl[ndecl] = varDecl
  285. ndecl++
  286. if len(name) == 1 { // unified categories
  287. dumpRange(
  288. "_"+name,
  289. func(code rune) bool { return categoryOp(code, name[0]) })
  290. continue
  291. }
  292. dumpRange("_"+name,
  293. func(code rune) bool { return chars[code].category == name })
  294. }
  295. decl.Sort()
  296. println("// These variables have type *RangeTable.")
  297. println("var (")
  298. for _, d := range decl {
  299. print(d)
  300. }
  301. print(")\n\n")
  302. }
  303. type Op func(code rune) bool
  304. func dumpRange(name string, inCategory Op) {
  305. runes := []rune{}
  306. for i := range chars {
  307. r := rune(i)
  308. if inCategory(r) {
  309. runes = append(runes, r)
  310. }
  311. }
  312. printRangeTable(name, runes)
  313. }
  314. func printRangeTable(name string, runes []rune) {
  315. rt := rangetable.New(runes...)
  316. printf("var %s = &RangeTable{\n", name)
  317. println("\tR16: []Range16{")
  318. for _, r := range rt.R16 {
  319. printf("\t\t{%#04x, %#04x, %d},\n", r.Lo, r.Hi, r.Stride)
  320. range16Count++
  321. }
  322. println("\t},")
  323. if len(rt.R32) > 0 {
  324. println("\tR32: []Range32{")
  325. for _, r := range rt.R32 {
  326. printf("\t\t{%#x, %#x, %d},\n", r.Lo, r.Hi, r.Stride)
  327. range32Count++
  328. }
  329. println("\t},")
  330. }
  331. if rt.LatinOffset > 0 {
  332. printf("\tLatinOffset: %d,\n", rt.LatinOffset)
  333. }
  334. printf("}\n\n")
  335. }
  336. func fullCategoryTest(list []string) {
  337. for _, name := range list {
  338. if _, ok := category[name]; !ok {
  339. logger.Fatal("unknown category", name)
  340. }
  341. r, ok := unicode.Categories[name]
  342. if !ok && len(name) > 1 {
  343. logger.Fatalf("unknown table %q", name)
  344. }
  345. if len(name) == 1 {
  346. verifyRange(name, func(code rune) bool { return categoryOp(code, name[0]) }, r)
  347. } else {
  348. verifyRange(
  349. name,
  350. func(code rune) bool { return chars[code].category == name },
  351. r)
  352. }
  353. }
  354. }
  355. func verifyRange(name string, inCategory Op, table *unicode.RangeTable) {
  356. count := 0
  357. for j := range chars {
  358. i := rune(j)
  359. web := inCategory(i)
  360. pkg := unicode.Is(table, i)
  361. if web != pkg {
  362. fmt.Fprintf(os.Stderr, "%s: %U: web=%t pkg=%t\n", name, i, web, pkg)
  363. count++
  364. if count > 10 {
  365. break
  366. }
  367. }
  368. }
  369. }
  370. func fullScriptTest(list []string, installed map[string]*unicode.RangeTable, scripts map[string][]rune) {
  371. for _, name := range list {
  372. if _, ok := scripts[name]; !ok {
  373. logger.Fatal("unknown script", name)
  374. }
  375. _, ok := installed[name]
  376. if !ok {
  377. logger.Fatal("unknown table", name)
  378. }
  379. for _, r := range scripts[name] {
  380. if !unicode.Is(installed[name], rune(r)) {
  381. fmt.Fprintf(os.Stderr, "%U: not in script %s\n", r, name)
  382. }
  383. }
  384. }
  385. }
  386. var deprecatedAliases = map[string]string{
  387. "Sentence_Terminal": "STerm",
  388. }
  389. // PropList.txt has the same format as Scripts.txt so we can share its parser.
  390. func printScriptOrProperty(doProps bool) {
  391. flaglist := *scriptlist
  392. file := "Scripts.txt"
  393. table := scripts
  394. installed := unicode.Scripts
  395. if doProps {
  396. flaglist = *proplist
  397. file = "PropList.txt"
  398. table = props
  399. installed = unicode.Properties
  400. }
  401. if flaglist == "" {
  402. return
  403. }
  404. ucd.Parse(gen.OpenUCDFile(file), func(p *ucd.Parser) {
  405. name := p.String(1)
  406. table[name] = append(table[name], p.Rune(0))
  407. })
  408. // Find out which scripts to dump
  409. list := strings.Split(flaglist, ",")
  410. if flaglist == "all" {
  411. list = all(table)
  412. }
  413. if *test {
  414. fullScriptTest(list, installed, table)
  415. return
  416. }
  417. if flaglist == "all" {
  418. if doProps {
  419. println("// Properties is the set of Unicode property tables.")
  420. println("var Properties = map[string] *RangeTable{")
  421. } else {
  422. println("// Scripts is the set of Unicode script tables.")
  423. println("var Scripts = map[string] *RangeTable{")
  424. }
  425. for _, k := range all(table) {
  426. printf("\t%q: %s,\n", k, k)
  427. if alias, ok := deprecatedAliases[k]; ok {
  428. printf("\t%q: %s,\n", alias, k)
  429. }
  430. }
  431. print("}\n\n")
  432. }
  433. decl := make(sort.StringSlice, len(list)+len(deprecatedAliases))
  434. ndecl := 0
  435. for _, name := range list {
  436. if doProps {
  437. decl[ndecl] = fmt.Sprintf(
  438. "\t%s = _%s;\t// %s is the set of Unicode characters with property %s.\n",
  439. name, name, name, name)
  440. } else {
  441. decl[ndecl] = fmt.Sprintf(
  442. "\t%s = _%s;\t// %s is the set of Unicode characters in script %s.\n",
  443. name, name, name, name)
  444. }
  445. ndecl++
  446. if alias, ok := deprecatedAliases[name]; ok {
  447. decl[ndecl] = fmt.Sprintf(
  448. "\t%[1]s = _%[2]s;\t// %[1]s is an alias for %[2]s.\n",
  449. alias, name)
  450. ndecl++
  451. }
  452. printRangeTable("_"+name, table[name])
  453. }
  454. decl.Sort()
  455. println("// These variables have type *RangeTable.")
  456. println("var (")
  457. for _, d := range decl {
  458. print(d)
  459. }
  460. print(")\n\n")
  461. }
  462. const (
  463. CaseUpper = 1 << iota
  464. CaseLower
  465. CaseTitle
  466. CaseNone = 0 // must be zero
  467. CaseMissing = -1 // character not present; not a valid case state
  468. )
  469. type caseState struct {
  470. point rune
  471. _case int
  472. deltaToUpper rune
  473. deltaToLower rune
  474. deltaToTitle rune
  475. }
  476. // Is d a continuation of the state of c?
  477. func (c *caseState) adjacent(d *caseState) bool {
  478. if d.point < c.point {
  479. c, d = d, c
  480. }
  481. switch {
  482. case d.point != c.point+1: // code points not adjacent (shouldn't happen)
  483. return false
  484. case d._case != c._case: // different cases
  485. return c.upperLowerAdjacent(d)
  486. case c._case == CaseNone:
  487. return false
  488. case c._case == CaseMissing:
  489. return false
  490. case d.deltaToUpper != c.deltaToUpper:
  491. return false
  492. case d.deltaToLower != c.deltaToLower:
  493. return false
  494. case d.deltaToTitle != c.deltaToTitle:
  495. return false
  496. }
  497. return true
  498. }
  499. // Is d the same as c, but opposite in upper/lower case? this would make it
  500. // an element of an UpperLower sequence.
  501. func (c *caseState) upperLowerAdjacent(d *caseState) bool {
  502. // check they're a matched case pair. we know they have adjacent values
  503. switch {
  504. case c._case == CaseUpper && d._case != CaseLower:
  505. return false
  506. case c._case == CaseLower && d._case != CaseUpper:
  507. return false
  508. }
  509. // matched pair (at least in upper/lower). make the order Upper Lower
  510. if c._case == CaseLower {
  511. c, d = d, c
  512. }
  513. // for an Upper Lower sequence the deltas have to be in order
  514. // c: 0 1 0
  515. // d: -1 0 -1
  516. switch {
  517. case c.deltaToUpper != 0:
  518. return false
  519. case c.deltaToLower != 1:
  520. return false
  521. case c.deltaToTitle != 0:
  522. return false
  523. case d.deltaToUpper != -1:
  524. return false
  525. case d.deltaToLower != 0:
  526. return false
  527. case d.deltaToTitle != -1:
  528. return false
  529. }
  530. return true
  531. }
  532. // Does this character start an UpperLower sequence?
  533. func (c *caseState) isUpperLower() bool {
  534. // for an Upper Lower sequence the deltas have to be in order
  535. // c: 0 1 0
  536. switch {
  537. case c.deltaToUpper != 0:
  538. return false
  539. case c.deltaToLower != 1:
  540. return false
  541. case c.deltaToTitle != 0:
  542. return false
  543. }
  544. return true
  545. }
  546. // Does this character start a LowerUpper sequence?
  547. func (c *caseState) isLowerUpper() bool {
  548. // for an Upper Lower sequence the deltas have to be in order
  549. // c: -1 0 -1
  550. switch {
  551. case c.deltaToUpper != -1:
  552. return false
  553. case c.deltaToLower != 0:
  554. return false
  555. case c.deltaToTitle != -1:
  556. return false
  557. }
  558. return true
  559. }
  560. func getCaseState(i rune) (c *caseState) {
  561. c = &caseState{point: i, _case: CaseNone}
  562. ch := &chars[i]
  563. switch ch.codePoint {
  564. case 0:
  565. c._case = CaseMissing // Will get NUL wrong but that doesn't matter
  566. return
  567. case ch.upperCase:
  568. c._case = CaseUpper
  569. case ch.lowerCase:
  570. c._case = CaseLower
  571. case ch.titleCase:
  572. c._case = CaseTitle
  573. }
  574. // Some things such as roman numeral U+2161 don't describe themselves
  575. // as upper case, but have a lower case. Second-guess them.
  576. if c._case == CaseNone && ch.lowerCase != 0 {
  577. c._case = CaseUpper
  578. }
  579. // Same in the other direction.
  580. if c._case == CaseNone && ch.upperCase != 0 {
  581. c._case = CaseLower
  582. }
  583. if ch.upperCase != 0 {
  584. c.deltaToUpper = ch.upperCase - i
  585. }
  586. if ch.lowerCase != 0 {
  587. c.deltaToLower = ch.lowerCase - i
  588. }
  589. if ch.titleCase != 0 {
  590. c.deltaToTitle = ch.titleCase - i
  591. }
  592. return
  593. }
  594. func printCases() {
  595. if *test {
  596. fullCaseTest()
  597. return
  598. }
  599. printf(
  600. "// CaseRanges is the table describing case mappings for all letters with\n" +
  601. "// non-self mappings.\n" +
  602. "var CaseRanges = _CaseRanges\n" +
  603. "var _CaseRanges = []CaseRange {\n")
  604. var startState *caseState // the start of a run; nil for not active
  605. var prevState = &caseState{} // the state of the previous character
  606. for i := range chars {
  607. state := getCaseState(rune(i))
  608. if state.adjacent(prevState) {
  609. prevState = state
  610. continue
  611. }
  612. // end of run (possibly)
  613. printCaseRange(startState, prevState)
  614. startState = nil
  615. if state._case != CaseMissing && state._case != CaseNone {
  616. startState = state
  617. }
  618. prevState = state
  619. }
  620. print("}\n")
  621. }
  622. func printCaseRange(lo, hi *caseState) {
  623. if lo == nil {
  624. return
  625. }
  626. if lo.deltaToUpper == 0 && lo.deltaToLower == 0 && lo.deltaToTitle == 0 {
  627. // character represents itself in all cases - no need to mention it
  628. return
  629. }
  630. switch {
  631. case hi.point > lo.point && lo.isUpperLower():
  632. printf("\t{0x%04X, 0x%04X, d{UpperLower, UpperLower, UpperLower}},\n",
  633. lo.point, hi.point)
  634. case hi.point > lo.point && lo.isLowerUpper():
  635. logger.Fatalf("LowerUpper sequence: should not happen: %U. If it's real, need to fix To()", lo.point)
  636. printf("\t{0x%04X, 0x%04X, d{LowerUpper, LowerUpper, LowerUpper}},\n",
  637. lo.point, hi.point)
  638. default:
  639. printf("\t{0x%04X, 0x%04X, d{%d, %d, %d}},\n",
  640. lo.point, hi.point,
  641. lo.deltaToUpper, lo.deltaToLower, lo.deltaToTitle)
  642. }
  643. }
  644. // If the cased value in the Char is 0, it means use the rune itself.
  645. func caseIt(r, cased rune) rune {
  646. if cased == 0 {
  647. return r
  648. }
  649. return cased
  650. }
  651. func fullCaseTest() {
  652. for j, c := range chars {
  653. i := rune(j)
  654. lower := unicode.ToLower(i)
  655. want := caseIt(i, c.lowerCase)
  656. if lower != want {
  657. fmt.Fprintf(os.Stderr, "lower %U should be %U is %U\n", i, want, lower)
  658. }
  659. upper := unicode.ToUpper(i)
  660. want = caseIt(i, c.upperCase)
  661. if upper != want {
  662. fmt.Fprintf(os.Stderr, "upper %U should be %U is %U\n", i, want, upper)
  663. }
  664. title := unicode.ToTitle(i)
  665. want = caseIt(i, c.titleCase)
  666. if title != want {
  667. fmt.Fprintf(os.Stderr, "title %U should be %U is %U\n", i, want, title)
  668. }
  669. }
  670. }
  671. func printLatinProperties() {
  672. if *test {
  673. return
  674. }
  675. println("var properties = [MaxLatin1+1]uint8{")
  676. for code := 0; code <= unicode.MaxLatin1; code++ {
  677. var property string
  678. switch chars[code].category {
  679. case "Cc", "": // NUL has no category.
  680. property = "pC"
  681. case "Cf": // soft hyphen, unique category, not printable.
  682. property = "0"
  683. case "Ll":
  684. property = "pLl | pp"
  685. case "Lo":
  686. property = "pLo | pp"
  687. case "Lu":
  688. property = "pLu | pp"
  689. case "Nd", "No":
  690. property = "pN | pp"
  691. case "Pc", "Pd", "Pe", "Pf", "Pi", "Po", "Ps":
  692. property = "pP | pp"
  693. case "Sc", "Sk", "Sm", "So":
  694. property = "pS | pp"
  695. case "Zs":
  696. property = "pZ"
  697. default:
  698. logger.Fatalf("%U has unknown category %q", code, chars[code].category)
  699. }
  700. // Special case
  701. if code == ' ' {
  702. property = "pZ | pp"
  703. }
  704. printf("\t0x%02X: %s, // %q\n", code, property, code)
  705. }
  706. printf("}\n\n")
  707. }
  708. func printCasefold() {
  709. // Build list of case-folding groups attached to each canonical folded char (typically lower case).
  710. var caseOrbit = make([][]rune, MaxChar+1)
  711. for j := range chars {
  712. i := rune(j)
  713. c := &chars[i]
  714. if c.foldCase == 0 {
  715. continue
  716. }
  717. orb := caseOrbit[c.foldCase]
  718. if orb == nil {
  719. orb = append(orb, c.foldCase)
  720. }
  721. caseOrbit[c.foldCase] = append(orb, i)
  722. }
  723. // Insert explicit 1-element groups when assuming [lower, upper] would be wrong.
  724. for j := range chars {
  725. i := rune(j)
  726. c := &chars[i]
  727. f := c.foldCase
  728. if f == 0 {
  729. f = i
  730. }
  731. orb := caseOrbit[f]
  732. if orb == nil && (c.upperCase != 0 && c.upperCase != i || c.lowerCase != 0 && c.lowerCase != i) {
  733. // Default assumption of [upper, lower] is wrong.
  734. caseOrbit[i] = []rune{i}
  735. }
  736. }
  737. // Delete the groups for which assuming [lower, upper] or [upper, lower] is right.
  738. for i, orb := range caseOrbit {
  739. if len(orb) == 2 && chars[orb[0]].upperCase == orb[1] && chars[orb[1]].lowerCase == orb[0] {
  740. caseOrbit[i] = nil
  741. }
  742. if len(orb) == 2 && chars[orb[1]].upperCase == orb[0] && chars[orb[0]].lowerCase == orb[1] {
  743. caseOrbit[i] = nil
  744. }
  745. }
  746. // Record orbit information in chars.
  747. for _, orb := range caseOrbit {
  748. if orb == nil {
  749. continue
  750. }
  751. sort.Slice(orb, func(i, j int) bool {
  752. return orb[i] < orb[j]
  753. })
  754. c := orb[len(orb)-1]
  755. for _, d := range orb {
  756. chars[c].caseOrbit = d
  757. c = d
  758. }
  759. }
  760. printAsciiFold()
  761. printCaseOrbit()
  762. // Tables of category and script folding exceptions: code points
  763. // that must be added when interpreting a particular category/script
  764. // in a case-folding context.
  765. cat := make(map[string]map[rune]bool)
  766. for name := range category {
  767. if x := foldExceptions(inCategory(name)); len(x) > 0 {
  768. cat[name] = x
  769. }
  770. }
  771. scr := make(map[string]map[rune]bool)
  772. for name := range scripts {
  773. if x := foldExceptions(scripts[name]); len(x) > 0 {
  774. scr[name] = x
  775. }
  776. }
  777. printCatFold("FoldCategory", cat)
  778. printCatFold("FoldScript", scr)
  779. }
  780. // inCategory returns a list of all the runes in the category.
  781. func inCategory(name string) []rune {
  782. var x []rune
  783. for j := range chars {
  784. i := rune(j)
  785. c := &chars[i]
  786. if c.category == name || len(name) == 1 && len(c.category) > 1 && c.category[0] == name[0] {
  787. x = append(x, i)
  788. }
  789. }
  790. return x
  791. }
  792. // foldExceptions returns a list of all the runes fold-equivalent
  793. // to runes in class but not in class themselves.
  794. func foldExceptions(class []rune) map[rune]bool {
  795. // Create map containing class and all fold-equivalent chars.
  796. m := make(map[rune]bool)
  797. for _, r := range class {
  798. c := &chars[r]
  799. if c.caseOrbit == 0 {
  800. // Just upper and lower.
  801. if u := c.upperCase; u != 0 {
  802. m[u] = true
  803. }
  804. if l := c.lowerCase; l != 0 {
  805. m[l] = true
  806. }
  807. m[r] = true
  808. continue
  809. }
  810. // Otherwise walk orbit.
  811. r0 := r
  812. for {
  813. m[r] = true
  814. r = chars[r].caseOrbit
  815. if r == r0 {
  816. break
  817. }
  818. }
  819. }
  820. // Remove class itself.
  821. for _, r := range class {
  822. delete(m, r)
  823. }
  824. // What's left is the exceptions.
  825. return m
  826. }
  827. var comment = map[string]string{
  828. "FoldCategory": "// FoldCategory maps a category name to a table of\n" +
  829. "// code points outside the category that are equivalent under\n" +
  830. "// simple case folding to code points inside the category.\n" +
  831. "// If there is no entry for a category name, there are no such points.\n",
  832. "FoldScript": "// FoldScript maps a script name to a table of\n" +
  833. "// code points outside the script that are equivalent under\n" +
  834. "// simple case folding to code points inside the script.\n" +
  835. "// If there is no entry for a script name, there are no such points.\n",
  836. }
  837. func printAsciiFold() {
  838. printf("var asciiFold = [MaxASCII + 1]uint16{\n")
  839. for i := rune(0); i <= unicode.MaxASCII; i++ {
  840. c := chars[i]
  841. f := c.caseOrbit
  842. if f == 0 {
  843. if c.lowerCase != i && c.lowerCase != 0 {
  844. f = c.lowerCase
  845. } else if c.upperCase != i && c.upperCase != 0 {
  846. f = c.upperCase
  847. } else {
  848. f = i
  849. }
  850. }
  851. printf("\t0x%04X,\n", f)
  852. }
  853. printf("}\n\n")
  854. }
  855. func printCaseOrbit() {
  856. if *test {
  857. for j := range chars {
  858. i := rune(j)
  859. c := &chars[i]
  860. f := c.caseOrbit
  861. if f == 0 {
  862. if c.lowerCase != i && c.lowerCase != 0 {
  863. f = c.lowerCase
  864. } else if c.upperCase != i && c.upperCase != 0 {
  865. f = c.upperCase
  866. } else {
  867. f = i
  868. }
  869. }
  870. if g := unicode.SimpleFold(i); g != f {
  871. fmt.Fprintf(os.Stderr, "unicode.SimpleFold(%#U) = %#U, want %#U\n", i, g, f)
  872. }
  873. }
  874. return
  875. }
  876. printf("var caseOrbit = []foldPair{\n")
  877. for i := range chars {
  878. c := &chars[i]
  879. if c.caseOrbit != 0 {
  880. printf("\t{0x%04X, 0x%04X},\n", i, c.caseOrbit)
  881. foldPairCount++
  882. }
  883. }
  884. printf("}\n\n")
  885. }
  886. func printCatFold(name string, m map[string]map[rune]bool) {
  887. if *test {
  888. var pkgMap map[string]*unicode.RangeTable
  889. if name == "FoldCategory" {
  890. pkgMap = unicode.FoldCategory
  891. } else {
  892. pkgMap = unicode.FoldScript
  893. }
  894. if len(pkgMap) != len(m) {
  895. fmt.Fprintf(os.Stderr, "unicode.%s has %d elements, want %d\n", name, len(pkgMap), len(m))
  896. return
  897. }
  898. for k, v := range m {
  899. t, ok := pkgMap[k]
  900. if !ok {
  901. fmt.Fprintf(os.Stderr, "unicode.%s[%q] missing\n", name, k)
  902. continue
  903. }
  904. n := 0
  905. for _, r := range t.R16 {
  906. for c := rune(r.Lo); c <= rune(r.Hi); c += rune(r.Stride) {
  907. if !v[c] {
  908. fmt.Fprintf(os.Stderr, "unicode.%s[%q] contains %#U, should not\n", name, k, c)
  909. }
  910. n++
  911. }
  912. }
  913. for _, r := range t.R32 {
  914. for c := rune(r.Lo); c <= rune(r.Hi); c += rune(r.Stride) {
  915. if !v[c] {
  916. fmt.Fprintf(os.Stderr, "unicode.%s[%q] contains %#U, should not\n", name, k, c)
  917. }
  918. n++
  919. }
  920. }
  921. if n != len(v) {
  922. fmt.Fprintf(os.Stderr, "unicode.%s[%q] has %d code points, want %d\n", name, k, n, len(v))
  923. }
  924. }
  925. return
  926. }
  927. print(comment[name])
  928. printf("var %s = map[string]*RangeTable{\n", name)
  929. for _, name := range allCatFold(m) {
  930. printf("\t%q: fold%s,\n", name, name)
  931. }
  932. printf("}\n\n")
  933. for _, name := range allCatFold(m) {
  934. class := m[name]
  935. dumpRange("fold"+name, func(code rune) bool { return class[code] })
  936. }
  937. }
  938. var range16Count = 0 // Number of entries in the 16-bit range tables.
  939. var range32Count = 0 // Number of entries in the 32-bit range tables.
  940. var foldPairCount = 0 // Number of fold pairs in the exception tables.
  941. func printSizes() {
  942. if *test {
  943. return
  944. }
  945. println()
  946. printf("// Range entries: %d 16-bit, %d 32-bit, %d total.\n", range16Count, range32Count, range16Count+range32Count)
  947. range16Bytes := range16Count * 3 * 2
  948. range32Bytes := range32Count * 3 * 4
  949. printf("// Range bytes: %d 16-bit, %d 32-bit, %d total.\n", range16Bytes, range32Bytes, range16Bytes+range32Bytes)
  950. println()
  951. printf("// Fold orbit bytes: %d pairs, %d bytes\n", foldPairCount, foldPairCount*2*2)
  952. }