golang / go

The Go programming language
https://go.dev
BSD 3-Clause "New" or "Revised" License
123.9k stars 17.65k forks source link

x/tools/go/analysis/passes/slog: False negitive when `error` type used as key. #65740

Open aDotInTheVoid opened 8 months ago

aDotInTheVoid commented 8 months ago

Go version

go version go1.22.0 linux/amd64

Output of go env in your module/workspace:

GO111MODULE=''
GOARCH='amd64'
GOBIN=''
GOCACHE='/home/alona/.cache/go-build'
GOENV='/home/alona/.config/go/env'
GOEXE=''
GOEXPERIMENT=''
GOFLAGS=''
GOHOSTARCH='amd64'
GOHOSTOS='linux'
GOINSECURE=''
GOMODCACHE='/home/alona/go/pkg/mod'
GONOPROXY=''
GONOSUMDB=''
GOOS='linux'
GOPATH='/home/alona/go'
GOPRIVATE=''
GOPROXY='https://proxy.golang.org,direct'
GOROOT='/home/alona/go/pkg/mod/golang.org/toolchain@v0.0.1-go1.22.0.linux-amd64'
GOSUMDB='sum.golang.org'
GOTMPDIR=''
GOTOOLCHAIN='auto'
GOTOOLDIR='/home/alona/go/pkg/mod/golang.org/toolchain@v0.0.1-go1.22.0.linux-amd64/pkg/tool/linux_amd64'
GOVCS=''
GOVERSION='go1.22.0'
GCCGO='gccgo'
GOAMD64='v1'
AR='ar'
CC='gcc'
CXX='g++'
CGO_ENABLED='1'
GOMOD='/tmp/goo/go.mod'
GOWORK=''
CGO_CFLAGS='-O2 -g'
CGO_CPPFLAGS=''
CGO_CXXFLAGS='-O2 -g'
CGO_FFLAGS='-O2 -g'
CGO_LDFLAGS='-O2 -g'
PKG_CONFIG='pkg-config'
GOGCCFLAGS='-fPIC -m64 -pthread -Wl,--no-gc-sections -fmessage-length=0 -ffile-prefix-map=/tmp/go-build3366501523=/tmp/go-build -gno-record-gcc-switches'

What did you do?

I wrote code that assumed slog methods worked like fmt.Printf, instead of talking Attr/key-value pairs:

package main

import "log/slog"

func main() {
        var x error
        slog.Error("The error is %v", x)
}

playground

Running go vet -slog ./main.go

What did you see happen?

go vet -slog reports no errors, but the key isn't present.

$ go vet -slog ./main.go
$ go run ./main.go
2024/02/16 00:50:48 ERROR The error is %v !BADKEY=<nil>

What did you expect to see?

go vet -slog ./main.go should report an error like ./main.go:7:32: slog.Error arg "x" should be a string or a slog.Attr (possible missing key or value).

Interestingly, if you change the type of x to int, the error fires as you'd expect.

package main

import "log/slog"

func main() {
        var x int
        slog.Error("The error is %v", x)
}
$ go vet -slog ./main.go
# command-line-arguments
# [command-line-arguments]
./main.go:7:32: slog.Error arg "x" should be a string or a slog.Attr (possible missing key or value)
$ go run ./main.go
2024/02/16 00:52:58 ERROR The error is %v !BADKEY=0
thanm commented 8 months ago

@jba per owners