Debian Codegraph @

internal/gen/gentables/main.go

raw
1 // Copyright 2023 Charlie Vieth. All rights reserved.
2 // Use of this source code is governed by the MIT license.
3
4 // gen generates the Unicode lookup tables used by strcase. The tables must
5 // be regenerated if this code is changed (`go generate`).
6 package main
7
8 import (
9 "bytes"
10 "cmp"
11 "crypto/sha256"
12 "encoding/binary"
13 "encoding/hex"
14 "encoding/json"
15 "flag"
16 "fmt"
17 "go/format"
18 "io/fs"
19 "log"
20 "math"
21 "os"
22 "os/exec"
23 "os/signal"
24 "path/filepath"
25 "runtime"
26 "runtime/pprof"
27 "slices"
28 "sort"
29 "strconv"
30 "strings"
31 "sync"
32 "sync/atomic"
33 "time"
34 "unicode"
35
36 "github.com/schollz/progressbar/v3"
37 "golang.org/x/term"
38 "golang.org/x/text/unicode/rangetable"
39
40 "github.com/charlievieth/strcase/internal/gen/gen"
41 "github.com/charlievieth/strcase/internal/gen/ucd"
42 "github.com/charlievieth/strcase/internal/gen/util"
43 )
44
45 func init() {
46 initLogs()
47
48 // If $GOMAXPROCS isn't set, use the full capacity of the machine.
49 // For small machines, use at least 4 threads.
50 if os.Getenv("GOMAXPROCS") == "" {
51 n := runtime.NumCPU()
52 if n < 4 {
53 n = 4
54 }
55 runtime.GOMAXPROCS(n)
56 }
57 }
58
59 func initLogs() {
60 log.SetPrefix("")
61 log.SetFlags(log.Lshortfile)
62 log.SetOutput(os.Stdout) // use stdout instead of stderr
63 }
64
65 // WARN: we need to include 'İ' (0x0130) and 'ı' (0x0131) in _FoldMap because
66 // we don't want to fallback to using toUpperLower() since we don't accept the
67 // upper/lower-case variants of these runes (breaks simple folding semantics).
68 //
69 // We should remove these runes and any other runes in _FoldMap from _UpperLower
70 // and maybe remove 'İ' and 'ı' from _FoldMap as well.
71 //
72 // TODO: remove İ (0x0130) from _UpperLower and fix tests
73
74 // TODO: consider renaming the generated tables
75 const (
76 MaxChar = 0x10FFFF
77 caseFoldShift = 19
78 caseFoldSize = 8192
79 foldMapShift = 24
80 foldMapSize = 256
81 upperLowerTableSize = 8192
82 upperLowerTableShift = 19
83 )
84
85 const (
86 GenCookieKey = "b3d53e54921be5a951563a7e77bfcb1a"
87 GenCookieValue = "c1bbb5805a8c389e0dd50234d5c38cce"
88 )
89
90 type foldPair struct {
91 From uint32
92 To uint32
93 }
94
95 var (
96 categories *unicode.RangeTable
97 caseFolds []foldPair
98 caseRanges []unicode.CaseRange // used by toLower and toUpper
99 caseOrbit []foldPair // used by simpleFold
100 asciiFold [unicode.MaxASCII + 1]uint16
101 )
102
103 var (
104 chars = make([]Char, MaxChar+1)
105 scripts = make(map[string][]rune)
106 props = make(map[string][]rune) // a property looks like a script; can share the format
107 )
108
109 // TODO: move
110 func loadCaseFolds() {
111 ucd.Parse(gen.OpenUCDFile("CaseFolding.txt"), func(p *ucd.Parser) {
112 kind := p.String(1)
113 if kind != "C" && kind != "S" {
114 // Only care about 'common' and 'simple' foldings.
115 return
116 }
117 p1 := p.Rune(0)
118 p2 := p.Rune(2)
119 caseFolds = append(caseFolds, foldPair{uint32(p1), uint32(p2)})
120 chars[p1].foldCase = p2
121 })
122 slices.SortFunc(caseFolds, func(a, b foldPair) int {
123 return cmp.Compare(a.From, b.From)
124 })
125 }
126
127 var buildTags = map[string]struct{ version, buildTags, filename string }{
128 "13.0.0": {"13.0.0", "go1.16,!go1.21", "tables_go116.go"},
129 "15.0.0": {"15.0.0", "go1.21,!go1.27", "tables_go121.go"},
130 "17.0.0": {"17.0.0", "go1.27", "tables_go127.go"},
131 }
132
133 // tablesFileName is the names of the file to generate and is based off
134 // of the Go version this program is ran with.
135 //
136 // NB: this must be called after command line flags are parsed
137 func tablesFileName(dirname string) string {
138 // gen.UnicodeVersion is set by the "-unicode" flag
139 if name := buildTags[gen.UnicodeVersion()].filename; name != "" {
140 return filepath.Join(dirname, name)
141 }
142 log.Panicf("unsupported Unicode version %q this script might need "+
143 "to be updated", gen.UnicodeVersion())
144 panic("unreachable")
145 }
146
147 type span struct {
148 Start, End int64
149 }
150
151 func generateSpans(start, end, delta int64) []span {
152 maxEnd := end
153 var spans []span
154 for i := start; i <= end; i += delta {
155 end := i + delta
156 if end >= maxEnd {
157 end = maxEnd
158 }
159 spans = append(spans, span{Start: i, End: end})
160 }
161
162 // Reverse spans since larger values are more likely to be better seeds.
163 // We previously randomly shuffled the spans, but led to non-deterministic
164 // behavior when more than one seed was ideal.
165 for i := len(spans)/2 - 1; i >= 0; i-- {
166 opp := len(spans) - 1 - i
167 spans[i], spans[opp] = spans[opp], spans[i]
168 }
169
170 return spans
171 }
172
173 func hash(seed, key, shift uint32) uint32 {
174 m := seed * key
175 return m >> shift
176 }
177
178 func shiftHash(seed, key, shift uint32) uint32 {
179 key |= key << 24 // fill top bits not occupied by unicode.MaxRune
180 m := seed * key
181 return m >> shift
182 }
183
184 type HashConfig struct {
185 TableName string
186 TableSize int
187 HashShift uint32 // TODO: this can be calculated from TableSize
188 // TODO: name is confusing with HashShift
189 ShiftHash bool // Use shiftHash instead of hash
190
191 // Use the first valid hash value instead of performing an exhaustive
192 // search to find the "best" hash seed. The seed is not deterministic
193 // and this is only meant for testing since it is much much faster.
194 FirstValidHash bool
195 }
196
197 var hashSeedCache = map[string]uint32{}
198
199 func cacheKey(inputs []uint32) string {
200 if !slices.IsSorted(inputs) {
201 slices.Sort(inputs)
202 }
203 b := make([]byte, len(inputs)*4)
204 for i, u := range inputs {
205 binary.LittleEndian.PutUint32(b[i*4:], u)
206 }
207 sum := sha256.Sum256(b)
208 return hex.EncodeToString(sum[:])
209 }
210
211 // TODO:
212 // - Return the first working hash value.
213 // - Find a better algorithm.
214 //
215 // GenerateHashValues performs a brute-force search for the best possible
216 // multiplicative hash seed for inputs. All uint32 values are checked.
217 func (conf *HashConfig) GenerateHashValues(inputs []uint32) (hashSeed uint32) {
218 const delta = 512 * 1024
219
220 if *useCachedSeeds {
221 if seed, ok := tableInfo.TableHashes[conf.TableName]; ok {
222 log.Printf("WARN: using cached seed %d for table: %s", seed, conf.TableName)
223 return seed
224 }
225 }
226
227 if seed, ok := hashSeedCache[cacheKey(inputs)]; ok {
228 log.Printf("Using previously computed seed (0x%04X) for the %s table",
229 seed, conf.TableName)
230 tableInfo.TableHashes[conf.TableName] = seed
231 return seed
232 }
233
234 if slices.IndexFunc(inputs, func(u uint32) bool { return u != 0 }) < 0 {
235 log.Panicf("Input is all zeros for table: %s", conf.TableName)
236 }
237
238 log.Printf("Generating values for the %s table (this may take a long time)...\n",
239 conf.TableName)
240
241 // This can take awhile so use a progress bar.
242 var bar *progressbar.ProgressBar
243 if term.IsTerminal(int(os.Stdout.Fd())) {
244 bar = progressbar.Default(math.MaxUint32)
245 } else {
246 bar = progressbar.DefaultSilent(math.MaxUint32)
247 }
248 start := time.Now()
249
250 // TODO: set GOMAXPROCS to NumCPU ??
251 numProcs := runtime.GOMAXPROCS(0)
252
253 // When FirstValidHash we exit before consuming all spans.
254 done := make(chan struct{})
255 defer close(done)
256
257 ch := make(chan *span, numProcs*2)
258 go func() {
259 spans := generateSpans(1, math.MaxUint32, delta)
260 for i := range spans {
261 select {
262 case ch <- &spans[i]:
263 case <-done:
264 return
265 }
266 }
267 close(ch)
268 }()
269
270 var (
271 bestIndex = int64(math.MaxInt64)
272 bestSeed uint32
273 foundSeed atomic.Bool
274 mu sync.Mutex
275 wg sync.WaitGroup
276 )
277 if seed := tableInfo.TableHashes[conf.TableName]; seed != 0 {
278 bestSeed = seed
279 }
280 for i := 0; i < numProcs; i++ {
281 wg.Add(1)
282 go func(inputs []uint32) {
283 defer wg.Done()
284 seen := make([]bool, conf.TableSize)
285 for sp := range ch {
286 if foundSeed.Load() {
287 return
288 }
289 best := atomic.LoadInt64(&bestIndex)
290 Loop:
291 for i := sp.Start; i <= sp.End && best >= int64(len(inputs)); i++ {
292 for i := range seen {
293 seen[i] = false // TODO: zero
294 }
295 // TODO: load more often
296 if i%8192 == 0 {
297 best = atomic.LoadInt64(&bestIndex)
298 }
299 var maxIdx int64
300 shift := conf.HashShift
301 seed := uint32(i)
302 useShiftHash := conf.ShiftHash
303 // TODO: is there anyway we can optimize this?
304 for _, x := range inputs {
305 var u int64
306 if useShiftHash {
307 u = int64(shiftHash(seed, x, shift))
308 } else {
309 u = int64(hash(seed, x, shift))
310 }
311 if u > best || seen[u] {
312 continue Loop
313 }
314 seen[u] = true
315 if u > maxIdx {
316 maxIdx = u
317 }
318 }
319 best = atomic.LoadInt64(&bestIndex)
320 if maxIdx < best {
321 // Use mutex to simplify updating both values
322 mu.Lock()
323 best = atomic.LoadInt64(&bestIndex) // re-check
324 if maxIdx < best {
325 atomic.StoreInt64(&bestIndex, maxIdx)
326 atomic.StoreUint32(&bestSeed, seed)
327
328 // Stop at the first valid has
329 if conf.FirstValidHash && foundSeed.CompareAndSwap(false, true) {
330 log.Println("WARN: -first-valid-hash flag provided: stopping early")
331 mu.Unlock()
332 return
333 }
334 }
335 mu.Unlock()
336 }
337 }
338 // TODO: figure out is we need to use `1 + sp.End - sp.Start`
339 if err := bar.Add64(sp.End - sp.Start); err != nil {
340 max := bar.GetMax64()
341 log.Panicf("error updating progress bar: %v: max: %d delta: %d",
342 err, max, 1+sp.End-sp.Start)
343 }
344 }
345 }(inputs)
346 }
347 wg.Wait()
348 bar.Close()
349
350 // TODO: we can probably just check bestSeed
351 if bestIndex == math.MaxInt64 || bestSeed == 0 {
352 log.Panicf("Failed to generate hash values for %s table: max_index: %d seed: %d",
353 conf.TableName, bestIndex, bestSeed)
354 }
355 if bestIndex <= int64(conf.TableSize/2) {
356 // Error if the algorithm found a table size that is a smaller power of 2
357 log.Panicf("The hash table size can be reduced to %d or less. The best index is: %d.",
358 conf.TableSize/2, bestIndex)
359 }
360
361 log.Printf("Successfully generated %s values in: %s\n"+
362 " max_index: %d\n"+
363 " seed: %d\n",
364 conf.TableName, time.Since(start), bestIndex, bestSeed)
365 // log.Printf("Successfully generated %s values in: %s", conf.TableName, time.Since(start))
366 // log.Printf(" max_index: %d", bestIndex)
367 // log.Printf(" seed: %d", bestSeed)
368
369 hashSeedCache[cacheKey(inputs)] = bestSeed // Cache result
370 tableInfo.TableHashes[conf.TableName] = bestSeed
371 return bestSeed
372 }
373
374 const (
375 CaseUpper = 1 << iota
376 CaseLower
377 CaseTitle
378 CaseNone = 0 // must be zero
379 CaseMissing = -1 // character not present; not a valid case state
380 )
381
382 type caseState struct {
383 point rune
384 _case int
385 deltaToUpper rune
386 deltaToLower rune
387 deltaToTitle rune
388 }
389
390 // Is d a continuation of the state of c?
391 func (c *caseState) adjacent(d *caseState) bool {
392 if d.point < c.point {
393 c, d = d, c
394 }
395 switch {
396 case d.point != c.point+1: // code points not adjacent (shouldn't happen)
397 return false
398 case d._case != c._case: // different cases
399 return c.upperLowerAdjacent(d)
400 case c._case == CaseNone:
401 return false
402 case c._case == CaseMissing:
403 return false
404 case d.deltaToUpper != c.deltaToUpper:
405 return false
406 case d.deltaToLower != c.deltaToLower:
407 return false
408 case d.deltaToTitle != c.deltaToTitle:
409 return false
410 }
411 return true
412 }
413
414 // Is d the same as c, but opposite in upper/lower case? this would make it
415 // an element of an UpperLower sequence.
416 func (c *caseState) upperLowerAdjacent(d *caseState) bool {
417 // check they're a matched case pair. we know they have adjacent values
418 switch {
419 case c._case == CaseUpper && d._case != CaseLower:
420 return false
421 case c._case == CaseLower && d._case != CaseUpper:
422 return false
423 }
424 // matched pair (at least in upper/lower). make the order Upper Lower
425 if c._case == CaseLower {
426 c, d = d, c
427 }
428 // for an Upper Lower sequence the deltas have to be in order
429 // c: 0 1 0
430 // d: -1 0 -1
431 switch {
432 case c.deltaToUpper != 0:
433 return false
434 case c.deltaToLower != 1:
435 return false
436 case c.deltaToTitle != 0:
437 return false
438 case d.deltaToUpper != -1:
439 return false
440 case d.deltaToLower != 0:
441 return false
442 case d.deltaToTitle != -1:
443 return false
444 }
445 return true
446 }
447
448 // Does this character start an UpperLower sequence?
449 func (c *caseState) isUpperLower() bool {
450 // for an Upper Lower sequence the deltas have to be in order
451 // c: 0 1 0
452 switch {
453 case c.deltaToUpper != 0:
454 return false
455 case c.deltaToLower != 1:
456 return false
457 case c.deltaToTitle != 0:
458 return false
459 }
460 return true
461 }
462
463 // Does this character start a LowerUpper sequence?
464 func (c *caseState) isLowerUpper() bool {
465 // for an Upper Lower sequence the deltas have to be in order
466 // c: -1 0 -1
467 switch {
468 case c.deltaToUpper != -1:
469 return false
470 case c.deltaToLower != 0:
471 return false
472 case c.deltaToTitle != -1:
473 return false
474 }
475 return true
476 }
477
478 func getCaseState(i rune) (c *caseState) {
479 c = &caseState{point: i, _case: CaseNone}
480 ch := &chars[i]
481 switch ch.codePoint {
482 case 0:
483 c._case = CaseMissing // Will get NUL wrong but that doesn't matter
484 return
485 case ch.upperCase:
486 c._case = CaseUpper
487 case ch.lowerCase:
488 c._case = CaseLower
489 case ch.titleCase:
490 c._case = CaseTitle
491 }
492 // Some things such as roman numeral U+2161 don't describe themselves
493 // as upper case, but have a lower case. Second-guess them.
494 if c._case == CaseNone && ch.lowerCase != 0 {
495 c._case = CaseUpper
496 }
497 // Same in the other direction.
498 if c._case == CaseNone && ch.upperCase != 0 {
499 c._case = CaseLower
500 }
501
502 if ch.upperCase != 0 {
503 c.deltaToUpper = ch.upperCase - i
504 }
505 if ch.lowerCase != 0 {
506 c.deltaToLower = ch.lowerCase - i
507 }
508 if ch.titleCase != 0 {
509 c.deltaToTitle = ch.titleCase - i
510 }
511 return
512 }
513
514 // TODO: we need to do this since we can't use the [unicode] package due to
515 // a version mismatch between the Unicode version we're generating for and
516 // Unicode version of Go version being used to generate this.
517 //
518 // TODO: fixup the above comment.
519 func generateCaseRanges() []unicode.CaseRange {
520 if gen.UnicodeVersion() == unicode.Version {
521 return unicode.CaseRanges
522 }
523 // The requested Unicode version does not match the stdlibs
524 var (
525 cases []unicode.CaseRange
526 startState *caseState // the start of a run; nil for not active
527 prevState = &caseState{} // the state of the previous character
528 )
529 for i := range chars {
530 state := getCaseState(rune(i))
531 if state.adjacent(prevState) {
532 prevState = state
533 continue
534 }
535 // end of run (possibly)
536 if c, ok := getCaseRange(startState, prevState); ok {
537 cases = append(cases, c)
538 }
539 // printCaseRange(startState, prevState)
540 startState = nil
541 if state._case != CaseMissing && state._case != CaseNone {
542 startState = state
543 }
544 prevState = state
545 }
546
547 return cases
548 }
549
550 // Modified version of golang.org/x/text/internal/export/unicode.printCaseRange
551 func getCaseRange(lo, hi *caseState) (unicode.CaseRange, bool) {
552 if lo == nil {
553 return unicode.CaseRange{}, false
554 }
555 if lo.deltaToUpper == 0 && lo.deltaToLower == 0 && lo.deltaToTitle == 0 {
556 // character represents itself in all cases - no need to mention it
557 return unicode.CaseRange{}, false
558 }
559 switch {
560 case hi.point > lo.point && lo.isUpperLower():
561 c := unicode.CaseRange{
562 Lo: uint32(lo.point),
563 Hi: uint32(hi.point),
564 Delta: [unicode.MaxCase]rune{
565 unicode.UpperLower,
566 unicode.UpperLower,
567 unicode.UpperLower,
568 },
569 }
570 return c, true
571 case hi.point > lo.point && lo.isLowerUpper():
572 log.Panicf("LowerUpper sequence: should not happen: %U. "+
573 "If it's real, need to fix To()", lo.point)
574 default:
575 c := unicode.CaseRange{
576 Lo: uint32(lo.point),
577 Hi: uint32(hi.point),
578 Delta: [unicode.MaxCase]rune{
579 lo.deltaToUpper,
580 lo.deltaToLower,
581 lo.deltaToTitle,
582 },
583 }
584 return c, true
585 }
586 return unicode.CaseRange{}, false
587 }
588
589 // simpleFold is the same as unicode.SimpleFold but uses the version of Unicode
590 // we loaded.
591 func simpleFold(r rune) rune {
592 if r < 0 || r > unicode.MaxRune {
593 return r
594 }
595
596 if int(r) < len(asciiFold) {
597 return rune(asciiFold[r])
598 }
599
600 // Consult caseOrbit table for special cases.
601 lo := 0
602 hi := len(caseOrbit)
603 for lo < hi {
604 m := lo + (hi-lo)/2
605 if rune(caseOrbit[m].From) < r {
606 lo = m + 1
607 } else {
608 hi = m
609 }
610 }
611 if lo < len(caseOrbit) && rune(caseOrbit[lo].From) == r {
612 return rune(caseOrbit[lo].To)
613 }
614
615 // No folding specified. This is a one- or two-element
616 // equivalence class containing rune and ToLower(rune)
617 // and ToUpper(rune) if they are different from rune.
618 if l := toLower(r); l != r {
619 return l
620 }
621 return toUpper(r)
622 }
623
624 // to maps the rune using the specified case mapping.
625 // It additionally reports whether caseRange contained a mapping for r.
626 func to(_case int, r rune, caseRange []unicode.CaseRange) (mappedRune rune) {
627 if len(caseRange) == 0 {
628 panic("empty caseRange")
629 }
630 if _case < 0 || unicode.MaxCase <= _case {
631 return unicode.ReplacementChar // as reasonable an error as any
632 }
633 // binary search over ranges
634 lo := 0
635 hi := len(caseRange)
636 for lo < hi {
637 m := lo + (hi-lo)/2
638 cr := caseRange[m]
639 if rune(cr.Lo) <= r && r <= rune(cr.Hi) {
640 delta := cr.Delta[_case]
641 if delta > unicode.MaxRune {
642 // In an Upper-Lower sequence, which always starts with
643 // an UpperCase letter, the real deltas always look like:
644 // {0, 1, 0} UpperCase (Lower is next)
645 // {-1, 0, -1} LowerCase (Upper, Title are previous)
646 // The characters at even offsets from the beginning of the
647 // sequence are upper case; the ones at odd offsets are lower.
648 // The correct mapping can be done by clearing or setting the low
649 // bit in the sequence offset.
650 // The constants UpperCase and TitleCase are even while LowerCase
651 // is odd so we take the low bit from _case.
652 return rune(cr.Lo) + ((r-rune(cr.Lo))&^1 | rune(_case&1))
653 }
654 return r + delta
655 }
656 if r < rune(cr.Lo) {
657 hi = m
658 } else {
659 lo = m + 1
660 }
661 }
662 return r
663 }
664
665 // toUpper is the same as unicode.ToUpper but uses the Unicode table we loaded.
666 func toUpper(r rune) rune {
667 if r <= unicode.MaxASCII {
668 if 'a' <= r && r <= 'z' {
669 r -= 'a' - 'A'
670 }
671 return r
672 }
673 return to(unicode.UpperCase, r, caseRanges)
674 }
675
676 // toLower is the same as unicode.ToLower but uses the Unicode table we loaded.
677 func toLower(r rune) rune {
678 if r <= unicode.MaxASCII {
679 if 'A' <= r && r <= 'Z' {
680 r += 'a' - 'A'
681 }
682 return r
683 }
684 return to(unicode.LowerCase, r, caseRanges)
685 }
686
687 func folds(sr rune) []rune {
688 r := simpleFold(sr)
689 runes := make([]rune, 1, 2)
690 runes[0] = sr
691 for r != sr {
692 runes = append(runes, r)
693 r = simpleFold(r)
694 }
695 return runes
696 }
697
698 func genCaseFolds(w *bytes.Buffer, firstValidHash bool) {
699 folds := caseFolds
700 inputs := make([]uint32, len(folds))
701 for i, p := range folds {
702 inputs[i] = p.From
703 }
704
705 conf := HashConfig{
706 TableName: "CaseFolds",
707 TableSize: caseFoldSize,
708 HashShift: caseFoldShift,
709 FirstValidHash: firstValidHash,
710 }
711 seed := conf.GenerateHashValues(inputs)
712
713 // TODO: probably don't need this
714 pairs := make([]foldPair, len(folds))
715 copy(pairs, folds)
716 slices.SortFunc(pairs, func(a, b foldPair) int {
717 return cmp.Compare(a.From, b.From)
718 })
719
720 hashes := make([]foldPair, 0, len(pairs))
721 for i, p := range pairs {
722 hashes = append(hashes, foldPair{
723 From: hash(p.From, seed, caseFoldShift),
724 To: uint32(i),
725 })
726 }
727 slices.SortFunc(hashes, func(a, b foldPair) int {
728 return cmp.Compare(a.From, b.From)
729 })
730
731 fmt.Fprint(w, "\n")
732 fmt.Fprintf(w, "const _CaseFoldsSeed = 0x%04X\n", seed)
733 fmt.Fprintf(w, "const _CaseFoldsShift = %d\n", caseFoldShift)
734 fmt.Fprint(w, "\n")
735 fmt.Fprintln(w, "// _CaseFolds stores all Unicode simple case-folds.")
736 fmt.Fprintf(w, "var _CaseFolds = [%d]foldPair{\n", caseFoldSize)
737 for _, h := range hashes {
738 p := pairs[h.To]
739 fmt.Fprintf(w, "\t%d: {0x%04X, 0x%04X}, // %q => %q\n", h.From, p.From, p.To, p.From, p.To)
740 }
741 fmt.Fprint(w, "}\n\n")
742 }
743
744 func dedupe(r []rune) []rune {
745 if len(r) < 2 {
746 return r
747 }
748 slices.Sort(r)
749 return slices.Compact(r)
750 }
751
752 // TODO: consider renaming this table
753 func genFoldTable(w *bytes.Buffer, firstValidHash bool) {
754 runes := make(map[rune][]rune)
755 rangetable.Visit(categories, func(r rune) {
756 ff := folds(r)
757 switch n := len(ff); {
758 case n > 2:
759 fallthrough
760 case n == 2 && ff[1] != toUpper(r) && ff[1] != toLower(r):
761 // A two-element fold orbit is normally covered by the _UpperLower
762 // table, but when the other rune is neither the upper nor lower
763 // case form of r it cannot be represented there and must be
764 // stored in _FoldMap.
765 fallthrough
766 case n == 1 && toUpper(r) != toLower(r):
767 runes[r] = append(runes[r], ff...)
768 }
769 })
770 // FIXME: fix the below since we have to work around it in the code
771 // WARN: we should not need to add this manually
772 runes['İ'] = append(runes['İ'], 'İ')
773 runes['ß'] = append(runes['ß'], 'ẞ')
774
775 keys := make([]uint32, 0, len(runes))
776 for k, rs := range runes {
777 // Make sure the key is included (was an issue with: 'ß')
778 if !slices.Contains(rs, k) {
779 rs = append(rs, k)
780 }
781 runes[k] = dedupe(rs)
782 keys = append(keys, uint32(k))
783 }
784
785 conf := HashConfig{
786 TableName: "FoldMap",
787 TableSize: foldMapSize,
788 HashShift: foldMapShift,
789 FirstValidHash: firstValidHash,
790 }
791 seed := conf.GenerateHashValues(keys)
792
793 // Make key the first element of the rune slice
794 folds := make([][]rune, 0, len(runes))
795 for k, rs := range runes {
796 if rs[0] != k {
797 a := []rune{k}
798 for _, r := range rs {
799 if r != k {
800 a = append(a, r)
801 }
802 }
803 rs = a
804 }
805 folds = append(folds, rs)
806 }
807 slices.SortFunc(folds, func(f1, f2 []rune) int {
808 return cmp.Compare(f1[0], f2[0])
809 })
810
811 fmt.Fprint(w, "\n")
812 fmt.Fprintf(w, "const _FoldMapSeed = 0x%04X\n", seed)
813 fmt.Fprintf(w, "const _FoldMapShift = %d\n", foldMapShift)
814 fmt.Fprint(w, "\n")
815 fmt.Fprintln(w, "// FoldMap stores the Unicode case-folds for characters "+
816 "that have two or more folds.")
817 fmt.Fprintf(w, "var _FoldMap = [%d][4]uint16{\n", foldMapSize)
818 for _, ff := range folds {
819 fmt.Fprintf(w, "\t%d: {0x%04X", hash(uint32(ff[0]), seed, foldMapShift), ff[0])
820 for _, f := range ff[1:] {
821 fmt.Fprintf(w, ", 0x%04X", f)
822 }
823 fmt.Fprintf(w, "}, // %q\n", ff)
824 }
825 fmt.Fprint(w, "}\n\n")
826
827 type runeSet struct {
828 r uint32
829 a [2]rune
830 }
831
832 var noUpperLower []runeSet
833 for k, rs := range runes {
834 u := toUpper(k)
835 l := toLower(k)
836 a := make([]rune, 0, 2)
837 for _, r := range rs {
838 if r != u && r != l {
839 a = append(a, r)
840 }
841 }
842 if len(a) > 2 {
843 log.Fatalf("fold set excluding upper/lower %q "+
844 "must have 2 or less elements got: %d", a, len(a))
845 }
846 switch len(a) {
847 case 0:
848 a = append(a, k, k)
849 case 1:
850 a = append(a, a[0])
851 }
852 slices.Sort(a)
853 noUpperLower = append(noUpperLower, runeSet{uint32(k), [2]rune{a[0], a[1]}})
854 }
855 slices.SortFunc(noUpperLower, func(c1, c2 runeSet) int {
856 return cmp.Compare(c1.r, c2.r)
857 })
858
859 const foldMapExcludingUpperLowerComment = `
860 // _FoldMapExcludingUpperLower stores the Unicode case-folds for charactecrs that
861 // have two or more folds, but excludes the uppercase and lowercase forms of the
862 // character.`
863
864 fmt.Fprintln(w, "")
865 fmt.Fprintf(w, "const _FoldMapExcludingUpperLowerSeed = 0x%04X\n", seed)
866 fmt.Fprintf(w, "const _FoldMapExcludingUpperLowerShift = %d\n", foldMapShift)
867 fmt.Fprintln(w, "")
868
869 fmt.Fprintln(w, foldMapExcludingUpperLowerComment)
870 fmt.Fprintf(w, "var _FoldMapExcludingUpperLower = [%d]struct {\n", foldMapSize)
871 fmt.Fprintln(w, "\tr uint16")
872 fmt.Fprintln(w, "\ta [2]uint16")
873 fmt.Fprintln(w, "}{")
874 for _, c := range noUpperLower {
875 h := hash(c.r, seed, foldMapShift)
876 if c.a[0] > math.MaxUint16 {
877 log.Fatalf("rune 0x%04X is larger than MaxUint16 0x%04X", c.a[0], math.MaxUint16)
878 }
879 if c.a[1] > math.MaxUint16 {
880 log.Fatalf("rune 0x%04X is larger than MaxUint16 0x%04X", c.a[1], math.MaxUint16)
881 }
882 fmt.Fprintf(w, "\t%d: {0x%04X, [2]uint16{0x%04X, 0x%04X}}, // %q: [%q, %q]\n",
883 h, c.r, c.a[0], c.a[1], c.r, c.a[0], c.a[1])
884 }
885 fmt.Fprint(w, "}\n\n")
886 }
887
888 func genUpperLowerTable(w *bytes.Buffer, firstValidHash bool) {
889 // WARN: attempt to use caseOrbit so that we don't have to handle special
890 // cases with toUpperLowerSpecial.
891
892 const docComment = `
893 // _UpperLower stores upper/lower case pairs of Unicode code points.
894 // This takes up more space than the stdlib's "unicode" package, but
895 // is roughly ~4x faster.`
896
897 type Case struct {
898 Rune rune `json:"rune"`
899 Upper rune `json:"upper"`
900 Lower rune `json:"lower"`
901 }
902 var cases []Case
903
904 // special cases where Rune != Upper or Lower
905 var special []Case
906
907 for r := rune('A'); r <= unicode.MaxRune; r++ {
908 if r <= unicode.MaxASCII {
909 continue
910 }
911 l := toLower(r)
912 u := toUpper(r)
913 if r != l || r != u {
914 if r == l || r == u {
915 cases = append(cases, Case{Rune: r, Upper: u, Lower: l})
916 } else {
917 special = append(special, Case{Rune: r, Upper: u, Lower: l})
918 }
919 }
920 }
921
922 keys := make([]uint32, len(cases))
923 for i, c := range cases {
924 keys[i] = uint32(c.Rune)
925 }
926 // TODO: this is probably not necessary
927 slices.Sort(keys)
928 keys = slices.Compact(keys)
929
930 conf := HashConfig{
931 TableName: "UpperLower",
932 TableSize: upperLowerTableSize,
933 HashShift: upperLowerTableShift,
934 ShiftHash: true,
935 FirstValidHash: firstValidHash,
936 }
937 seed := conf.GenerateHashValues(keys)
938
939 fmt.Fprint(w, "\n")
940 fmt.Fprintf(w, "const _UpperLowerSeed = 0x%04X\n", seed)
941 fmt.Fprintf(w, "const _UpperLowerShift = %d\n", upperLowerTableShift)
942 fmt.Fprint(w, "\n")
943 fmt.Fprintln(w, strings.TrimSpace(docComment))
944 fmt.Fprintf(w, "var _UpperLower = [%d][2]uint32{\n", upperLowerTableSize)
945 for _, c := range cases {
946 fmt.Fprintf(w, "\t%d: {0x%04X, 0x%04X}, // %q => %q\n",
947 shiftHash(seed, uint32(c.Rune), upperLowerTableShift), c.Upper, c.Lower, c.Upper, c.Lower)
948 }
949 fmt.Fprint(w, "}\n\n")
950
951 slices.SortFunc(special, func(c1, c2 Case) int {
952 return cmp.Compare(c1.Rune, c2.Rune)
953 })
954
955 fmt.Fprintln(w, `
956 // toUpperLowerSpecial returns the uppercase and lowercase form of r,
957 // which is a character that is not equal to either its uppercase or
958 // lowercase form and thus cannot be mapped into the _UpperLower table.
959 func toUpperLowerSpecial(r rune) (rune, rune, bool) {
960 switch r {`)
961 for _, c := range special {
962 fmt.Fprintf(w, "\tcase %q:\n", c.Rune)
963 fmt.Fprintf(w, "\t\treturn %q, %q, %t\n", c.Upper, c.Lower, true)
964 }
965 fmt.Fprintln(w, "\t}")
966 fmt.Fprintln(w, "\treturn r, r, false")
967 fmt.Fprintln(w, "}")
968 }
969
970 func writeInitGuard(w *bytes.Buffer) {
971 const s = `
972
973 func init() {
974 // This is essentially a compile time assertion that can only fail if a
975 // future Go release updates the version of Unicode it supports. This
976 // check is elided if the Unicode versions match.
977 //
978 // TLDR if you see this panic file an issue:
979 // https://github.com/charlievieth/strcase/issues
980 //
981 if UnicodeVersion != unicode.Version {
982 panic("strcase.UnicodeVersion \"" + UnicodeVersion +
983 "\" != unicode.Version \"" + unicode.Version + "\"")
984 }
985 }
986
987 `
988 w.WriteString(s)
989 }
990
991 func writeTypes(w *bytes.Buffer) {
992 const s = `
993
994 // A foldPair stores Unicode case folding pairs
995 type foldPair struct {
996 From uint32
997 To uint32
998 }
999
1000 `
1001 w.WriteString(s)
1002 }
1003
1004 func writeFunctions(w *bytes.Buffer) {
1005 const s = `
1006
1007 // TODO: rename to "foldCase"
1008 //
1009 // CaseFold returns the Unicode simple case-fold for r, if one exists, or r
1010 // unmodified, if one does not exist.
1011 func CaseFold(r rune) rune {
1012 // TODO: check if r is ASCII here?
1013 u := uint32(r)
1014 h := (u * _CaseFoldsSeed) >> _CaseFoldsShift
1015 p := _CaseFolds[h]
1016 if p.From == u {
1017 r = rune(p.To)
1018 }
1019 return r
1020 }
1021
1022 // TODO: rename
1023 func FoldMap(r rune) *[4]uint16 {
1024 u := uint32(r)
1025 h := (u * _FoldMapSeed) >> _FoldMapShift
1026 p := &_FoldMap[h]
1027 if uint32(p[0]) == u {
1028 return p
1029 }
1030 return nil
1031 }
1032
1033 func FoldMapExcludingUpperLower(r rune) [2]rune {
1034 u := uint32(r)
1035 h := (u * _FoldMapSeed) >> _FoldMapShift
1036 p := &_FoldMapExcludingUpperLower[h]
1037 if uint32(p.r) == u {
1038 return [2]rune{rune(p.a[0]), rune(p.a[1])}
1039 }
1040 return [2]rune{}
1041 }
1042
1043 // ToUpperLower combines unicode.ToUpper and unicode.ToLower in one function.
1044 func ToUpperLower(r rune) (upper, lower rune, foundMapping bool) {
1045 if r <= 0x80 {
1046 if 'A' <= r && r <= 'Z' {
1047 return r, r + ('a' - 'A'), true
1048 }
1049 if 'a' <= r && r <= 'z' {
1050 return r - ('a' - 'A'), r, true
1051 }
1052 return r, r, false
1053 }
1054 // Hash rune r and see if it's in the _UpperLower table.
1055 u := uint32(r)
1056 h := (u | u<<24) * _UpperLowerSeed
1057 p := &_UpperLower[h>>_UpperLowerShift]
1058 if p[0] == u || p[1] == u {
1059 return rune(p[0]), rune(p[1]), true
1060 }
1061 // Handle Unicode characters that do not equal
1062 // their upper and lower case forms.
1063 return toUpperLowerSpecial(r)
1064 }
1065
1066 `
1067 w.WriteString(s)
1068 }
1069
1070 func runCommand(dir string, args ...string) {
1071 cmd := exec.Command("go", args...)
1072 cmd.Dir = dir
1073 out, err := cmd.CombinedOutput()
1074 if err != nil {
1075 log.Printf("Error: %v", err)
1076 log.Printf("Command: %s", strings.Join(cmd.Args, " "))
1077 log.Printf("Output: %s", bytes.TrimSpace(out))
1078 log.Panicf("Failed to build generated file: %v\n", err)
1079 }
1080 }
1081
1082 func testBuild(tablesFile string, data []byte, skipTests bool) {
1083 dir, err := os.MkdirTemp("", "strcase.*")
1084 if err != nil {
1085 log.Panic(err)
1086 }
1087
1088 tables := filepath.Join(dir, filepath.Base(tablesFile))
1089 overlay := filepath.Join(dir, "overlay.json")
1090
1091 type overlayJSON struct {
1092 Replace map[string]string
1093 }
1094
1095 overlayData, err := json.Marshal(overlayJSON{
1096 Replace: map[string]string{
1097 // filepath.Base(tablesFile): tables,
1098 tablesFile: tables,
1099 },
1100 })
1101 if err != nil {
1102 log.Panic(err)
1103 }
1104
1105 if err := os.WriteFile(overlay, overlayData, 0644); err != nil {
1106 log.Panic(err)
1107 }
1108 if err := os.WriteFile(tables, data, 0644); err != nil {
1109 log.Panic(err)
1110 }
1111
1112 cmdDir := filepath.Dir(tablesFile)
1113 runCommand(cmdDir, "build", "-overlay="+overlay, "./...")
1114 if !skipTests {
1115 runCommand(cmdDir, "test", "-overlay="+overlay, "./...")
1116 }
1117
1118 os.RemoveAll(dir) // Only remove temp dir if successful
1119 }
1120
1121 func dataEqual(filename string, data []byte) bool {
1122 got, err := os.ReadFile(filename)
1123 return err == nil && bytes.Equal(got, data)
1124 }
1125
1126 func writeFile(name string, data []byte) {
1127 if dataEqual(name, data) {
1128 return
1129 }
1130
1131 f, err := os.CreateTemp(filepath.Dir(name), filepath.Base(name)+".tmp.*")
1132 if err != nil {
1133 log.Fatal(err)
1134 }
1135 tmp := f.Name()
1136 exit := func(err error) {
1137 os.Remove(tmp)
1138 log.Panic(err)
1139 }
1140 if _, err := f.Write(data); err != nil {
1141 exit(err)
1142 }
1143 if err := f.Chmod(0644); err != nil {
1144 exit(err)
1145 }
1146 if err := f.Close(); err != nil {
1147 exit(err)
1148 }
1149 if err := os.Rename(tmp, name); err != nil {
1150 exit(err)
1151 }
1152 }
1153
1154 func writeTemp(name string, b []byte) {
1155 dir, err := os.MkdirTemp("", "strcase.gen.*")
1156 if err != nil {
1157 log.Panic(err)
1158 }
1159 path := filepath.Join(dir, name)
1160 if err := os.WriteFile(path, b, 0644); err != nil {
1161 log.Panic(err)
1162 }
1163 log.Println("TMPFILE:", path)
1164 }
1165
1166 // TODO: use gen.CodeWriter
1167 //
1168 // writeGo formats the Go source in w and re-writes it back to w.
1169 func writeGo(w *bytes.Buffer, tablesFile, buildTags string) {
1170 data := make([]byte, w.Len())
1171 copy(data, w.Bytes())
1172 src, err := format.Source(data)
1173 if err != nil {
1174 writeTemp(tablesFile, data)
1175 log.Panic(err)
1176 }
1177 w.Reset()
1178 if _, err := gen.WriteGo(w, "tables", buildTags, src); err != nil {
1179 log.Fatal(err)
1180 }
1181 }
1182
1183 func hashCaseFolds() string {
1184 b := make([]byte, 0, 4096)
1185 for _, p := range caseFolds {
1186 b = binary.LittleEndian.AppendUint32(b, p.From)
1187 b = binary.LittleEndian.AppendUint32(b, p.To)
1188 }
1189 return fmt.Sprintf("%x", sha256.Sum256(b))
1190 }
1191
1192 type TableInfo struct {
1193 Filename string `json:"filename"`
1194 UnicodeVersion string `json:"unicode_version"`
1195 CLDRVersion string `json:"cldr_version"`
1196 CaseFoldHash string `json:"case_fold_hash"`
1197 GenGoHash string `json:"gen_go_hash"`
1198 TableHashes map[string]uint32 `json:"table_hashes"`
1199 }
1200
1201 var tableInfo = TableInfo{
1202 TableHashes: map[string]uint32{},
1203 }
1204
1205 func readTableInfo(root, tablesFile string) (map[string]TableInfo, error) {
1206 m := make(map[string]TableInfo)
1207 // The ".tables.json" file is adjacent to the generated tables file.
1208 data, err := os.ReadFile(filepath.Join(root, ".tables.json"))
1209 if err != nil {
1210 return m, err
1211 }
1212 if err := json.Unmarshal(data, &m); err != nil {
1213 return m, err
1214 }
1215 return m, nil
1216 }
1217
1218 // TODO: change this to use the Unicode version instead of the file name
1219 //
1220 // Note: loadTableInfo may be an absolute path.
1221 func loadTableInfo(root, tablesFile string) {
1222 m, err := readTableInfo(root, tablesFile)
1223 if err != nil {
1224 if os.IsNotExist(err) {
1225 return
1226 }
1227 log.Panic(err)
1228 }
1229 base := filepath.Base(tablesFile)
1230 tableInfo = m[base]
1231 // TODO: do we need this intermediary step ??
1232 if tableInfo.Filename == "" {
1233 tableInfo.Filename = base
1234 }
1235 if tableInfo.TableHashes == nil {
1236 tableInfo.TableHashes = make(map[string]uint32)
1237 }
1238 }
1239
1240 func updateTableInfoFile(root, tablesFile, fileHash, foldHash string) {
1241 base := filepath.Base(tablesFile)
1242
1243 tableInfo.Filename = base
1244 tableInfo.UnicodeVersion = gen.UnicodeVersion()
1245 tableInfo.CLDRVersion = gen.CLDRVersion()
1246 tableInfo.CaseFoldHash = foldHash
1247 tableInfo.GenGoHash = fileHash
1248
1249 m, err := readTableInfo(root, tablesFile)
1250 if err != nil && !os.IsNotExist(err) {
1251 log.Panic(err)
1252 }
1253 m[base] = tableInfo
1254
1255 data, err := json.MarshalIndent(m, "", " ")
1256 if err != nil {
1257 log.Panic(err)
1258 }
1259 writeFile(filepath.Join(root, ".tables.json"), data)
1260 }
1261
1262 func fileExists(name string) bool {
1263 _, err := os.Lstat(name)
1264 return err == nil
1265 }
1266
1267 var category = map[string]bool{
1268 // Nd Lu etc.
1269 // We use one-character names to identify merged categories
1270 "L": true, // Lu Ll Lt Lm Lo
1271 "P": true, // Pc Pd Ps Pe Pu Pf Po
1272 "M": true, // Mn Mc Me
1273 "N": true, // Nd Nl No
1274 "S": true, // Sm Sc Sk So
1275 "Z": true, // Zs Zl Zp
1276 "C": true, // Cc Cf Cs Co Cn
1277 // Multi-letter group categories added in go1.27.
1278 "LC": true, // Lu Ll Lt (Cased_Letter)
1279 "Cn": true, // Unassigned code points
1280 }
1281
1282 // This contains only the properties we're interested in.
1283 type Char struct {
1284 codePoint rune // if zero, this index is not a valid code point.
1285 category string
1286 upperCase rune
1287 lowerCase rune
1288 titleCase rune
1289 foldCase rune // simple case folding
1290 caseOrbit rune // next in simple case folding orbit
1291 }
1292
1293 func allCategories() []string {
1294 a := make([]string, 0, len(category))
1295 for k := range category {
1296 a = append(a, k)
1297 }
1298 sort.Strings(a)
1299 return a
1300 }
1301
1302 func allCatFold(m map[string]map[rune]bool) []string {
1303 a := make([]string, 0, len(m))
1304 for k := range m {
1305 a = append(a, k)
1306 }
1307 slices.Sort(a)
1308 return a
1309 }
1310
1311 // WARN WARN WARN: move this
1312 func loadChars() {
1313 ucd.Parse(gen.OpenUCDFile("UnicodeData.txt"), func(p *ucd.Parser) {
1314 c := Char{codePoint: p.Rune(0)}
1315
1316 getRune := func(field int) rune {
1317 if p.String(field) == "" {
1318 return 0
1319 }
1320 return p.Rune(field)
1321 }
1322
1323 c.category = p.String(ucd.GeneralCategory)
1324 category[c.category] = true
1325 switch c.category {
1326 case "Nd":
1327 // Decimal digit
1328 p.Int(ucd.NumericValue)
1329 case "Lu":
1330 c.upperCase = getRune(ucd.CodePoint)
1331 c.lowerCase = getRune(ucd.SimpleLowercaseMapping)
1332 c.titleCase = getRune(ucd.SimpleTitlecaseMapping)
1333 case "Ll":
1334 c.upperCase = getRune(ucd.SimpleUppercaseMapping)
1335 c.lowerCase = getRune(ucd.CodePoint)
1336 c.titleCase = getRune(ucd.SimpleTitlecaseMapping)
1337 case "Lt":
1338 c.upperCase = getRune(ucd.SimpleUppercaseMapping)
1339 c.lowerCase = getRune(ucd.SimpleLowercaseMapping)
1340 c.titleCase = getRune(ucd.CodePoint)
1341 default:
1342 c.upperCase = getRune(ucd.SimpleUppercaseMapping)
1343 c.lowerCase = getRune(ucd.SimpleLowercaseMapping)
1344 c.titleCase = getRune(ucd.SimpleTitlecaseMapping)
1345 }
1346
1347 chars[c.codePoint] = c
1348 })
1349 }
1350
1351 // WARN: rename and fix other loadCategories()
1352 func loadCategoryTables() map[string]*unicode.RangeTable {
1353 categoryOp := func(code rune, class uint8) bool {
1354 category := chars[code].category
1355 return len(category) > 0 && category[0] == class
1356 }
1357
1358 list := allCategories()
1359 cats := make(map[string]*unicode.RangeTable, len(list))
1360
1361 // Avoid calculating these tables if possible
1362 if gen.UnicodeVersion() == unicode.Version {
1363 for _, name := range list {
1364 if _, ok := unicode.Categories[name]; !ok {
1365 log.Fatal("unknown category", name)
1366 }
1367 cats[name] = unicode.Categories[name]
1368 }
1369 return cats
1370 }
1371
1372 for _, name := range list {
1373 if _, ok := category[name]; !ok {
1374 log.Fatal("unknown category", name)
1375 }
1376 // Previously, we only distinguished between "unified" and all other
1377 // categories. Since go1.27, we need to also handle the "LC" (cased
1378 // letter) and "Cn" (unassigned) categories. This code does that.
1379 var rt *unicode.RangeTable
1380 switch {
1381 case name == "LC": // cased letter
1382 rt = dumpRange(func(code rune) bool {
1383 switch chars[code].category {
1384 case "Lu", "Ll", "Lt":
1385 return true
1386 }
1387 return false
1388 })
1389 case name == "Cn": // unassigned: no general category
1390 rt = dumpRange(func(code rune) bool { return chars[code].category == "" })
1391 case len(name) == 1: // unified categories
1392 rt = dumpRange(func(code rune) bool { return categoryOp(code, name[0]) })
1393 default:
1394 rt = dumpRange(func(code rune) bool { return chars[code].category == name })
1395 }
1396 cats[name] = rt
1397 }
1398 return cats
1399 }
1400
1401 type Op func(code rune) bool
1402
1403 // TODO: rename
1404 func dumpRange(inCategory Op) *unicode.RangeTable {
1405 runes := []rune{}
1406 for i := range chars {
1407 r := rune(i)
1408 if inCategory(r) {
1409 runes = append(runes, r)
1410 }
1411 }
1412 return rangetable.New(runes...)
1413 }
1414
1415 // PropList.txt has the same format as Scripts.txt so we can share its parser.
1416 func loadScriptOrProperty(doProps bool) map[string]*unicode.RangeTable {
1417 if gen.UnicodeVersion() == unicode.Version {
1418 if doProps {
1419 return unicode.Properties
1420 }
1421 return unicode.Scripts
1422 }
1423
1424 file := "Scripts.txt"
1425 table := scripts
1426 if doProps {
1427 file = "PropList.txt"
1428 table = props
1429 }
1430 ucd.Parse(gen.OpenUCDFile(file), func(p *ucd.Parser) {
1431 name := p.String(1)
1432 table[name] = append(table[name], p.Rune(0))
1433 })
1434
1435 // Handle deprecated "STerm" alias (this is only needed for tests)
1436 if rt, ok := table["Sentence_Terminal"]; ok {
1437 table["STerm"] = rt
1438 }
1439 tab := make(map[string]*unicode.RangeTable, len(table))
1440 for name, runes := range table {
1441 tab[name] = rangetable.New(runes...)
1442 }
1443 return tab
1444 }
1445
1446 func loadCasefold() (foldCategory, foldScript map[string]*unicode.RangeTable) {
1447 // Build list of case-folding groups attached to each canonical folded char (typically lower case).
1448 var caseOrbit = make([][]rune, MaxChar+1)
1449 for j := range chars {
1450 i := rune(j)
1451 c := &chars[i]
1452 if c.foldCase == 0 {
1453 continue
1454 }
1455 orb := caseOrbit[c.foldCase]
1456 if orb == nil {
1457 orb = append(orb, c.foldCase)
1458 }
1459 caseOrbit[c.foldCase] = append(orb, i)
1460 }
1461
1462 // Insert explicit 1-element groups when assuming [lower, upper] would be wrong.
1463 for j := range chars {
1464 i := rune(j)
1465 c := &chars[i]
1466 f := c.foldCase
1467 if f == 0 {
1468 f = i
1469 }
1470 orb := caseOrbit[f]
1471 if orb == nil && (c.upperCase != 0 && c.upperCase != i || c.lowerCase != 0 && c.lowerCase != i) {
1472 // Default assumption of [upper, lower] is wrong.
1473 caseOrbit[i] = []rune{i}
1474 }
1475 }
1476
1477 // Delete the groups for which assuming [lower, upper] or [upper, lower] is right.
1478 for i, orb := range caseOrbit {
1479 if len(orb) == 2 && chars[orb[0]].upperCase == orb[1] && chars[orb[1]].lowerCase == orb[0] {
1480 caseOrbit[i] = nil
1481 }
1482 if len(orb) == 2 && chars[orb[1]].upperCase == orb[0] && chars[orb[0]].lowerCase == orb[1] {
1483 caseOrbit[i] = nil
1484 }
1485 }
1486
1487 // Record orbit information in chars.
1488 for _, orb := range caseOrbit {
1489 if orb == nil {
1490 continue
1491 }
1492 sort.Slice(orb, func(i, j int) bool {
1493 return orb[i] < orb[j]
1494 })
1495 c := orb[len(orb)-1]
1496 for _, d := range orb {
1497 chars[c].caseOrbit = d
1498 c = d
1499 }
1500 }
1501
1502 loadAsciiFold()
1503 loadCaseOrbit()
1504
1505 // Fast exit if we don't need to recalculate these tables.
1506 if gen.UnicodeVersion() == unicode.Version {
1507 return unicode.FoldCategory, unicode.FoldScript
1508 }
1509
1510 // Tables of category and script folding exceptions: code points
1511 // that must be added when interpreting a particular category/script
1512 // in a case-folding context.
1513 cat := make(map[string]map[rune]bool)
1514 for name := range category {
1515 if x := foldExceptions(inCategory(name)); len(x) > 0 {
1516 cat[name] = x
1517 }
1518 }
1519
1520 scr := make(map[string]map[rune]bool)
1521 for name := range scripts {
1522 if x := foldExceptions(scripts[name]); len(x) > 0 {
1523 scr[name] = x
1524 }
1525 }
1526
1527 return loadCatFold(cat), loadCatFold(scr) // TODO: this takes ~60ms
1528 }
1529
1530 func loadAsciiFold() {
1531 for i := rune(0); i <= unicode.MaxASCII; i++ {
1532 c := chars[i]
1533 f := c.caseOrbit
1534 if f == 0 {
1535 switch {
1536 case c.lowerCase != i && c.lowerCase != 0:
1537 f = c.lowerCase
1538 case c.upperCase != i && c.upperCase != 0:
1539 f = c.upperCase
1540 default:
1541 f = i
1542 }
1543 }
1544 asciiFold[i] = uint16(f)
1545 }
1546 }
1547
1548 // TODO: rename
1549 func loadCaseOrbit() {
1550 for i := range chars {
1551 c := &chars[i]
1552 if c.caseOrbit != 0 {
1553 caseOrbit = append(caseOrbit, foldPair{uint32(i), uint32(c.caseOrbit)})
1554 }
1555 }
1556 }
1557
1558 // inCategory returns a list of all the runes in the category.
1559 func inCategory(name string) []rune {
1560 var x []rune
1561 for j := range chars {
1562 i := rune(j)
1563 c := &chars[i]
1564 if c.category == name || len(name) == 1 && len(c.category) > 1 && c.category[0] == name[0] {
1565 x = append(x, i)
1566 }
1567 }
1568 // fmt.Printf("%s: %d\n", name, len(x))
1569 return x
1570 }
1571
1572 // foldExceptions returns a list of all the runes fold-equivalent
1573 // to runes in class but not in class themselves.
1574 func foldExceptions(class []rune) map[rune]bool {
1575 // Create map containing class and all fold-equivalent chars.
1576 m := make(map[rune]bool)
1577 for _, r := range class {
1578 c := &chars[r]
1579 if c.caseOrbit == 0 {
1580 // Just upper and lower.
1581 if u := c.upperCase; u != 0 {
1582 m[u] = true
1583 }
1584 if l := c.lowerCase; l != 0 {
1585 m[l] = true
1586 }
1587 m[r] = true
1588 continue
1589 }
1590 // Otherwise walk orbit.
1591 r0 := r
1592 for {
1593 m[r] = true
1594 r = chars[r].caseOrbit
1595 if r == r0 {
1596 break
1597 }
1598 }
1599 }
1600
1601 // Remove class itself.
1602 for _, r := range class {
1603 delete(m, r)
1604 }
1605
1606 // What's left is the exceptions.
1607 return m
1608 }
1609
1610 func loadCatFold(m map[string]map[rune]bool) map[string]*unicode.RangeTable {
1611 folds := allCatFold(m)
1612 tabs := make(map[string]*unicode.RangeTable, len(folds))
1613 for _, name := range folds {
1614 class := m[name]
1615 tabs[name] = dumpRange(func(code rune) bool { return class[code] })
1616 }
1617 return tabs
1618 }
1619
1620 // TODO: move to the top
1621 func initTables(root, tablesFile string) {
1622 loadTableInfo(root, tablesFile)
1623 loadChars()
1624 loadCaseFolds() // download Unicode tables
1625 foldCategories, foldScripts := loadCasefold() // TODO: this is slow (~200ms)
1626
1627 cats := []map[string]*unicode.RangeTable{
1628 loadCategoryTables(),
1629 loadScriptOrProperty(false),
1630 loadScriptOrProperty(true),
1631 foldCategories,
1632 foldScripts,
1633 }
1634
1635 tabs := make([]*unicode.RangeTable, 0, len(cats))
1636 for _, m := range cats {
1637 for _, rt := range m {
1638 tabs = append(tabs, rt)
1639 }
1640 }
1641 categories = rangetable.Merge(tabs...)
1642
1643 caseRanges = generateCaseRanges()
1644 }
1645
1646 func requireFlags(names ...string) {
1647 var missing []string
1648 for _, name := range names {
1649 if flag.Lookup(name) == nil {
1650 missing = append(missing, name)
1651 }
1652 }
1653 if len(missing) > 0 {
1654 log.Panicf("The following flags were not registered: %q", missing)
1655 }
1656 }
1657
1658 func listSourceFiles(dir string) []string {
1659 match := func(name string) bool {
1660 if name == "go.mod" || name == "go.sum" {
1661 return true
1662 }
1663 if strings.HasSuffix(name, "_test.go") {
1664 return false
1665 }
1666 switch filepath.Ext(name) {
1667 case ".go", ".c", ".cc", ".cpp", ".cxx", ".f", ".F", ".f90", ".for",
1668 ".h", ".hh", ".hpp", ".hxx", ".m", ".s", ".S", ".swig", ".swigcxx",
1669 ".sx", ".syso":
1670 return true
1671 }
1672 return false
1673 }
1674 var a []string
1675 err := filepath.WalkDir(dir, func(path string, d fs.DirEntry, err error) error {
1676 name := d.Name()
1677 if d.IsDir() && (name == "vendor" || name[0] == '.') {
1678 return fs.SkipDir
1679 }
1680 if match(name) {
1681 a = append(a, path)
1682 }
1683 return nil
1684 })
1685 if err != nil {
1686 log.Fatal(err)
1687 }
1688 slices.Sort(a)
1689 return a
1690 }
1691
1692 func hashGenFiles() string {
1693 root, err := util.GenTablesRoot()
1694 if err != nil {
1695 log.Fatal(err)
1696 }
1697
1698 files := listSourceFiles(root)
1699 if len(files) == 0 {
1700 log.Fatal("no go source files in:", root)
1701 }
1702
1703 h := sha256.New()
1704 for _, name := range files {
1705 fmt.Fprintf(h, "%s\x00", filepath.Base(name))
1706 data, err := os.ReadFile(name)
1707 if err != nil {
1708 log.Fatal(err)
1709 }
1710 _, _ = h.Write(data)
1711 _, _ = h.Write([]byte{'\x00', '\x00'})
1712 }
1713
1714 return fmt.Sprintf("%x", h.Sum(nil))
1715 }
1716
1717 var useCachedSeeds = flag.Bool("cache", false,
1718 "used cached seeds instead of regenerating (for testing only)")
1719
1720 func realMain() int {
1721 initLogs() // Other packages configure logs on init so do it again here
1722
1723 root, err := util.ProjectRoot()
1724 if err != nil {
1725 log.Panic(err)
1726 }
1727
1728 flag.Usage = func() {
1729 flag.CommandLine.SetOutput(os.Stdout) // Write help to STDOUT
1730 fmt.Fprintf(flag.CommandLine.Output(), "Usage: %s [OPTION]...\n",
1731 filepath.Base(os.Args[0]))
1732 flag.PrintDefaults()
1733 }
1734
1735 // NB(charlie): the "-url", "-iana", "-unicode", and "-cldr" flags are
1736 // registered by the github.com/charlievieth/strcase/internal/gen/gen package.
1737 requireFlags("url", "iana", "unicode", "cldr")
1738
1739 skipTests := flag.Bool("skip-tests", false, "skip running tests")
1740 skipBuild := flag.Bool("skip-build", false, "skip building the strcase package (testing only)")
1741 dryRun := flag.Bool("dry-run", false,
1742 "report if generate would change the generated tables file and exit non-zero")
1743 // TODO: remove `-update-gen-hash` since it's dangerous and bypasses
1744 // our checks.
1745 updateGenHash := flag.Bool("update-gen-hash", false,
1746 `only update the hash of the gen.go file stored in ".tables.go" `+
1747 `(WARN: this is only for development)`)
1748 cpuprofile := flag.String("cpuprofile", "",
1749 "write cpu profile to `file`\n"+
1750 "NOTE: this traps SIGINT.\n"+
1751 " First SIGINT the cpu profile is written to 'file'.\n"+
1752 " Second SIGINT the program aborts.")
1753
1754 firstValidHash := flag.Bool("first-valid-hash", false,
1755 "use the first valid hash instead of performing an exhaustive search (testing only, much faster)")
1756
1757 outputDir := flag.String("dir", filepath.Join(root, "internal", "tables"),
1758 "write generated tables to this directory")
1759 // outputDir := flag.String("dir", filepath.Join(root),
1760 // "write generated tables to this directory")
1761
1762 flag.Parse()
1763
1764 if flag.NArg() != 0 {
1765 flag.Usage()
1766 return 1
1767 }
1768
1769 // Validate Unicode version flag
1770
1771 var supportedVersions []string
1772 for v := range buildTags {
1773 supportedVersions = append(supportedVersions, v)
1774 }
1775 if _, ok := buildTags[gen.UnicodeVersion()]; !ok {
1776 slices.Sort(supportedVersions)
1777 log.Printf("The selected Unicode version %q is unsupported. Either the version\n"+
1778 "is incorrect or this code needs to updated to handle a new version of Go.\n"+
1779 "The supported Unicode versions are: %q.", gen.UnicodeVersion(), supportedVersions)
1780 return 1
1781 }
1782
1783 tablesFile := tablesFileName(*outputDir)
1784 // Use the Unicode version as the log prefix since we invoke this program
1785 // multiple times with different versions.
1786 log.SetPrefix("(" + gen.UnicodeVersion() + ") ")
1787
1788 log.Println("Tables file:", tablesFile)
1789
1790 if *cpuprofile != "" {
1791 f, err := os.Create(*cpuprofile)
1792 if err != nil {
1793 log.Fatal("could not create CPU profile: ", err)
1794 }
1795 if err := pprof.StartCPUProfile(f); err != nil {
1796 log.Fatal("could not start CPU profile: ", err)
1797 }
1798 defer pprof.StopCPUProfile()
1799 ch := make(chan os.Signal, 1)
1800 signal.Notify(ch, os.Interrupt)
1801 go func() {
1802 <-ch
1803 log.Println("writing CPU profile: next interrupt will stop the program")
1804 pprof.StopCPUProfile()
1805 if err := f.Close(); err != nil {
1806 log.Printf("error closing CPU profile: %v", err)
1807 }
1808 signal.Reset(os.Interrupt)
1809 }()
1810 }
1811
1812 if !*updateGenHash && *outputDir != "." {
1813 if err := os.MkdirAll(*outputDir, 0755); err != nil {
1814 log.Println("error:", err)
1815 return 1
1816 }
1817 }
1818
1819 buildTags := buildTags[gen.UnicodeVersion()].buildTags
1820 if buildTags == "" {
1821 log.Printf("missing build tags for unicode version: %q", gen.UnicodeVersion())
1822 return 1
1823 }
1824
1825 initTables(root, tablesFile)
1826 fileHash := hashGenFiles() // hash gentables source files
1827 foldHash := hashCaseFolds()
1828
1829 chop := func(s string, n int) string {
1830 if len(s) >= n {
1831 return s[:n]
1832 }
1833 return s
1834 }
1835
1836 if fileExists(tablesFile) &&
1837 gen.UnicodeVersion() == tableInfo.UnicodeVersion &&
1838 gen.CLDRVersion() == tableInfo.CLDRVersion &&
1839 foldHash == tableInfo.CaseFoldHash &&
1840 fileHash == tableInfo.GenGoHash {
1841
1842 log.Printf("gen: exiting - no changes:\n"+
1843 " unicode_version: %q\n"+
1844 " cldr_version: %q\n"+
1845 " case_fold_hash: %q\n"+
1846 " gen_go_hash: %q\n",
1847 tableInfo.UnicodeVersion, tableInfo.CLDRVersion,
1848 chop(tableInfo.CaseFoldHash, 8), chop(tableInfo.GenGoHash, 8))
1849 return 0
1850 }
1851
1852 isTerm := term.IsTerminal(1)
1853 ansi := func(color int, s string) string {
1854 if !isTerm {
1855 return s
1856 }
1857 return fmt.Sprintf("\x1b[%d;m%s\x1b[0;m", color, s)
1858 }
1859 colorize := func(args ...string) []any {
1860 if len(args)&1 != 0 {
1861 log.Panicf("number of args (%d) must be even!", len(args))
1862 }
1863 // Quote args since we can't use '%q' in log.Printf
1864 for i, s := range args {
1865 args[i] = strconv.Quote(s)
1866 }
1867 // Colorize args that have changed if output is a terminal
1868 if isTerm {
1869 for i := 0; i < len(args); i += 2 {
1870 if args[i] != args[i+1] {
1871 args[i] = ansi(32, args[i]) // green
1872 args[i+1] = ansi(31, args[i+1]) // red
1873 }
1874 }
1875 }
1876 a := make([]any, len(args))
1877 for i, s := range args {
1878 a[i] = s
1879 }
1880 return a
1881 }
1882
1883 // TODO: print a relative path
1884 log.Printf("gen: would update "+tablesFile+" due to the following changes:\n"+
1885 " unicode_version: %s => %s\n"+
1886 " cldr_version: %s => %s\n"+
1887 " case_fold_hash: %s => %s\n"+
1888 " gen_go_hash: %s => %s\n\n",
1889 colorize(tableInfo.UnicodeVersion, gen.UnicodeVersion(),
1890 tableInfo.CLDRVersion, gen.CLDRVersion(),
1891 chop(tableInfo.CaseFoldHash, 8), chop(foldHash, 8),
1892 chop(tableInfo.GenGoHash, 8), chop(fileHash, 8))...)
1893 if *dryRun {
1894 log.Printf("%s gen: would change %s "+
1895 "(remove -dry-run flag to update the generated files)\n",
1896 tablesFile, ansi(33, "WARN:"))
1897 log.Printf("%s gen: exiting now\n", ansi(33, "WARN:"))
1898
1899 return 1
1900 }
1901
1902 // NB: can't test or build if the Unicode version does not match
1903 // the version used by the Go binary running this.
1904 if !*updateGenHash {
1905 var w bytes.Buffer
1906
1907 w.WriteString("\n\nimport \"unicode\"\n\n")
1908 gen.WriteUnicodeVersion(&w)
1909
1910 writeInitGuard(&w)
1911 writeTypes(&w)
1912 writeFunctions(&w)
1913
1914 genCaseFolds(&w, *firstValidHash)
1915 genUpperLowerTable(&w, *firstValidHash)
1916 genFoldTable(&w, *firstValidHash)
1917
1918 writeGo(&w, tablesFile, buildTags)
1919 if *skipBuild {
1920 log.Println("gen: skipping go build")
1921 } else {
1922 if gen.UnicodeVersion() != unicode.Version {
1923 log.Printf("gen: \"go build\" is ineffective because the generated file "+
1924 "will be excluded due to Unicode version: %q != %q",
1925 tableInfo.UnicodeVersion, unicode.Version)
1926 }
1927 testBuild(tablesFile, w.Bytes(), *skipTests)
1928 }
1929
1930 // For dry runs only report if tables.go would be changed and
1931 // exit with an error if so.
1932 if *dryRun {
1933 // TODO: this might be unreachable
1934 if !dataEqual(tablesFile, w.Bytes()) {
1935 fmt.Printf("gen: would change %s", tablesFile)
1936 return 1
1937 }
1938 return 0
1939 }
1940
1941 writeFile(tablesFile, w.Bytes())
1942 }
1943
1944 updateTableInfoFile(root, tablesFile, fileHash, foldHash)
1945 log.Printf("Successfully generated tables:\n"+
1946 " unicode_version: %q\n"+
1947 " cldr_version: %q\n"+
1948 " case_fold_hash: %q\n"+
1949 " gen_go_hash: %q\n",
1950 tableInfo.UnicodeVersion, tableInfo.CLDRVersion,
1951 chop(tableInfo.CaseFoldHash, 8), chop(tableInfo.GenGoHash, 8))
1952
1953 // Exit 1 if we only update the hash of the generate files since this
1954 // is a development only flag.
1955 if *updateGenHash {
1956 return 1
1957 }
1958 return 0
1959 }
1960
1961 func main() {
1962 if code := realMain(); code != 0 {
1963 os.Exit(code)
1964 }
1965 }