Skip to content

Commit

Permalink
SA1006: simpler and more robust computation of alternative
Browse files Browse the repository at this point in the history
Closes: gh-1564
  • Loading branch information
dominikh committed Jun 21, 2024
1 parent 1f70727 commit 3fe6ed0
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 7 deletions.
18 changes: 11 additions & 7 deletions staticcheck/sa1006/sa1006.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import (
"fmt"
"go/ast"
"go/types"
"strings"

"honnef.co/go/tools/analysis/code"
"honnef.co/go/tools/analysis/edit"
Expand Down Expand Up @@ -71,6 +70,7 @@ func run(pass *analysis.Pass) (interface{}, error) {
return
}
if len(call.Args) != arg+1 {
// This filters out calls of method expressions like (*log.Logger).Printf(nil, s)
return
}
switch call.Args[arg].(type) {
Expand All @@ -86,13 +86,17 @@ func run(pass *analysis.Pass) (interface{}, error) {
return
}

alt := name[:len(name)-1] // fmt.Printf
if alt[0] == '(' { // (*log.Logger).Printf
_, alt, _ = strings.Cut(alt, ")")
alt = call.Fun.(*ast.SelectorExpr).X.(*ast.Ident).Name + alt
}
if name == "fmt.Errorf" { // Special case.
var alt string
if name == "fmt.Errorf" {
// The alternative to fmt.Errorf isn't fmt.Error but errors.New
alt = "errors.New"
} else {
// This can be either a function call like log.Printf or a method call with an
// arbitrarily complex selector, such as foo.bar[0].Printf. In either case,
// all we have to do is remove the final 'f' from the existing call.Fun
// expression.
alt = report.Render(pass, call.Fun)
alt = alt[:len(alt)-1]
}
report.Report(pass, call,
"printf-style function with dynamic format string and no further arguments should use print-style function instead",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,11 @@ func fn(s string) {
tb.Skipf(s) //@ diag(`should use print-style function`)

fmt.Errorf(s) //@ diag(`should use print-style function`)

var nested struct {
l log.Logger
}
nested.l.Printf(s) //@ diag(`should use print-style function`)
}

func fn3() (string, int) { return "", 0 }
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,11 @@ func fn(s string) {
tb.Skip(s) //@ diag(`should use print-style function`)

errors.New(s) //@ diag(`should use print-style function`)

var nested struct {
l log.Logger
}
nested.l.Print(s) //@ diag(`should use print-style function`)
}

func fn3() (string, int) { return "", 0 }

0 comments on commit 3fe6ed0

Please sign in to comment.