github.com/miolini/go@v0.0.0-20160405192216-fca68c8cb408/src/cmd/vet/print.go (about) 1 // Copyright 2010 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 contains the printf-checker. 6 7 package main 8 9 import ( 10 "bytes" 11 "flag" 12 "go/ast" 13 "go/constant" 14 "go/token" 15 "go/types" 16 "strconv" 17 "strings" 18 "unicode/utf8" 19 ) 20 21 var printfuncs = flag.String("printfuncs", "", "comma-separated list of print function names to check") 22 23 func init() { 24 register("printf", 25 "check printf-like invocations", 26 checkFmtPrintfCall, 27 funcDecl, callExpr) 28 } 29 30 func initPrintFlags() { 31 if *printfuncs == "" { 32 return 33 } 34 for _, name := range strings.Split(*printfuncs, ",") { 35 if len(name) == 0 { 36 flag.Usage() 37 } 38 skip := 0 39 if colon := strings.LastIndex(name, ":"); colon > 0 { 40 var err error 41 skip, err = strconv.Atoi(name[colon+1:]) 42 if err != nil { 43 errorf(`illegal format for "Func:N" argument %q; %s`, name, err) 44 } 45 name = name[:colon] 46 } 47 name = strings.ToLower(name) 48 if name[len(name)-1] == 'f' { 49 isFormattedPrint[name] = true 50 } else { 51 printList[name] = skip 52 } 53 } 54 } 55 56 // isFormattedPrint records the formatted-print functions. Names are 57 // lower-cased so the lookup is case insensitive. 58 var isFormattedPrint = map[string]bool{ 59 "errorf": true, 60 "fatalf": true, 61 "fprintf": true, 62 "logf": true, 63 "panicf": true, 64 "printf": true, 65 "sprintf": true, 66 } 67 68 // printList records the unformatted-print functions. The value is the location 69 // of the first parameter to be printed. Names are lower-cased so the lookup is 70 // case insensitive. 71 var printList = map[string]int{ 72 "error": 0, 73 "fatal": 0, 74 "fprint": 1, "fprintln": 1, 75 "log": 0, 76 "panic": 0, "panicln": 0, 77 "print": 0, "println": 0, 78 "sprint": 0, "sprintln": 0, 79 } 80 81 // formatString returns the format string argument and its index within 82 // the given printf-like call expression. 83 // 84 // The last parameter before variadic arguments is assumed to be 85 // a format string. 86 // 87 // The first string literal or string constant is assumed to be a format string 88 // if the call's signature cannot be determined. 89 // 90 // If it cannot find any format string parameter, it returns ("", -1). 91 func formatString(f *File, call *ast.CallExpr) (string, int) { 92 typ := f.pkg.types[call.Fun].Type 93 if typ != nil { 94 if sig, ok := typ.(*types.Signature); ok { 95 if !sig.Variadic() { 96 // Skip checking non-variadic functions 97 return "", -1 98 } 99 idx := sig.Params().Len() - 2 100 if idx < 0 { 101 // Skip checking variadic functions without 102 // fixed arguments. 103 return "", -1 104 } 105 s, ok := stringLiteralArg(f, call, idx) 106 if !ok { 107 // The last argument before variadic args isn't a string 108 return "", -1 109 } 110 return s, idx 111 } 112 } 113 114 // Cannot determine call's signature. Fallback to scanning for the first 115 // string argument in the call 116 for idx := range call.Args { 117 if s, ok := stringLiteralArg(f, call, idx); ok { 118 return s, idx 119 } 120 } 121 return "", -1 122 } 123 124 // stringLiteralArg returns call's string constant argument at the index idx. 125 // 126 // ("", false) is returned if call's argument at the index idx isn't a string 127 // literal. 128 func stringLiteralArg(f *File, call *ast.CallExpr, idx int) (string, bool) { 129 if idx >= len(call.Args) { 130 return "", false 131 } 132 arg := call.Args[idx] 133 lit := f.pkg.types[arg].Value 134 if lit != nil && lit.Kind() == constant.String { 135 return constant.StringVal(lit), true 136 } 137 return "", false 138 } 139 140 // checkCall triggers the print-specific checks if the call invokes a print function. 141 func checkFmtPrintfCall(f *File, node ast.Node) { 142 if d, ok := node.(*ast.FuncDecl); ok && isStringer(f, d) { 143 // Remember we saw this. 144 if f.stringers == nil { 145 f.stringers = make(map[*ast.Object]bool) 146 } 147 if l := d.Recv.List; len(l) == 1 { 148 if n := l[0].Names; len(n) == 1 { 149 f.stringers[n[0].Obj] = true 150 } 151 } 152 return 153 } 154 155 call, ok := node.(*ast.CallExpr) 156 if !ok { 157 return 158 } 159 var Name string 160 switch x := call.Fun.(type) { 161 case *ast.Ident: 162 Name = x.Name 163 case *ast.SelectorExpr: 164 Name = x.Sel.Name 165 default: 166 return 167 } 168 169 name := strings.ToLower(Name) 170 if _, ok := isFormattedPrint[name]; ok { 171 f.checkPrintf(call, Name) 172 return 173 } 174 if skip, ok := printList[name]; ok { 175 f.checkPrint(call, Name, skip) 176 return 177 } 178 } 179 180 // isStringer returns true if the provided declaration is a "String() string" 181 // method, an implementation of fmt.Stringer. 182 func isStringer(f *File, d *ast.FuncDecl) bool { 183 return d.Recv != nil && d.Name.Name == "String" && d.Type.Results != nil && 184 len(d.Type.Params.List) == 0 && len(d.Type.Results.List) == 1 && 185 f.pkg.types[d.Type.Results.List[0].Type].Type == types.Typ[types.String] 186 } 187 188 // formatState holds the parsed representation of a printf directive such as "%3.*[4]d". 189 // It is constructed by parsePrintfVerb. 190 type formatState struct { 191 verb rune // the format verb: 'd' for "%d" 192 format string // the full format directive from % through verb, "%.3d". 193 name string // Printf, Sprintf etc. 194 flags []byte // the list of # + etc. 195 argNums []int // the successive argument numbers that are consumed, adjusted to refer to actual arg in call 196 indexed bool // whether an indexing expression appears: %[1]d. 197 firstArg int // Index of first argument after the format in the Printf call. 198 // Used only during parse. 199 file *File 200 call *ast.CallExpr 201 argNum int // Which argument we're expecting to format now. 202 indexPending bool // Whether we have an indexed argument that has not resolved. 203 nbytes int // number of bytes of the format string consumed. 204 } 205 206 // checkPrintf checks a call to a formatted print routine such as Printf. 207 func (f *File) checkPrintf(call *ast.CallExpr, name string) { 208 format, idx := formatString(f, call) 209 if idx < 0 { 210 if *verbose { 211 f.Warn(call.Pos(), "can't check non-constant format in call to", name) 212 } 213 return 214 } 215 216 firstArg := idx + 1 // Arguments are immediately after format string. 217 if !strings.Contains(format, "%") { 218 if len(call.Args) > firstArg { 219 f.Badf(call.Pos(), "no formatting directive in %s call", name) 220 } 221 return 222 } 223 // Hard part: check formats against args. 224 argNum := firstArg 225 indexed := false 226 for i, w := 0, 0; i < len(format); i += w { 227 w = 1 228 if format[i] == '%' { 229 state := f.parsePrintfVerb(call, name, format[i:], firstArg, argNum) 230 if state == nil { 231 return 232 } 233 w = len(state.format) 234 if state.indexed { 235 indexed = true 236 } 237 if !f.okPrintfArg(call, state) { // One error per format is enough. 238 return 239 } 240 if len(state.argNums) > 0 { 241 // Continue with the next sequential argument. 242 argNum = state.argNums[len(state.argNums)-1] + 1 243 } 244 } 245 } 246 // Dotdotdot is hard. 247 if call.Ellipsis.IsValid() && argNum >= len(call.Args)-1 { 248 return 249 } 250 // If the arguments were direct indexed, we assume the programmer knows what's up. 251 // Otherwise, there should be no leftover arguments. 252 if !indexed && argNum != len(call.Args) { 253 expect := argNum - firstArg 254 numArgs := len(call.Args) - firstArg 255 f.Badf(call.Pos(), "wrong number of args for format in %s call: %d needed but %d args", name, expect, numArgs) 256 } 257 } 258 259 // parseFlags accepts any printf flags. 260 func (s *formatState) parseFlags() { 261 for s.nbytes < len(s.format) { 262 switch c := s.format[s.nbytes]; c { 263 case '#', '0', '+', '-', ' ': 264 s.flags = append(s.flags, c) 265 s.nbytes++ 266 default: 267 return 268 } 269 } 270 } 271 272 // scanNum advances through a decimal number if present. 273 func (s *formatState) scanNum() { 274 for ; s.nbytes < len(s.format); s.nbytes++ { 275 c := s.format[s.nbytes] 276 if c < '0' || '9' < c { 277 return 278 } 279 } 280 } 281 282 // parseIndex scans an index expression. It returns false if there is a syntax error. 283 func (s *formatState) parseIndex() bool { 284 if s.nbytes == len(s.format) || s.format[s.nbytes] != '[' { 285 return true 286 } 287 // Argument index present. 288 s.indexed = true 289 s.nbytes++ // skip '[' 290 start := s.nbytes 291 s.scanNum() 292 if s.nbytes == len(s.format) || s.nbytes == start || s.format[s.nbytes] != ']' { 293 s.file.Badf(s.call.Pos(), "illegal syntax for printf argument index") 294 return false 295 } 296 arg32, err := strconv.ParseInt(s.format[start:s.nbytes], 10, 32) 297 if err != nil { 298 s.file.Badf(s.call.Pos(), "illegal syntax for printf argument index: %s", err) 299 return false 300 } 301 s.nbytes++ // skip ']' 302 arg := int(arg32) 303 arg += s.firstArg - 1 // We want to zero-index the actual arguments. 304 s.argNum = arg 305 s.indexPending = true 306 return true 307 } 308 309 // parseNum scans a width or precision (or *). It returns false if there's a bad index expression. 310 func (s *formatState) parseNum() bool { 311 if s.nbytes < len(s.format) && s.format[s.nbytes] == '*' { 312 if s.indexPending { // Absorb it. 313 s.indexPending = false 314 } 315 s.nbytes++ 316 s.argNums = append(s.argNums, s.argNum) 317 s.argNum++ 318 } else { 319 s.scanNum() 320 } 321 return true 322 } 323 324 // parsePrecision scans for a precision. It returns false if there's a bad index expression. 325 func (s *formatState) parsePrecision() bool { 326 // If there's a period, there may be a precision. 327 if s.nbytes < len(s.format) && s.format[s.nbytes] == '.' { 328 s.flags = append(s.flags, '.') // Treat precision as a flag. 329 s.nbytes++ 330 if !s.parseIndex() { 331 return false 332 } 333 if !s.parseNum() { 334 return false 335 } 336 } 337 return true 338 } 339 340 // parsePrintfVerb looks the formatting directive that begins the format string 341 // and returns a formatState that encodes what the directive wants, without looking 342 // at the actual arguments present in the call. The result is nil if there is an error. 343 func (f *File) parsePrintfVerb(call *ast.CallExpr, name, format string, firstArg, argNum int) *formatState { 344 state := &formatState{ 345 format: format, 346 name: name, 347 flags: make([]byte, 0, 5), 348 argNum: argNum, 349 argNums: make([]int, 0, 1), 350 nbytes: 1, // There's guaranteed to be a percent sign. 351 indexed: false, 352 firstArg: firstArg, 353 file: f, 354 call: call, 355 } 356 // There may be flags. 357 state.parseFlags() 358 indexPending := false 359 // There may be an index. 360 if !state.parseIndex() { 361 return nil 362 } 363 // There may be a width. 364 if !state.parseNum() { 365 return nil 366 } 367 // There may be a precision. 368 if !state.parsePrecision() { 369 return nil 370 } 371 // Now a verb, possibly prefixed by an index (which we may already have). 372 if !indexPending && !state.parseIndex() { 373 return nil 374 } 375 if state.nbytes == len(state.format) { 376 f.Badf(call.Pos(), "missing verb at end of format string in %s call", name) 377 return nil 378 } 379 verb, w := utf8.DecodeRuneInString(state.format[state.nbytes:]) 380 state.verb = verb 381 state.nbytes += w 382 if verb != '%' { 383 state.argNums = append(state.argNums, state.argNum) 384 } 385 state.format = state.format[:state.nbytes] 386 return state 387 } 388 389 // printfArgType encodes the types of expressions a printf verb accepts. It is a bitmask. 390 type printfArgType int 391 392 const ( 393 argBool printfArgType = 1 << iota 394 argInt 395 argRune 396 argString 397 argFloat 398 argComplex 399 argPointer 400 anyType printfArgType = ^0 401 ) 402 403 type printVerb struct { 404 verb rune // User may provide verb through Formatter; could be a rune. 405 flags string // known flags are all ASCII 406 typ printfArgType 407 } 408 409 // Common flag sets for printf verbs. 410 const ( 411 noFlag = "" 412 numFlag = " -+.0" 413 sharpNumFlag = " -+.0#" 414 allFlags = " -+.0#" 415 ) 416 417 // printVerbs identifies which flags are known to printf for each verb. 418 // TODO: A type that implements Formatter may do what it wants, and vet 419 // will complain incorrectly. 420 var printVerbs = []printVerb{ 421 // '-' is a width modifier, always valid. 422 // '.' is a precision for float, max width for strings. 423 // '+' is required sign for numbers, Go format for %v. 424 // '#' is alternate format for several verbs. 425 // ' ' is spacer for numbers 426 {'%', noFlag, 0}, 427 {'b', numFlag, argInt | argFloat | argComplex}, 428 {'c', "-", argRune | argInt}, 429 {'d', numFlag, argInt}, 430 {'e', numFlag, argFloat | argComplex}, 431 {'E', numFlag, argFloat | argComplex}, 432 {'f', numFlag, argFloat | argComplex}, 433 {'F', numFlag, argFloat | argComplex}, 434 {'g', numFlag, argFloat | argComplex}, 435 {'G', numFlag, argFloat | argComplex}, 436 {'o', sharpNumFlag, argInt}, 437 {'p', "-#", argPointer}, 438 {'q', " -+.0#", argRune | argInt | argString}, 439 {'s', " -+.0", argString}, 440 {'t', "-", argBool}, 441 {'T', "-", anyType}, 442 {'U', "-#", argRune | argInt}, 443 {'v', allFlags, anyType}, 444 {'x', sharpNumFlag, argRune | argInt | argString}, 445 {'X', sharpNumFlag, argRune | argInt | argString}, 446 } 447 448 // okPrintfArg compares the formatState to the arguments actually present, 449 // reporting any discrepancies it can discern. If the final argument is ellipsissed, 450 // there's little it can do for that. 451 func (f *File) okPrintfArg(call *ast.CallExpr, state *formatState) (ok bool) { 452 var v printVerb 453 found := false 454 // Linear scan is fast enough for a small list. 455 for _, v = range printVerbs { 456 if v.verb == state.verb { 457 found = true 458 break 459 } 460 } 461 if !found { 462 f.Badf(call.Pos(), "unrecognized printf verb %q", state.verb) 463 return false 464 } 465 for _, flag := range state.flags { 466 if !strings.ContainsRune(v.flags, rune(flag)) { 467 f.Badf(call.Pos(), "unrecognized printf flag for verb %q: %q", state.verb, flag) 468 return false 469 } 470 } 471 // Verb is good. If len(state.argNums)>trueArgs, we have something like %.*s and all 472 // but the final arg must be an integer. 473 trueArgs := 1 474 if state.verb == '%' { 475 trueArgs = 0 476 } 477 nargs := len(state.argNums) 478 for i := 0; i < nargs-trueArgs; i++ { 479 argNum := state.argNums[i] 480 if !f.argCanBeChecked(call, i, true, state) { 481 return 482 } 483 arg := call.Args[argNum] 484 if !f.matchArgType(argInt, nil, arg) { 485 f.Badf(call.Pos(), "arg %s for * in printf format not of type int", f.gofmt(arg)) 486 return false 487 } 488 } 489 if state.verb == '%' { 490 return true 491 } 492 argNum := state.argNums[len(state.argNums)-1] 493 if !f.argCanBeChecked(call, len(state.argNums)-1, false, state) { 494 return false 495 } 496 arg := call.Args[argNum] 497 if f.isFunctionValue(arg) && state.verb != 'p' && state.verb != 'T' { 498 f.Badf(call.Pos(), "arg %s in printf call is a function value, not a function call", f.gofmt(arg)) 499 return false 500 } 501 if !f.matchArgType(v.typ, nil, arg) { 502 typeString := "" 503 if typ := f.pkg.types[arg].Type; typ != nil { 504 typeString = typ.String() 505 } 506 f.Badf(call.Pos(), "arg %s for printf verb %%%c of wrong type: %s", f.gofmt(arg), state.verb, typeString) 507 return false 508 } 509 if v.typ&argString != 0 && v.verb != 'T' && !bytes.Contains(state.flags, []byte{'#'}) && f.recursiveStringer(arg) { 510 f.Badf(call.Pos(), "arg %s for printf causes recursive call to String method", f.gofmt(arg)) 511 return false 512 } 513 return true 514 } 515 516 // recursiveStringer reports whether the provided argument is r or &r for the 517 // fmt.Stringer receiver identifier r. 518 func (f *File) recursiveStringer(e ast.Expr) bool { 519 if len(f.stringers) == 0 { 520 return false 521 } 522 var obj *ast.Object 523 switch e := e.(type) { 524 case *ast.Ident: 525 obj = e.Obj 526 case *ast.UnaryExpr: 527 if id, ok := e.X.(*ast.Ident); ok && e.Op == token.AND { 528 obj = id.Obj 529 } 530 } 531 532 // It's unlikely to be a recursive stringer if it has a Format method. 533 if typ := f.pkg.types[e].Type; typ != nil { 534 // Not a perfect match; see issue 6259. 535 if f.hasMethod(typ, "Format") { 536 return false 537 } 538 } 539 540 // We compare the underlying Object, which checks that the identifier 541 // is the one we declared as the receiver for the String method in 542 // which this printf appears. 543 return f.stringers[obj] 544 } 545 546 // isFunctionValue reports whether the expression is a function as opposed to a function call. 547 // It is almost always a mistake to print a function value. 548 func (f *File) isFunctionValue(e ast.Expr) bool { 549 if typ := f.pkg.types[e].Type; typ != nil { 550 _, ok := typ.(*types.Signature) 551 return ok 552 } 553 return false 554 } 555 556 // argCanBeChecked reports whether the specified argument is statically present; 557 // it may be beyond the list of arguments or in a terminal slice... argument, which 558 // means we can't see it. 559 func (f *File) argCanBeChecked(call *ast.CallExpr, formatArg int, isStar bool, state *formatState) bool { 560 argNum := state.argNums[formatArg] 561 if argNum < 0 { 562 // Shouldn't happen, so catch it with prejudice. 563 panic("negative arg num") 564 } 565 if argNum == 0 { 566 f.Badf(call.Pos(), `index value [0] for %s("%s"); indexes start at 1`, state.name, state.format) 567 return false 568 } 569 if argNum < len(call.Args)-1 { 570 return true // Always OK. 571 } 572 if call.Ellipsis.IsValid() { 573 return false // We just can't tell; there could be many more arguments. 574 } 575 if argNum < len(call.Args) { 576 return true 577 } 578 // There are bad indexes in the format or there are fewer arguments than the format needs. 579 // This is the argument number relative to the format: Printf("%s", "hi") will give 1 for the "hi". 580 arg := argNum - state.firstArg + 1 // People think of arguments as 1-indexed. 581 f.Badf(call.Pos(), `missing argument for %s("%s"): format reads arg %d, have only %d args`, state.name, state.format, arg, len(call.Args)-state.firstArg) 582 return false 583 } 584 585 // checkPrint checks a call to an unformatted print routine such as Println. 586 // call.Args[firstArg] is the first argument to be printed. 587 func (f *File) checkPrint(call *ast.CallExpr, name string, firstArg int) { 588 isLn := strings.HasSuffix(name, "ln") 589 isF := strings.HasPrefix(name, "F") 590 args := call.Args 591 if name == "Log" && len(args) > 0 { 592 // Special case: Don't complain about math.Log or cmplx.Log. 593 // Not strictly necessary because the only complaint likely is for Log("%d") 594 // but it feels wrong to check that math.Log is a good print function. 595 if sel, ok := args[0].(*ast.SelectorExpr); ok { 596 if x, ok := sel.X.(*ast.Ident); ok { 597 if x.Name == "math" || x.Name == "cmplx" { 598 return 599 } 600 } 601 } 602 } 603 // check for Println(os.Stderr, ...) 604 if firstArg == 0 && !isF && len(args) > 0 { 605 if sel, ok := args[0].(*ast.SelectorExpr); ok { 606 if x, ok := sel.X.(*ast.Ident); ok { 607 if x.Name == "os" && strings.HasPrefix(sel.Sel.Name, "Std") { 608 f.Badf(call.Pos(), "first argument to %s is %s.%s", name, x.Name, sel.Sel.Name) 609 } 610 } 611 } 612 } 613 if len(args) <= firstArg { 614 // If we have a call to a method called Error that satisfies the Error interface, 615 // then it's ok. Otherwise it's something like (*T).Error from the testing package 616 // and we need to check it. 617 if name == "Error" && f.isErrorMethodCall(call) { 618 return 619 } 620 // If it's an Error call now, it's probably for printing errors. 621 if !isLn { 622 // Check the signature to be sure: there are niladic functions called "error". 623 if firstArg != 0 || f.numArgsInSignature(call) != firstArg { 624 f.Badf(call.Pos(), "no args in %s call", name) 625 } 626 } 627 return 628 } 629 arg := args[firstArg] 630 if lit, ok := arg.(*ast.BasicLit); ok && lit.Kind == token.STRING { 631 if strings.Contains(lit.Value, "%") { 632 f.Badf(call.Pos(), "possible formatting directive in %s call", name) 633 } 634 } 635 if isLn { 636 // The last item, if a string, should not have a newline. 637 arg = args[len(call.Args)-1] 638 if lit, ok := arg.(*ast.BasicLit); ok && lit.Kind == token.STRING { 639 if strings.HasSuffix(lit.Value, `\n"`) { 640 f.Badf(call.Pos(), "%s call ends with newline", name) 641 } 642 } 643 } 644 for _, arg := range args { 645 if f.isFunctionValue(arg) { 646 f.Badf(call.Pos(), "arg %s in %s call is a function value, not a function call", f.gofmt(arg), name) 647 } 648 if f.recursiveStringer(arg) { 649 f.Badf(call.Pos(), "arg %s in %s call causes recursive call to String method", f.gofmt(arg), name) 650 } 651 } 652 }