1 // Copyright 2012 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.
5 package main // import "golang.org/x/text/collate/tools/colcmp"
21 "golang.org/x/text/unicode/norm"
25 doNorm = flag.Bool("norm", false, "normalize input strings")
26 cases = flag.Bool("case", false, "generate case variants")
27 verbose = flag.Bool("verbose", false, "print results")
28 debug = flag.Bool("debug", false, "output debug information")
29 locales = flag.String("locale", "en_US", "the locale to use. May be a comma-separated list for some commands.")
30 col = flag.String("col", "go", "collator to test")
31 gold = flag.String("gold", "go", "collator used as the gold standard")
32 usecmp = flag.Bool("usecmp", false,
33 `use comparison instead of sort keys when sorting. Must be "test", "gold" or "both"`)
34 cpuprofile = flag.String("cpuprofile", "", "write cpu profile to file")
35 exclude = flag.String("exclude", "", "exclude errors that contain any of the characters")
36 limit = flag.Int("limit", 5000000, "maximum number of samples to generate for one run")
39 func failOnError(err error) {
45 // Test holds test data for testing a locale-collator pair.
46 // Test also provides functionality that is commonly used by the various commands.
57 Duration time.Duration
64 func (t *Test) clear() {
70 msgGeneratingInput = "generating input"
71 msgGeneratingKeys = "generating keys"
72 msgSorting = "sorting"
77 func (t *Test) SetStatus(msg string) {
78 if *debug || *verbose {
79 fmt.Printf("%s: %s...\n", t.Name, msg)
80 } else if t.ctxt.out != nil {
81 fmt.Fprint(t.ctxt.out, strings.Repeat(" ", lastLen))
82 fmt.Fprint(t.ctxt.out, strings.Repeat("\b", lastLen))
83 fmt.Fprint(t.ctxt.out, msg, "...")
84 lastLen = len(msg) + 3
85 fmt.Fprint(t.ctxt.out, strings.Repeat("\b", lastLen))
89 // Start is used by commands to signal the start of an operation.
90 func (t *Test) Start(msg string) {
97 // Stop is used by commands to signal the end of an operation.
98 func (t *Test) Stop() (time.Duration, int) {
99 d := time.Now().Sub(t.start)
101 if *debug || *verbose {
102 fmt.Printf("%s: %s done. (%.3fs /%dK ops)\n", t.Name, t.msg, d.Seconds(), t.count/1000)
107 // generateKeys generates sort keys for all the inputs.
108 func (t *Test) generateKeys() {
109 for i, s := range t.Input {
113 fmt.Printf("%s (%X): %X\n", string(s.UTF8), s.UTF16, b)
118 // Sort sorts the inputs. It generates sort keys if this is required by the
119 // chosen sort method.
120 func (t *Test) Sort() (tkey, tsort time.Duration, nkey, nsort int) {
121 if *cpuprofile != "" {
122 f, err := os.Create(*cpuprofile)
124 pprof.StartCPUProfile(f)
125 defer pprof.StopCPUProfile()
127 if t.UseCompare || t.Col.Key(t.Input[0]) == nil {
129 sort.Sort(&testCompare{*t})
130 tsort, nsort = t.Stop()
132 t.Start(msgGeneratingKeys)
134 t.count = len(t.Input)
135 tkey, nkey = t.Stop()
138 tsort, nsort = t.Stop()
143 func (t *Test) Swap(a, b int) {
144 t.Input[a], t.Input[b] = t.Input[b], t.Input[a]
147 func (t *Test) Less(a, b int) bool {
149 return bytes.Compare(t.Input[a].key, t.Input[b].key) == -1
152 func (t Test) Len() int {
156 type testCompare struct {
160 func (t *testCompare) Less(a, b int) bool {
162 return t.Col.Compare(t.Input[a], t.Input[b]) == -1
165 type testRestore struct {
169 func (t *testRestore) Less(a, b int) bool {
170 return t.Input[a].index < t.Input[b].index
173 // GenerateInput generates input phrases for the locale tested by t.
174 func (t *Test) GenerateInput() {
176 if t.ctxt.lastLocale != t.Locale {
177 gen := phraseGenerator{}
179 t.SetStatus(msgGeneratingInput)
180 t.ctxt.lastInput = nil // allow the previous value to be garbage collected.
181 t.Input = gen.generate(*doNorm)
182 t.ctxt.lastInput = t.Input
183 t.ctxt.lastLocale = t.Locale
185 t.Input = t.ctxt.lastInput
186 for i := range t.Input {
189 sort.Sort(&testRestore{*t})
193 // Context holds all tests and settings translated from command line options.
194 type Context struct {
204 func (ts *Context) Printf(format string, a ...interface{}) {
206 fmt.Fprintf(ts.out, format, a...)
209 func (ts *Context) Print(a ...interface{}) {
211 fmt.Fprint(ts.out, a...)
214 // assertBuf sets up an io.Writer for output, if it doesn't already exist.
215 // In debug and verbose mode, output is buffered so that the regular output
216 // will not interfere with the additional output. Otherwise, output is
217 // written directly to stdout for a more responsive feel.
218 func (ts *Context) assertBuf() {
222 if *debug || *verbose {
223 ts.out = &bytes.Buffer{}
229 // flush flushes the contents of ts.out to stdout, if it is not stdout already.
230 func (ts *Context) flush() {
232 if _, ok := ts.out.(io.ReadCloser); !ok {
233 io.Copy(os.Stdout, ts.out.(io.Reader))
238 // parseTests creates all tests from command lines and returns
239 // a Context to hold them.
240 func parseTests() *Context {
242 colls := strings.Split(*col, ",")
243 for _, loc := range strings.Split(*locales, ",") {
244 loc = strings.TrimSpace(loc)
245 for _, name := range colls {
246 name = strings.TrimSpace(name)
247 col := getCollator(name, loc)
248 ctxt.test = append(ctxt.test, &Test{
260 func (c *Context) Len() int {
264 func (c *Context) Test(i int) *Test {
272 func parseInput(args []string) []Input {
274 for _, s := range args {
278 r, _, s, _ = strconv.UnquoteChar(s, '\'')
283 s = norm.NFD.String(s)
285 input = append(input, makeInputString(s))
290 // A Command is an implementation of a colcmp command.
291 type Command struct {
292 Run func(cmd *Context, args []string)
298 func (cmd Command) Name() string {
299 return strings.SplitN(cmd.Usage, " ", 2)[0]
302 var commands = []*Command{
309 Sort sorts a given list of strings. Strings are separated by whitespace.
312 var cmdSort = &Command{
314 Usage: "sort <string>*",
315 Short: "sort a given list of strings",
319 func runSort(ctxt *Context, args []string) {
320 input := parseInput(args)
322 log.Fatalf("Nothing to sort.")
325 ctxt.Print("COLL LOCALE RESULT\n")
327 for i := 0; i < ctxt.Len(); i++ {
329 t.Input = append(t.Input, input...)
332 ctxt.Printf("%-5s %-5s ", t.ColName, t.Locale)
334 for _, s := range t.Input {
335 ctxt.Print(string(s.UTF8), " ")
342 Bench runs a benchmark for the given list of collator implementations.
343 If no collator implementations are given, the go collator will be used.
346 var cmdBench = &Command{
349 Short: "benchmark a given list of collator implementations",
353 func runBench(ctxt *Context, args []string) {
354 ctxt.Printf("%-7s %-5s %-6s %-24s %-24s %-5s %s\n", "LOCALE", "COLL", "N", "KEYS", "SORT", "AVGLN", "TOTAL")
355 for i := 0; i < ctxt.Len(); i++ {
357 ctxt.Printf("%-7s %-5s ", t.Locale, t.ColName)
359 ctxt.Printf("%-6s ", fmt.Sprintf("%dK", t.Len()/1000))
360 tkey, tsort, nkey, nsort := t.Sort()
361 p := func(dur time.Duration, n int) {
364 s = fmt.Sprintf("%6.3fs ", dur.Seconds())
366 s += fmt.Sprintf("%15s", fmt.Sprintf("(%4.2f ns/op)", float64(dur)/float64(n)))
369 ctxt.Printf("%-24s ", s)
375 for _, s := range t.Input {
378 ctxt.Printf("%-5d ", total/t.Len())
379 ctxt.Printf("%6.3fs\n", t.Duration.Seconds())
381 for _, s := range t.Input {
382 fmt.Print(string(s.UTF8), " ")
389 const regressHelp = `
390 Regress runs a monkey test by comparing the results of randomly generated tests
391 between two implementations of a collator. The user may optionally pass a list
392 of strings to regress against instead of the default test set.
395 var cmdRegress = &Command{
397 Usage: "regress -gold=<col> -test=<col> [string]*",
398 Short: "run a monkey test between two collators",
402 const failedKeyCompare = `
403 %s:%d: incorrect comparison result for input:
408 Compare(a, b) = %d; want %d.
415 const failedCompare = `
416 %s:%d: incorrect comparison result for input:
419 Compare(a, b) = %d; want %d.
422 func keyStr(b []byte) string {
423 buf := &bytes.Buffer{}
424 for _, v := range b {
425 fmt.Fprintf(buf, "%.2X ", v)
430 func runRegress(ctxt *Context, args []string) {
431 input := parseInput(args)
432 for i := 0; i < ctxt.Len(); i++ {
435 t.Input = append(t.Input, input...)
441 gold := getCollator(*gold, t.Locale)
442 for i := 1; i < len(t.Input); i++ {
445 if bytes.IndexAny(ib.UTF8, *exclude) != -1 {
449 if bytes.IndexAny(ia.UTF8, *exclude) != -1 {
452 goldCmp := gold.Compare(ia, ib)
453 if cmp := bytes.Compare(ia.key, ib.key); cmp != goldCmp {
457 fmt.Printf(failedKeyCompare, t.Locale, i-1, a, []rune(a), keyStr(ia.key), b, []rune(b), keyStr(ib.key), cmp, goldCmp, keyStr(gold.Key(ia)), keyStr(gold.Key(ib)))
458 } else if cmp := t.Col.Compare(ia, ib); cmp != goldCmp {
462 fmt.Printf(failedCompare, t.Locale, i-1, a, []rune(a), b, []rune(b), cmp, goldCmp)
466 ctxt.Printf("Found %d inconsistencies in %d entries.\n", count, t.Len()-1)
471 const helpTemplate = `
472 colcmp is a tool for testing and benchmarking collation
474 Usage: colcmp command [arguments]
478 {{.Name | printf "%-11s"}} {{.Short}}{{end}}
480 Use "col help [topic]" for more information about that topic.
483 const detailedHelpTemplate = `
484 Usage: colcmp {{.Usage}}
489 func runHelp(args []string) {
490 t := template.New("help")
491 t.Funcs(template.FuncMap{"trim": strings.TrimSpace})
493 template.Must(t.Parse(helpTemplate))
494 failOnError(t.Execute(os.Stderr, &commands))
496 for _, cmd := range commands {
497 if cmd.Name() == args[0] {
498 template.Must(t.Parse(detailedHelpTemplate))
499 failOnError(t.Execute(os.Stderr, cmd))
503 log.Fatalf("Unknown command %q. Run 'colcmp help'.", args[0])
517 args := flag.Args()[1:]
518 if flag.Arg(0) == "help" {
521 for _, cmd := range commands {
522 if cmd.Name() == flag.Arg(0) {