github.com/panjjo/go@v0.0.0-20161104043856-d62b31386338/src/cmd/compile/fmt_test.go (about) 1 // Copyright 2016 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 5 // This file implements TestFormats; a test that verifies 6 // format strings in the compiler (this directory and all 7 // subdirectories, recursively). 8 // 9 // TestFormats finds potential (Printf, etc.) format strings. 10 // If they are used in a call, the format verbs are verified 11 // based on the matching argument type against a precomputed 12 // table of valid formats. The knownFormats table can be used 13 // to automatically rewrite format strings with the -u flag. 14 // 15 // A new knownFormats table based on the found formats is printed 16 // when the test is run in verbose mode (-v flag). The table 17 // needs to be updated whenever a new (type, format) combination 18 // is found and the format verb is not 'v' or 'T' (as in "%v" or 19 // "%T"). 20 // 21 // Run as: go test -run Formats [-u][-v] 22 // 23 // Known bugs: 24 // - indexed format strings ("%[2]s", etc.) are not supported 25 // (the test will fail) 26 // - format strings that are not simple string literals cannot 27 // be updated automatically 28 // (the test will fail with respective warnings) 29 // - format strings in _test packages outside the current 30 // package are not processed 31 // (the test will report those files) 32 // 33 package main_test 34 35 import ( 36 "bytes" 37 "flag" 38 "fmt" 39 "go/ast" 40 "go/build" 41 "go/constant" 42 "go/format" 43 "go/importer" 44 "go/parser" 45 "go/token" 46 "go/types" 47 "internal/testenv" 48 "io/ioutil" 49 "log" 50 "os" 51 "path/filepath" 52 "sort" 53 "strconv" 54 "strings" 55 "testing" 56 "unicode/utf8" 57 ) 58 59 var update = flag.Bool("u", false, "update format strings") 60 61 // The following variables collect information across all processed files. 62 var ( 63 fset = token.NewFileSet() 64 formatStrings = make(map[*ast.BasicLit]bool) // set of all potential format strings found 65 foundFormats = make(map[string]bool) // set of all formats found 66 callSites = make(map[*ast.CallExpr]*callSite) // map of all calls 67 ) 68 69 // A File is a corresponding (filename, ast) pair. 70 type File struct { 71 name string 72 ast *ast.File 73 } 74 75 func TestFormats(t *testing.T) { 76 testenv.MustHaveGoBuild(t) // more restrictive than necessary, but that's ok 77 78 // process all directories 79 filepath.Walk(".", func(path string, info os.FileInfo, err error) error { 80 if info.IsDir() { 81 if info.Name() == "testdata" { 82 return filepath.SkipDir 83 } 84 85 importPath := filepath.Join("cmd/compile", path) 86 if blacklistedPackages[filepath.ToSlash(importPath)] { 87 return filepath.SkipDir 88 } 89 90 pkg, err := build.Import(importPath, path, 0) 91 if err != nil { 92 if _, ok := err.(*build.NoGoError); ok { 93 return nil // nothing to do here 94 } 95 t.Fatal(err) 96 } 97 collectPkgFormats(t, pkg) 98 } 99 return nil 100 }) 101 102 // test and rewrite formats 103 updatedFiles := make(map[string]File) // files that were rewritten 104 for _, p := range callSites { 105 // test current format literal and determine updated one 106 out := formatReplace(p.str, func(index int, in string) string { 107 if in == "*" { 108 return in // cannot rewrite '*' (as in "%*d") 109 } 110 // in != '*' 111 typ := p.types[index] 112 format := typ + " " + in // e.g., "*Node %n" 113 114 // check if format is known 115 out, known := knownFormats[format] 116 117 // record format if not yet found 118 _, found := foundFormats[format] 119 if !found { 120 foundFormats[format] = true 121 } 122 123 // report an error if the format is unknown and this is the first 124 // time we see it; ignore "%v" and "%T" which are always valid 125 if !known && !found && in != "%v" && in != "%T" { 126 t.Errorf("%s: unknown format %q for %s argument", posString(p.arg), in, typ) 127 } 128 129 if out == "" { 130 out = in 131 } 132 return out 133 }) 134 135 // replace existing format literal if it changed 136 if out != p.str { 137 // we cannot replace the argument if it's not a string literal for now 138 // (e.g., it may be "foo" + "bar") 139 lit, ok := p.arg.(*ast.BasicLit) 140 if !ok { 141 delete(callSites, p.call) // treat as if we hadn't found this site 142 continue 143 } 144 145 if testing.Verbose() { 146 fmt.Printf("%s:\n\t- %q\n\t+ %q\n", posString(p.arg), p.str, out) 147 } 148 149 // find argument index of format argument 150 index := -1 151 for i, arg := range p.call.Args { 152 if p.arg == arg { 153 index = i 154 break 155 } 156 } 157 if index < 0 { 158 // we may have processed the same call site twice, 159 // but that shouldn't happen 160 panic("internal error: matching argument not found") 161 } 162 163 // replace literal 164 new := *lit // make a copy 165 new.Value = strconv.Quote(out) // this may introduce "-quotes where there were `-quotes 166 p.call.Args[index] = &new 167 updatedFiles[p.file.name] = p.file 168 } 169 } 170 171 // write dirty files back 172 var filesUpdated bool 173 if len(updatedFiles) > 0 && *update { 174 for _, file := range updatedFiles { 175 var buf bytes.Buffer 176 if err := format.Node(&buf, fset, file.ast); err != nil { 177 t.Errorf("WARNING: formatting %s failed: %v", file.name, err) 178 continue 179 } 180 if err := ioutil.WriteFile(file.name, buf.Bytes(), 0x666); err != nil { 181 t.Errorf("WARNING: writing %s failed: %v", file.name, err) 182 continue 183 } 184 fmt.Printf("updated %s\n", file.name) 185 filesUpdated = true 186 } 187 } 188 189 // report all function names containing a format string 190 if len(callSites) > 0 && testing.Verbose() { 191 set := make(map[string]bool) 192 for _, p := range callSites { 193 set[nodeString(p.call.Fun)] = true 194 } 195 var list []string 196 for s := range set { 197 list = append(list, s) 198 } 199 fmt.Println("\nFunctions") 200 printList(list) 201 } 202 203 // report all formats found 204 if len(foundFormats) > 0 && testing.Verbose() { 205 var list []string 206 for s := range foundFormats { 207 list = append(list, fmt.Sprintf("%q: \"\",", s)) 208 } 209 fmt.Println("\nvar knownFormats = map[string]string{") 210 printList(list) 211 fmt.Println("}") 212 } 213 214 // all format strings of calls must be in the formatStrings set (self-verification) 215 for _, p := range callSites { 216 if lit, ok := p.arg.(*ast.BasicLit); ok && lit.Kind == token.STRING { 217 if formatStrings[lit] { 218 // ok 219 delete(formatStrings, lit) 220 } else { 221 // this should never happen 222 panic(fmt.Sprintf("internal error: format string not found (%s)", posString(lit))) 223 } 224 } 225 } 226 227 // if we have any strings left, we may need to update them manually 228 if len(formatStrings) > 0 && filesUpdated { 229 var list []string 230 for lit := range formatStrings { 231 list = append(list, fmt.Sprintf("%s: %s", posString(lit), nodeString(lit))) 232 } 233 fmt.Println("\nWARNING: Potentially missed format strings") 234 printList(list) 235 t.Fail() 236 } 237 238 fmt.Println() 239 } 240 241 // A callSite describes a function call that appears to contain 242 // a format string. 243 type callSite struct { 244 file File 245 call *ast.CallExpr // call containing the format string 246 arg ast.Expr // format argument (string literal or constant) 247 str string // unquoted format string 248 types []string // argument types 249 } 250 251 func collectPkgFormats(t *testing.T, pkg *build.Package) { 252 // collect all files 253 var filenames []string 254 filenames = append(filenames, pkg.GoFiles...) 255 filenames = append(filenames, pkg.CgoFiles...) 256 filenames = append(filenames, pkg.TestGoFiles...) 257 258 // TODO(gri) verify _test files outside package 259 for _, name := range pkg.XTestGoFiles { 260 // don't process this test itself 261 if name != "fmt_test.go" && testing.Verbose() { 262 fmt.Printf("WARNING: %s not processed\n", filepath.Join(pkg.Dir, name)) 263 } 264 } 265 266 // make filenames relative to . 267 for i, name := range filenames { 268 filenames[i] = filepath.Join(pkg.Dir, name) 269 } 270 271 // parse all files 272 files := make([]*ast.File, len(filenames)) 273 for i, filename := range filenames { 274 f, err := parser.ParseFile(fset, filename, nil, parser.ParseComments) 275 if err != nil { 276 t.Fatal(err) 277 } 278 files[i] = f 279 } 280 281 // typecheck package 282 conf := types.Config{Importer: importer.Default()} 283 etypes := make(map[ast.Expr]types.TypeAndValue) 284 if _, err := conf.Check(pkg.ImportPath, fset, files, &types.Info{Types: etypes}); err != nil { 285 t.Fatal(err) 286 } 287 288 // collect all potential format strings (for extra verification later) 289 for _, file := range files { 290 ast.Inspect(file, func(n ast.Node) bool { 291 if s, ok := stringLit(n); ok && isFormat(s) { 292 formatStrings[n.(*ast.BasicLit)] = true 293 } 294 return true 295 }) 296 } 297 298 // collect all formats/arguments of calls with format strings 299 for index, file := range files { 300 ast.Inspect(file, func(n ast.Node) bool { 301 if call, ok := n.(*ast.CallExpr); ok { 302 // ignore blacklisted functions 303 if blacklistedFunctions[nodeString(call.Fun)] { 304 return true 305 } 306 // look for an arguments that might be a format string 307 for i, arg := range call.Args { 308 if s, ok := stringVal(etypes[arg]); ok && isFormat(s) { 309 // make sure we have enough arguments 310 n := numFormatArgs(s) 311 if i+1+n > len(call.Args) { 312 t.Errorf("%s: not enough format args (blacklist %s?)", posString(call), nodeString(call.Fun)) 313 break // ignore this call 314 } 315 // assume last n arguments are to be formatted; 316 // determine their types 317 argTypes := make([]string, n) 318 for i, arg := range call.Args[len(call.Args)-n:] { 319 if tv, ok := etypes[arg]; ok { 320 argTypes[i] = typeString(tv.Type) 321 } 322 } 323 // collect call site 324 if callSites[call] != nil { 325 panic("internal error: file processed twice?") 326 } 327 callSites[call] = &callSite{ 328 file: File{filenames[index], file}, 329 call: call, 330 arg: arg, 331 str: s, 332 types: argTypes, 333 } 334 break // at most one format per argument list 335 } 336 } 337 } 338 return true 339 }) 340 } 341 } 342 343 // printList prints list in sorted order. 344 func printList(list []string) { 345 sort.Strings(list) 346 for _, s := range list { 347 fmt.Println("\t", s) 348 } 349 } 350 351 // posString returns a string representation of n's position 352 // in the form filename:line:col: . 353 func posString(n ast.Node) string { 354 if n == nil { 355 return "" 356 } 357 return fset.Position(n.Pos()).String() 358 } 359 360 // nodeString returns a string representation of n. 361 func nodeString(n ast.Node) string { 362 var buf bytes.Buffer 363 if err := format.Node(&buf, fset, n); err != nil { 364 log.Fatal(err) // should always succeed 365 } 366 return buf.String() 367 } 368 369 // typeString returns a string representation of n. 370 func typeString(typ types.Type) string { 371 return filepath.ToSlash(typ.String()) 372 } 373 374 // stringLit returns the unquoted string value and true if 375 // n represents a string literal; otherwise it returns "" 376 // and false. 377 func stringLit(n ast.Node) (string, bool) { 378 if lit, ok := n.(*ast.BasicLit); ok && lit.Kind == token.STRING { 379 s, err := strconv.Unquote(lit.Value) 380 if err != nil { 381 log.Fatal(err) // should not happen with correct ASTs 382 } 383 return s, true 384 } 385 return "", false 386 } 387 388 // stringVal returns the (unquoted) string value and true if 389 // tv is a string constant; otherwise it returns "" and false. 390 func stringVal(tv types.TypeAndValue) (string, bool) { 391 if tv.IsValue() && tv.Value != nil && tv.Value.Kind() == constant.String { 392 return constant.StringVal(tv.Value), true 393 } 394 return "", false 395 } 396 397 // formatIter iterates through the string s in increasing 398 // index order and calls f for each format specifier '%..v'. 399 // The arguments for f describe the specifier's index range. 400 // If a format specifier contains a "*", f is called with 401 // the index range for "*" alone, before being called for 402 // the entire specifier. The result of f is the index of 403 // the rune at which iteration continues. 404 func formatIter(s string, f func(i, j int) int) { 405 i := 0 // index after current rune 406 var r rune // current rune 407 408 next := func() { 409 r1, w := utf8.DecodeRuneInString(s[i:]) 410 if w == 0 { 411 r1 = -1 // signal end-of-string 412 } 413 r = r1 414 i += w 415 } 416 417 flags := func() { 418 for r == ' ' || r == '#' || r == '+' || r == '-' || r == '0' { 419 next() 420 } 421 } 422 423 index := func() { 424 if r == '[' { 425 log.Fatalf("cannot handle indexed arguments: %s", s) 426 } 427 } 428 429 digits := func() { 430 index() 431 if r == '*' { 432 i = f(i-1, i) 433 next() 434 return 435 } 436 for '0' <= r && r <= '9' { 437 next() 438 } 439 } 440 441 for next(); r >= 0; next() { 442 if r == '%' { 443 i0 := i 444 next() 445 flags() 446 digits() 447 if r == '.' { 448 next() 449 digits() 450 } 451 index() 452 // accept any letter (a-z, A-Z) as format verb; 453 // ignore anything else 454 if 'a' <= r && r <= 'z' || 'A' <= r && r <= 'Z' { 455 i = f(i0-1, i) 456 } 457 } 458 } 459 } 460 461 // isFormat reports whether s contains format specifiers. 462 func isFormat(s string) (yes bool) { 463 formatIter(s, func(i, j int) int { 464 yes = true 465 return len(s) // stop iteration 466 }) 467 return 468 } 469 470 // oneFormat reports whether s is exactly one format specifier. 471 func oneFormat(s string) (yes bool) { 472 formatIter(s, func(i, j int) int { 473 yes = i == 0 && j == len(s) 474 return j 475 }) 476 return 477 } 478 479 // numFormatArgs returns the number of format specifiers in s. 480 func numFormatArgs(s string) int { 481 count := 0 482 formatIter(s, func(i, j int) int { 483 count++ 484 return j 485 }) 486 return count 487 } 488 489 // formatReplace replaces the i'th format specifier s in the incoming 490 // string in with the result of f(i, s) and returns the new string. 491 func formatReplace(in string, f func(i int, s string) string) string { 492 var buf []byte 493 i0 := 0 494 index := 0 495 formatIter(in, func(i, j int) int { 496 if sub := in[i:j]; sub != "*" { // ignore calls for "*" width/length specifiers 497 buf = append(buf, in[i0:i]...) 498 buf = append(buf, f(index, sub)...) 499 i0 = j 500 } 501 index++ 502 return j 503 }) 504 return string(append(buf, in[i0:]...)) 505 } 506 507 // blacklistedPackages is the set of packages which can 508 // be ignored. 509 var blacklistedPackages = map[string]bool{} 510 511 // blacklistedFunctions is the set of functions which may have 512 // format-like arguments but which don't do any formatting and 513 // thus may be ignored. 514 var blacklistedFunctions = map[string]bool{} 515 516 func init() { 517 // verify that knownFormats entries are correctly formatted 518 for key, val := range knownFormats { 519 // key must be "typename format", and format starts with a '%' 520 // (formats containing '*' alone are not collected in this table) 521 i := strings.Index(key, "%") 522 if i < 0 || !oneFormat(key[i:]) { 523 log.Fatalf("incorrect knownFormats key: %q", key) 524 } 525 // val must be "format" or "" 526 if val != "" && !oneFormat(val) { 527 log.Fatalf("incorrect knownFormats value: %q (key = %q)", val, key) 528 } 529 } 530 } 531 532 // knownFormats entries are of the form "typename format" -> "newformat". 533 // An absent entry means that the format is not recognized as valid. 534 // An empty new format means that the format should remain unchanged. 535 // To print out a new table, run: go test -run Formats -v. 536 var knownFormats = map[string]string{ 537 "*bytes.Buffer %s": "", 538 "*math/big.Int %#x": "", 539 "*cmd/compile/internal/gc.Bits %v": "", 540 "*cmd/compile/internal/gc.Field %p": "", 541 "*cmd/compile/internal/gc.Field %v": "", 542 "*cmd/compile/internal/gc.Mpflt %v": "", 543 "*cmd/compile/internal/gc.Mpint %v": "", 544 "*cmd/compile/internal/gc.Node %#v": "", 545 "*cmd/compile/internal/gc.Node %+S": "", 546 "*cmd/compile/internal/gc.Node %+v": "", 547 "*cmd/compile/internal/gc.Node %0j": "", 548 "*cmd/compile/internal/gc.Node %L": "", 549 "*cmd/compile/internal/gc.Node %S": "", 550 "*cmd/compile/internal/gc.Node %j": "", 551 "*cmd/compile/internal/gc.Node %p": "", 552 "*cmd/compile/internal/gc.Node %v": "", 553 "*cmd/compile/internal/gc.Sym %+v": "", 554 "*cmd/compile/internal/gc.Sym %-v": "", 555 "*cmd/compile/internal/gc.Sym %0S": "", 556 "*cmd/compile/internal/gc.Sym %S": "", 557 "*cmd/compile/internal/gc.Sym %p": "", 558 "*cmd/compile/internal/gc.Sym %v": "", 559 "*cmd/compile/internal/gc.Type %#v": "", 560 "*cmd/compile/internal/gc.Type %+v": "", 561 "*cmd/compile/internal/gc.Type %-S": "", 562 "*cmd/compile/internal/gc.Type %0S": "", 563 "*cmd/compile/internal/gc.Type %L": "", 564 "*cmd/compile/internal/gc.Type %S": "", 565 "*cmd/compile/internal/gc.Type %p": "", 566 "*cmd/compile/internal/gc.Type %v": "", 567 "*cmd/compile/internal/ssa.Block %s": "", 568 "*cmd/compile/internal/ssa.Block %v": "", 569 "*cmd/compile/internal/ssa.Func %s": "", 570 "*cmd/compile/internal/ssa.SparseTreeNode %v": "", 571 "*cmd/compile/internal/ssa.Value %s": "", 572 "*cmd/compile/internal/ssa.Value %v": "", 573 "*cmd/compile/internal/ssa.sparseTreeMapEntry %v": "", 574 "*cmd/internal/obj.Addr %v": "", 575 "*cmd/internal/obj.Prog %p": "", 576 "*cmd/internal/obj.Prog %s": "", 577 "*cmd/internal/obj.Prog %v": "", 578 "[16]byte %x": "", 579 "[]*cmd/compile/internal/gc.Node %v": "", 580 "[]*cmd/compile/internal/gc.Sig %#v": "", 581 "[]*cmd/compile/internal/ssa.Value %v": "", 582 "[]byte %s": "", 583 "[]byte %x": "", 584 "[]cmd/compile/internal/ssa.Edge %v": "", 585 "[]cmd/compile/internal/ssa.ID %v": "", 586 "[]string %v": "", 587 "bool %t": "", 588 "bool %v": "", 589 "byte %02x": "", 590 "byte %08b": "", 591 "byte %c": "", 592 "cmd/compile/internal/arm.shift %d": "", 593 "cmd/compile/internal/gc.Class %d": "", 594 "cmd/compile/internal/gc.Ctype %d": "", 595 "cmd/compile/internal/gc.Ctype %v": "", 596 "cmd/compile/internal/gc.EType %d": "", 597 "cmd/compile/internal/gc.EType %s": "", 598 "cmd/compile/internal/gc.EType %v": "", 599 "cmd/compile/internal/gc.Level %d": "", 600 "cmd/compile/internal/gc.Level %v": "", 601 "cmd/compile/internal/gc.Node %#v": "", 602 "cmd/compile/internal/gc.Nodes %#v": "", 603 "cmd/compile/internal/gc.Nodes %+v": "", 604 "cmd/compile/internal/gc.Nodes %.v": "", 605 "cmd/compile/internal/gc.Nodes %v": "", 606 "cmd/compile/internal/gc.Op %#v": "", 607 "cmd/compile/internal/gc.Op %v": "", 608 "cmd/compile/internal/gc.Val %#v": "", 609 "cmd/compile/internal/gc.Val %T": "", 610 "cmd/compile/internal/gc.Val %v": "", 611 "cmd/compile/internal/gc.initKind %d": "", 612 "cmd/compile/internal/ssa.BlockKind %s": "", 613 "cmd/compile/internal/ssa.BranchPrediction %d": "", 614 "cmd/compile/internal/ssa.Edge %v": "", 615 "cmd/compile/internal/ssa.GCNode %s": "", 616 "cmd/compile/internal/ssa.ID %d": "", 617 "cmd/compile/internal/ssa.LocalSlot %s": "", 618 "cmd/compile/internal/ssa.Location %v": "", 619 "cmd/compile/internal/ssa.Op %s": "", 620 "cmd/compile/internal/ssa.Op %v": "", 621 "cmd/compile/internal/ssa.SizeAndAlign %s": "", 622 "cmd/compile/internal/ssa.Type %s": "", 623 "cmd/compile/internal/ssa.ValAndOff %s": "", 624 "cmd/compile/internal/ssa.markKind %d": "", 625 "cmd/compile/internal/ssa.rbrank %d": "", 626 "cmd/compile/internal/ssa.regMask %d": "", 627 "cmd/compile/internal/ssa.register %d": "", 628 "cmd/compile/internal/syntax.Expr %#v": "", 629 "cmd/compile/internal/syntax.Expr %s": "", 630 "cmd/compile/internal/syntax.Node %T": "", 631 "cmd/compile/internal/syntax.Operator %d": "", 632 "cmd/compile/internal/syntax.Operator %s": "", 633 "cmd/compile/internal/syntax.token %d": "", 634 "cmd/compile/internal/syntax.token %q": "", 635 "cmd/compile/internal/syntax.token %s": "", 636 "cmd/internal/obj.As %v": "", 637 "error %v": "", 638 "float64 %.2f": "", 639 "float64 %.3f": "", 640 "float64 %.6g": "", 641 "float64 %g": "", 642 "fmt.Stringer %T": "", 643 "int %#x": "", 644 "int %-12d": "", 645 "int %-2d": "", 646 "int %-6d": "", 647 "int %-8o": "", 648 "int %2d": "", 649 "int %5d": "", 650 "int %6d": "", 651 "int %c": "", 652 "int %d": "", 653 "int %v": "", 654 "int %x": "", 655 "int16 %2d": "", 656 "int16 %d": "", 657 "int16 %x": "", 658 "int32 %4d": "", 659 "int32 %5d": "", 660 "int32 %d": "", 661 "int32 %v": "", 662 "int32 %x": "", 663 "int64 %+d": "", 664 "int64 %-10d": "", 665 "int64 %X": "", 666 "int64 %d": "", 667 "int64 %v": "", 668 "int64 %x": "", 669 "int8 %d": "", 670 "int8 %x": "", 671 "interface{} %#v": "", 672 "interface{} %T": "", 673 "interface{} %q": "", 674 "interface{} %s": "", 675 "interface{} %v": "", 676 "map[*cmd/compile/internal/gc.Node]*cmd/compile/internal/ssa.Value %v": "", 677 "reflect.Type %s": "", 678 "rune %#U": "", 679 "rune %c": "", 680 "rune %d": "", 681 "string %-16s": "", 682 "string %.*s": "", 683 "string %q": "", 684 "string %s": "", 685 "string %v": "", 686 "time.Duration %d": "", 687 "time.Duration %v": "", 688 "uint %.4d": "", 689 "uint %04x": "", 690 "uint %d": "", 691 "uint %v": "", 692 "uint16 %d": "", 693 "uint16 %v": "", 694 "uint16 %x": "", 695 "uint32 %#x": "", 696 "uint32 %08x": "", 697 "uint32 %d": "", 698 "uint32 %x": "", 699 "uint64 %#x": "", 700 "uint64 %016x": "", 701 "uint64 %08x": "", 702 "uint64 %d": "", 703 "uint64 %x": "", 704 "uint8 %d": "", 705 "uint8 %x": "", 706 "uintptr %d": "", 707 }