gen.go 21 KB

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