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

832 lines
21 KiB

  1. // Copyright 2014 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. // This program generates the trie for casing operations. The Unicode casing
  6. // algorithm requires the lookup of various properties and mappings for each
  7. // rune. The table generated by this generator combines several of the most
  8. // frequently used of these into a single trie so that they can be accessed
  9. // with a single lookup.
  10. package main
  11. import (
  12. "bytes"
  13. "fmt"
  14. "io"
  15. "io/ioutil"
  16. "log"
  17. "reflect"
  18. "strconv"
  19. "strings"
  20. "unicode"
  21. "golang.org/x/text/internal/gen"
  22. "golang.org/x/text/internal/triegen"
  23. "golang.org/x/text/internal/ucd"
  24. "golang.org/x/text/unicode/norm"
  25. )
  26. func main() {
  27. gen.Init()
  28. genTables()
  29. genTablesTest()
  30. gen.Repackage("gen_trieval.go", "trieval.go", "cases")
  31. }
  32. // runeInfo contains all information for a rune that we care about for casing
  33. // operations.
  34. type runeInfo struct {
  35. Rune rune
  36. entry info // trie value for this rune.
  37. CaseMode info
  38. // Simple case mappings.
  39. Simple [1 + maxCaseMode][]rune
  40. // Special casing
  41. HasSpecial bool
  42. Conditional bool
  43. Special [1 + maxCaseMode][]rune
  44. // Folding
  45. FoldSimple rune
  46. FoldSpecial rune
  47. FoldFull []rune
  48. // TODO: FC_NFKC, or equivalent data.
  49. // Properties
  50. SoftDotted bool
  51. CaseIgnorable bool
  52. Cased bool
  53. DecomposeGreek bool
  54. BreakType string
  55. BreakCat breakCategory
  56. // We care mostly about 0, Above, and IotaSubscript.
  57. CCC byte
  58. }
  59. type breakCategory int
  60. const (
  61. breakBreak breakCategory = iota
  62. breakLetter
  63. breakIgnored
  64. )
  65. // mapping returns the case mapping for the given case type.
  66. func (r *runeInfo) mapping(c info) string {
  67. if r.HasSpecial {
  68. return string(r.Special[c])
  69. }
  70. if len(r.Simple[c]) != 0 {
  71. return string(r.Simple[c])
  72. }
  73. return string(r.Rune)
  74. }
  75. func parse(file string, f func(p *ucd.Parser)) {
  76. ucd.Parse(gen.OpenUCDFile(file), f)
  77. }
  78. func parseUCD() []runeInfo {
  79. chars := make([]runeInfo, unicode.MaxRune)
  80. get := func(r rune) *runeInfo {
  81. c := &chars[r]
  82. c.Rune = r
  83. return c
  84. }
  85. parse("UnicodeData.txt", func(p *ucd.Parser) {
  86. ri := get(p.Rune(0))
  87. ri.CCC = byte(p.Int(ucd.CanonicalCombiningClass))
  88. ri.Simple[cLower] = p.Runes(ucd.SimpleLowercaseMapping)
  89. ri.Simple[cUpper] = p.Runes(ucd.SimpleUppercaseMapping)
  90. ri.Simple[cTitle] = p.Runes(ucd.SimpleTitlecaseMapping)
  91. if p.String(ucd.GeneralCategory) == "Lt" {
  92. ri.CaseMode = cTitle
  93. }
  94. })
  95. // <code>; <property>
  96. parse("PropList.txt", func(p *ucd.Parser) {
  97. if p.String(1) == "Soft_Dotted" {
  98. chars[p.Rune(0)].SoftDotted = true
  99. }
  100. })
  101. // <code>; <word break type>
  102. parse("DerivedCoreProperties.txt", func(p *ucd.Parser) {
  103. ri := get(p.Rune(0))
  104. switch p.String(1) {
  105. case "Case_Ignorable":
  106. ri.CaseIgnorable = true
  107. case "Cased":
  108. ri.Cased = true
  109. case "Lowercase":
  110. ri.CaseMode = cLower
  111. case "Uppercase":
  112. ri.CaseMode = cUpper
  113. }
  114. })
  115. // <code>; <lower> ; <title> ; <upper> ; (<condition_list> ;)?
  116. parse("SpecialCasing.txt", func(p *ucd.Parser) {
  117. // We drop all conditional special casing and deal with them manually in
  118. // the language-specific case mappers. Rune 0x03A3 is the only one with
  119. // a conditional formatting that is not language-specific. However,
  120. // dealing with this letter is tricky, especially in a streaming
  121. // context, so we deal with it in the Caser for Greek specifically.
  122. ri := get(p.Rune(0))
  123. if p.String(4) == "" {
  124. ri.HasSpecial = true
  125. ri.Special[cLower] = p.Runes(1)
  126. ri.Special[cTitle] = p.Runes(2)
  127. ri.Special[cUpper] = p.Runes(3)
  128. } else {
  129. ri.Conditional = true
  130. }
  131. })
  132. // TODO: Use text breaking according to UAX #29.
  133. // <code>; <word break type>
  134. parse("auxiliary/WordBreakProperty.txt", func(p *ucd.Parser) {
  135. ri := get(p.Rune(0))
  136. ri.BreakType = p.String(1)
  137. // We collapse the word breaking properties onto the categories we need.
  138. switch p.String(1) { // TODO: officially we need to canonicalize.
  139. case "Format", "MidLetter", "MidNumLet", "Single_Quote":
  140. ri.BreakCat = breakIgnored
  141. case "ALetter", "Hebrew_Letter", "Numeric", "Extend", "ExtendNumLet":
  142. ri.BreakCat = breakLetter
  143. }
  144. })
  145. // <code>; <type>; <mapping>
  146. parse("CaseFolding.txt", func(p *ucd.Parser) {
  147. ri := get(p.Rune(0))
  148. switch p.String(1) {
  149. case "C":
  150. ri.FoldSimple = p.Rune(2)
  151. ri.FoldFull = p.Runes(2)
  152. case "S":
  153. ri.FoldSimple = p.Rune(2)
  154. case "T":
  155. ri.FoldSpecial = p.Rune(2)
  156. case "F":
  157. ri.FoldFull = p.Runes(2)
  158. default:
  159. log.Fatalf("%U: unknown type: %s", p.Rune(0), p.String(1))
  160. }
  161. })
  162. return chars
  163. }
  164. func genTables() {
  165. chars := parseUCD()
  166. verifyProperties(chars)
  167. t := triegen.NewTrie("case")
  168. for i := range chars {
  169. c := &chars[i]
  170. makeEntry(c)
  171. t.Insert(rune(i), uint64(c.entry))
  172. }
  173. w := gen.NewCodeWriter()
  174. defer w.WriteGoFile("tables.go", "cases")
  175. gen.WriteUnicodeVersion(w)
  176. // TODO: write CLDR version after adding a mechanism to detect that the
  177. // tables on which the manually created locale-sensitive casing code is
  178. // based hasn't changed.
  179. w.WriteVar("xorData", string(xorData))
  180. w.WriteVar("exceptions", string(exceptionData))
  181. sz, err := t.Gen(w, triegen.Compact(&sparseCompacter{}))
  182. if err != nil {
  183. log.Fatal(err)
  184. }
  185. w.Size += sz
  186. }
  187. func makeEntry(ri *runeInfo) {
  188. if ri.CaseIgnorable {
  189. if ri.Cased {
  190. ri.entry = cIgnorableCased
  191. } else {
  192. ri.entry = cIgnorableUncased
  193. }
  194. } else {
  195. ri.entry = ri.CaseMode
  196. }
  197. // TODO: handle soft-dotted.
  198. ccc := cccOther
  199. switch ri.CCC {
  200. case 0: // Not_Reordered
  201. ccc = cccZero
  202. case above: // Above
  203. ccc = cccAbove
  204. }
  205. if ri.BreakCat == breakBreak {
  206. ccc = cccBreak
  207. }
  208. ri.entry |= ccc
  209. if ri.CaseMode == cUncased {
  210. return
  211. }
  212. // Need to do something special.
  213. if ri.CaseMode == cTitle || ri.HasSpecial || ri.mapping(cTitle) != ri.mapping(cUpper) {
  214. makeException(ri)
  215. return
  216. }
  217. if f := string(ri.FoldFull); len(f) > 0 && f != ri.mapping(cUpper) && f != ri.mapping(cLower) {
  218. makeException(ri)
  219. return
  220. }
  221. // Rune is either lowercase or uppercase.
  222. orig := string(ri.Rune)
  223. mapped := ""
  224. if ri.CaseMode == cUpper {
  225. mapped = ri.mapping(cLower)
  226. } else {
  227. mapped = ri.mapping(cUpper)
  228. }
  229. if len(orig) != len(mapped) {
  230. makeException(ri)
  231. return
  232. }
  233. if string(ri.FoldFull) == ri.mapping(cUpper) {
  234. ri.entry |= inverseFoldBit
  235. }
  236. n := len(orig)
  237. // Create per-byte XOR mask.
  238. var b []byte
  239. for i := 0; i < n; i++ {
  240. b = append(b, orig[i]^mapped[i])
  241. }
  242. // Remove leading 0 bytes, but keep at least one byte.
  243. for ; len(b) > 1 && b[0] == 0; b = b[1:] {
  244. }
  245. if len(b) == 1 && b[0]&0xc0 == 0 {
  246. ri.entry |= info(b[0]) << xorShift
  247. return
  248. }
  249. key := string(b)
  250. x, ok := xorCache[key]
  251. if !ok {
  252. xorData = append(xorData, 0) // for detecting start of sequence
  253. xorData = append(xorData, b...)
  254. x = len(xorData) - 1
  255. xorCache[key] = x
  256. }
  257. ri.entry |= info(x<<xorShift) | xorIndexBit
  258. }
  259. var xorCache = map[string]int{}
  260. // xorData contains byte-wise XOR data for the least significant bytes of a
  261. // UTF-8 encoded rune. An index points to the last byte. The sequence starts
  262. // with a zero terminator.
  263. var xorData = []byte{}
  264. // See the comments in gen_trieval.go re "the exceptions slice".
  265. var exceptionData = []byte{0}
  266. // makeException encodes case mappings that cannot be expressed in a simple
  267. // XOR diff.
  268. func makeException(ri *runeInfo) {
  269. ccc := ri.entry & cccMask
  270. // Set exception bit and retain case type.
  271. ri.entry &= 0x0007
  272. ri.entry |= exceptionBit
  273. if len(exceptionData) >= 1<<numExceptionBits {
  274. log.Fatalf("%U:exceptionData too large %x > %d bits", ri.Rune, len(exceptionData), numExceptionBits)
  275. }
  276. // Set the offset in the exceptionData array.
  277. ri.entry |= info(len(exceptionData) << exceptionShift)
  278. orig := string(ri.Rune)
  279. tc := ri.mapping(cTitle)
  280. uc := ri.mapping(cUpper)
  281. lc := ri.mapping(cLower)
  282. ff := string(ri.FoldFull)
  283. // addString sets the length of a string and adds it to the expansions array.
  284. addString := func(s string, b *byte) {
  285. if len(s) == 0 {
  286. // Zero-length mappings exist, but only for conditional casing,
  287. // which we are representing outside of this table.
  288. log.Fatalf("%U: has zero-length mapping.", ri.Rune)
  289. }
  290. *b <<= 3
  291. if s != orig {
  292. n := len(s)
  293. if n > 7 {
  294. log.Fatalf("%U: mapping larger than 7 (%d)", ri.Rune, n)
  295. }
  296. *b |= byte(n)
  297. exceptionData = append(exceptionData, s...)
  298. }
  299. }
  300. // byte 0:
  301. exceptionData = append(exceptionData, byte(ccc)|byte(len(ff)))
  302. // byte 1:
  303. p := len(exceptionData)
  304. exceptionData = append(exceptionData, 0)
  305. if len(ff) > 7 { // May be zero-length.
  306. log.Fatalf("%U: fold string larger than 7 (%d)", ri.Rune, len(ff))
  307. }
  308. exceptionData = append(exceptionData, ff...)
  309. ct := ri.CaseMode
  310. if ct != cLower {
  311. addString(lc, &exceptionData[p])
  312. }
  313. if ct != cUpper {
  314. addString(uc, &exceptionData[p])
  315. }
  316. if ct != cTitle {
  317. // If title is the same as upper, we set it to the original string so
  318. // that it will be marked as not present. This implies title case is
  319. // the same as upper case.
  320. if tc == uc {
  321. tc = orig
  322. }
  323. addString(tc, &exceptionData[p])
  324. }
  325. }
  326. // sparseCompacter is a trie value block Compacter. There are many cases where
  327. // successive runes alternate between lower- and upper-case. This Compacter
  328. // exploits this by adding a special case type where the case value is obtained
  329. // from or-ing it with the least-significant bit of the rune, creating large
  330. // ranges of equal case values that compress well.
  331. type sparseCompacter struct {
  332. sparseBlocks [][]uint16
  333. sparseOffsets []uint16
  334. sparseCount int
  335. }
  336. // makeSparse returns the number of elements that compact block would contain
  337. // as well as the modified values.
  338. func makeSparse(vals []uint64) ([]uint16, int) {
  339. // Copy the values.
  340. values := make([]uint16, len(vals))
  341. for i, v := range vals {
  342. values[i] = uint16(v)
  343. }
  344. alt := func(i int, v uint16) uint16 {
  345. if cm := info(v & fullCasedMask); cm == cUpper || cm == cLower {
  346. // Convert cLower or cUpper to cXORCase value, which has the form 11x.
  347. xor := v
  348. xor &^= 1
  349. xor |= uint16(i&1) ^ (v & 1)
  350. xor |= 0x4
  351. return xor
  352. }
  353. return v
  354. }
  355. var count int
  356. var previous uint16
  357. for i, v := range values {
  358. if v != 0 {
  359. // Try if the unmodified value is equal to the previous.
  360. if v == previous {
  361. continue
  362. }
  363. // Try if the xor-ed value is equal to the previous value.
  364. a := alt(i, v)
  365. if a == previous {
  366. values[i] = a
  367. continue
  368. }
  369. // This is a new value.
  370. count++
  371. // Use the xor-ed value if it will be identical to the next value.
  372. if p := i + 1; p < len(values) && alt(p, values[p]) == a {
  373. values[i] = a
  374. v = a
  375. }
  376. }
  377. previous = v
  378. }
  379. return values, count
  380. }
  381. func (s *sparseCompacter) Size(v []uint64) (int, bool) {
  382. _, n := makeSparse(v)
  383. // We limit using this method to having 16 entries.
  384. if n > 16 {
  385. return 0, false
  386. }
  387. return 2 + int(reflect.TypeOf(valueRange{}).Size())*n, true
  388. }
  389. func (s *sparseCompacter) Store(v []uint64) uint32 {
  390. h := uint32(len(s.sparseOffsets))
  391. values, sz := makeSparse(v)
  392. s.sparseBlocks = append(s.sparseBlocks, values)
  393. s.sparseOffsets = append(s.sparseOffsets, uint16(s.sparseCount))
  394. s.sparseCount += sz
  395. return h
  396. }
  397. func (s *sparseCompacter) Handler() string {
  398. // The sparse global variable and its lookup method is defined in gen_trieval.go.
  399. return "sparse.lookup"
  400. }
  401. func (s *sparseCompacter) Print(w io.Writer) (retErr error) {
  402. p := func(format string, args ...interface{}) {
  403. _, err := fmt.Fprintf(w, format, args...)
  404. if retErr == nil && err != nil {
  405. retErr = err
  406. }
  407. }
  408. ls := len(s.sparseBlocks)
  409. if ls == len(s.sparseOffsets) {
  410. s.sparseOffsets = append(s.sparseOffsets, uint16(s.sparseCount))
  411. }
  412. p("// sparseOffsets: %d entries, %d bytes\n", ls+1, (ls+1)*2)
  413. p("var sparseOffsets = %#v\n\n", s.sparseOffsets)
  414. ns := s.sparseCount
  415. p("// sparseValues: %d entries, %d bytes\n", ns, ns*4)
  416. p("var sparseValues = [%d]valueRange {", ns)
  417. for i, values := range s.sparseBlocks {
  418. p("\n// Block %#x, offset %#x", i, s.sparseOffsets[i])
  419. var v uint16
  420. for i, nv := range values {
  421. if nv != v {
  422. if v != 0 {
  423. p(",hi:%#02x},", 0x80+i-1)
  424. }
  425. if nv != 0 {
  426. p("\n{value:%#04x,lo:%#02x", nv, 0x80+i)
  427. }
  428. }
  429. v = nv
  430. }
  431. if v != 0 {
  432. p(",hi:%#02x},", 0x80+len(values)-1)
  433. }
  434. }
  435. p("\n}\n\n")
  436. return
  437. }
  438. // verifyProperties that properties of the runes that are relied upon in the
  439. // implementation. Each property is marked with an identifier that is referred
  440. // to in the places where it is used.
  441. func verifyProperties(chars []runeInfo) {
  442. for i, c := range chars {
  443. r := rune(i)
  444. // Rune properties.
  445. // A.1: modifier never changes on lowercase. [ltLower]
  446. if c.CCC > 0 && unicode.ToLower(r) != r {
  447. log.Fatalf("%U: non-starter changes when lowercased", r)
  448. }
  449. // A.2: properties of decompositions starting with I or J. [ltLower]
  450. d := norm.NFD.PropertiesString(string(r)).Decomposition()
  451. if len(d) > 0 {
  452. if d[0] == 'I' || d[0] == 'J' {
  453. // A.2.1: we expect at least an ASCII character and a modifier.
  454. if len(d) < 3 {
  455. log.Fatalf("%U: length of decomposition was %d; want >= 3", r, len(d))
  456. }
  457. // All subsequent runes are modifiers and all have the same CCC.
  458. runes := []rune(string(d[1:]))
  459. ccc := chars[runes[0]].CCC
  460. for _, mr := range runes[1:] {
  461. mc := chars[mr]
  462. // A.2.2: all modifiers have a CCC of Above or less.
  463. if ccc == 0 || ccc > above {
  464. log.Fatalf("%U: CCC of successive rune (%U) was %d; want (0,230]", r, mr, ccc)
  465. }
  466. // A.2.3: a sequence of modifiers all have the same CCC.
  467. if mc.CCC != ccc {
  468. log.Fatalf("%U: CCC of follow-up modifier (%U) was %d; want %d", r, mr, mc.CCC, ccc)
  469. }
  470. // A.2.4: for each trailing r, r in [0x300, 0x311] <=> CCC == Above.
  471. if (ccc == above) != (0x300 <= mr && mr <= 0x311) {
  472. log.Fatalf("%U: modifier %U in [U+0300, U+0311] != ccc(%U) == 230", r, mr, mr)
  473. }
  474. if i += len(string(mr)); i >= len(d) {
  475. break
  476. }
  477. }
  478. }
  479. }
  480. // A.3: no U+0307 in decomposition of Soft-Dotted rune. [ltUpper]
  481. if unicode.Is(unicode.Soft_Dotted, r) && strings.Contains(string(d), "\u0307") {
  482. log.Fatalf("%U: decomposition of soft-dotted rune may not contain U+0307", r)
  483. }
  484. // A.4: only rune U+0345 may be of CCC Iota_Subscript. [elUpper]
  485. if c.CCC == iotaSubscript && r != 0x0345 {
  486. log.Fatalf("%U: only rune U+0345 may have CCC Iota_Subscript", r)
  487. }
  488. // A.5: soft-dotted runes do not have exceptions.
  489. if c.SoftDotted && c.entry&exceptionBit != 0 {
  490. log.Fatalf("%U: soft-dotted has exception", r)
  491. }
  492. // A.6: Greek decomposition. [elUpper]
  493. if unicode.Is(unicode.Greek, r) {
  494. if b := norm.NFD.PropertiesString(string(r)).Decomposition(); b != nil {
  495. runes := []rune(string(b))
  496. // A.6.1: If a Greek rune decomposes and the first rune of the
  497. // decomposition is greater than U+00FF, the rune is always
  498. // great and not a modifier.
  499. if f := runes[0]; unicode.IsMark(f) || f > 0xFF && !unicode.Is(unicode.Greek, f) {
  500. log.Fatalf("%U: expeced first rune of Greek decomposition to be letter, found %U", r, f)
  501. }
  502. // A.6.2: Any follow-up rune in a Greek decomposition is a
  503. // modifier of which the first should be gobbled in
  504. // decomposition.
  505. for _, m := range runes[1:] {
  506. switch m {
  507. case 0x0313, 0x0314, 0x0301, 0x0300, 0x0306, 0x0342, 0x0308, 0x0304, 0x345:
  508. default:
  509. log.Fatalf("%U: modifier %U is outside of expeced Greek modifier set", r, m)
  510. }
  511. }
  512. }
  513. }
  514. // Breaking properties.
  515. // B.1: all runes with CCC > 0 are of break type Extend.
  516. if c.CCC > 0 && c.BreakType != "Extend" {
  517. log.Fatalf("%U: CCC == %d, but got break type %s; want Extend", r, c.CCC, c.BreakType)
  518. }
  519. // B.2: all cased runes with c.CCC == 0 are of break type ALetter.
  520. if c.CCC == 0 && c.Cased && c.BreakType != "ALetter" {
  521. log.Fatalf("%U: cased, but got break type %s; want ALetter", r, c.BreakType)
  522. }
  523. // B.3: letter category.
  524. if c.CCC == 0 && c.BreakCat != breakBreak && !c.CaseIgnorable {
  525. if c.BreakCat != breakLetter {
  526. log.Fatalf("%U: check for letter break type gave %d; want %d", r, c.BreakCat, breakLetter)
  527. }
  528. }
  529. }
  530. }
  531. func genTablesTest() {
  532. w := &bytes.Buffer{}
  533. fmt.Fprintln(w, "var (")
  534. printProperties(w, "DerivedCoreProperties.txt", "Case_Ignorable", verifyIgnore)
  535. // We discard the output as we know we have perfect functions. We run them
  536. // just to verify the properties are correct.
  537. n := printProperties(ioutil.Discard, "DerivedCoreProperties.txt", "Cased", verifyCased)
  538. n += printProperties(ioutil.Discard, "DerivedCoreProperties.txt", "Lowercase", verifyLower)
  539. n += printProperties(ioutil.Discard, "DerivedCoreProperties.txt", "Uppercase", verifyUpper)
  540. if n > 0 {
  541. log.Fatalf("One of the discarded properties does not have a perfect filter.")
  542. }
  543. // <code>; <lower> ; <title> ; <upper> ; (<condition_list> ;)?
  544. fmt.Fprintln(w, "\tspecial = map[rune]struct{ toLower, toTitle, toUpper string }{")
  545. parse("SpecialCasing.txt", func(p *ucd.Parser) {
  546. // Skip conditional entries.
  547. if p.String(4) != "" {
  548. return
  549. }
  550. r := p.Rune(0)
  551. fmt.Fprintf(w, "\t\t0x%04x: {%q, %q, %q},\n",
  552. r, string(p.Runes(1)), string(p.Runes(2)), string(p.Runes(3)))
  553. })
  554. fmt.Fprint(w, "\t}\n\n")
  555. // <code>; <type>; <runes>
  556. table := map[rune]struct{ simple, full, special string }{}
  557. parse("CaseFolding.txt", func(p *ucd.Parser) {
  558. r := p.Rune(0)
  559. t := p.String(1)
  560. v := string(p.Runes(2))
  561. if t != "T" && v == string(unicode.ToLower(r)) {
  562. return
  563. }
  564. x := table[r]
  565. switch t {
  566. case "C":
  567. x.full = v
  568. x.simple = v
  569. case "S":
  570. x.simple = v
  571. case "F":
  572. x.full = v
  573. case "T":
  574. x.special = v
  575. }
  576. table[r] = x
  577. })
  578. fmt.Fprintln(w, "\tfoldMap = map[rune]struct{ simple, full, special string }{")
  579. for r := rune(0); r < 0x10FFFF; r++ {
  580. x, ok := table[r]
  581. if !ok {
  582. continue
  583. }
  584. fmt.Fprintf(w, "\t\t0x%04x: {%q, %q, %q},\n", r, x.simple, x.full, x.special)
  585. }
  586. fmt.Fprint(w, "\t}\n\n")
  587. // Break property
  588. notBreak := map[rune]bool{}
  589. parse("auxiliary/WordBreakProperty.txt", func(p *ucd.Parser) {
  590. switch p.String(1) {
  591. case "Extend", "Format", "MidLetter", "MidNumLet", "Single_Quote",
  592. "ALetter", "Hebrew_Letter", "Numeric", "ExtendNumLet":
  593. notBreak[p.Rune(0)] = true
  594. }
  595. })
  596. fmt.Fprintln(w, "\tbreakProp = []struct{ lo, hi rune }{")
  597. inBreak := false
  598. for r := rune(0); r <= lastRuneForTesting; r++ {
  599. if isBreak := !notBreak[r]; isBreak != inBreak {
  600. if isBreak {
  601. fmt.Fprintf(w, "\t\t{0x%x, ", r)
  602. } else {
  603. fmt.Fprintf(w, "0x%x},\n", r-1)
  604. }
  605. inBreak = isBreak
  606. }
  607. }
  608. if inBreak {
  609. fmt.Fprintf(w, "0x%x},\n", lastRuneForTesting)
  610. }
  611. fmt.Fprint(w, "\t}\n\n")
  612. // Word break test
  613. // Filter out all samples that do not contain cased characters.
  614. cased := map[rune]bool{}
  615. parse("DerivedCoreProperties.txt", func(p *ucd.Parser) {
  616. if p.String(1) == "Cased" {
  617. cased[p.Rune(0)] = true
  618. }
  619. })
  620. fmt.Fprintln(w, "\tbreakTest = []string{")
  621. parse("auxiliary/WordBreakTest.txt", func(p *ucd.Parser) {
  622. c := strings.Split(p.String(0), " ")
  623. const sep = '|'
  624. numCased := 0
  625. test := ""
  626. for ; len(c) >= 2; c = c[2:] {
  627. if c[0] == "÷" && test != "" {
  628. test += string(sep)
  629. }
  630. i, err := strconv.ParseUint(c[1], 16, 32)
  631. r := rune(i)
  632. if err != nil {
  633. log.Fatalf("Invalid rune %q.", c[1])
  634. }
  635. if r == sep {
  636. log.Fatalf("Separator %q not allowed in test data. Pick another one.", sep)
  637. }
  638. if cased[r] {
  639. numCased++
  640. }
  641. test += string(r)
  642. }
  643. if numCased > 1 {
  644. fmt.Fprintf(w, "\t\t%q,\n", test)
  645. }
  646. })
  647. fmt.Fprintln(w, "\t}")
  648. fmt.Fprintln(w, ")")
  649. gen.WriteGoFile("tables_test.go", "cases", w.Bytes())
  650. }
  651. // These functions are just used for verification that their definition have not
  652. // changed in the Unicode Standard.
  653. func verifyCased(r rune) bool {
  654. return verifyLower(r) || verifyUpper(r) || unicode.IsTitle(r)
  655. }
  656. func verifyLower(r rune) bool {
  657. return unicode.IsLower(r) || unicode.Is(unicode.Other_Lowercase, r)
  658. }
  659. func verifyUpper(r rune) bool {
  660. return unicode.IsUpper(r) || unicode.Is(unicode.Other_Uppercase, r)
  661. }
  662. // verifyIgnore is an approximation of the Case_Ignorable property using the
  663. // core unicode package. It is used to reduce the size of the test data.
  664. func verifyIgnore(r rune) bool {
  665. props := []*unicode.RangeTable{
  666. unicode.Mn,
  667. unicode.Me,
  668. unicode.Cf,
  669. unicode.Lm,
  670. unicode.Sk,
  671. }
  672. for _, p := range props {
  673. if unicode.Is(p, r) {
  674. return true
  675. }
  676. }
  677. return false
  678. }
  679. // printProperties prints tables of rune properties from the given UCD file.
  680. // A filter func f can be given to exclude certain values. A rune r will have
  681. // the indicated property if it is in the generated table or if f(r).
  682. func printProperties(w io.Writer, file, property string, f func(r rune) bool) int {
  683. verify := map[rune]bool{}
  684. n := 0
  685. varNameParts := strings.Split(property, "_")
  686. varNameParts[0] = strings.ToLower(varNameParts[0])
  687. fmt.Fprintf(w, "\t%s = map[rune]bool{\n", strings.Join(varNameParts, ""))
  688. parse(file, func(p *ucd.Parser) {
  689. if p.String(1) == property {
  690. r := p.Rune(0)
  691. verify[r] = true
  692. if !f(r) {
  693. n++
  694. fmt.Fprintf(w, "\t\t0x%.4x: true,\n", r)
  695. }
  696. }
  697. })
  698. fmt.Fprint(w, "\t}\n\n")
  699. // Verify that f is correct, that is, it represents a subset of the property.
  700. for r := rune(0); r <= lastRuneForTesting; r++ {
  701. if !verify[r] && f(r) {
  702. log.Fatalf("Incorrect filter func for property %q.", property)
  703. }
  704. }
  705. return n
  706. }
  707. // The newCaseTrie, sparseValues and sparseOffsets definitions below are
  708. // placeholders referred to by gen_trieval.go. The real definitions are
  709. // generated by this program and written to tables.go.
  710. func newCaseTrie(int) int { return 0 }
  711. var (
  712. sparseValues [0]valueRange
  713. sparseOffsets [0]uint16
  714. )