profile
viewpoint
Dominik Honnef dominikh Consultant Germany https://dominik.honnef.co Long-time Go user, contributor, and author of many Go related tools, including staticcheck.

dominikh/filesize 73

filesize is a small ruby class for handling filesizes with both the SI and binary prefixes, allowing conversion from any size to any other size.

dominikh/go-augeas 19

Go bindings for augeas

dominikh/dmenu-ruby 5

A Ruby OOP wrapper around dmenu

issue commentdominikh/go-tools

Missing fmt.Sprintf format string errors

We should probably catch these as part of SA1006 (Printf with dynamic first argument and no further arguments) though.

dgryski

comment created time in 6 hours

issue commentgolang/go

runtime: emit better errors from checkptr

I'm torn between the two prefixes, both have their advantage; I'm slightly leaning towards "checkptr:", because then people might not wonder as much why unsafe reports errors when using the race detector and not otherwise. Definitely makes it easier to google for "checkptr".

Your suggestions definitely improve upon the current messages, and we'll have a whole cycle to bikeshed them to death :-)

dominikh

comment created time in 8 hours

issue openedgolang/go

runtime: emit better errors from checkptr

Currently, checkptr checks for four different kinds of mistakes; two of them concerning alignment, two of them concerning pointer arithmetic. However, it only emits two different kinds of errors, one per class of mistakes. It would be helpful to know which specific kind of mistake I made. Did I ignore alignment, or did I straddle multiple objects?

Furthermore, the errors themselves can be confusing. unsafe pointer conversion will point to a line of code that uses unsafe.Pointer conversion; it is not immediately obvious that these two uses of the word "unsafe" mean different things – checkptr really complains about potentially broken pointer conversions.

created time in 10 hours

issue commentetcd-io/bbolt

panic: runtime error: unsafe pointer conversion (Go 1.14)

The conversions to arrays of 0x7FFFFFF elements are clearly violating this rule, and the ones to maxAllocSize are probably invalid as well.

After looking into the checkptr code, re-reading https://github.com/golang/go/wiki/cgo#turning-c-arrays-into-go-slices and experimenting myself, it is my understanding that this isn't true per se. Specifically, there is a valid pattern of converting between two slices involving these huge arrays, namely

(*[0x7FFFFFF]Type2)(unsafe.Pointer(&theSlice[0]))[:length:length]

The overall value of this expression, if considered as a single unit, does not produce any pointers that straddle more than one object (given the correct value for length)

This pattern has in the past been preferred over constructing a reflect.SliceHeader from scratch. In particular, reflect.SliceHeader stores a uintptr, so strictly speaking, this would be invalid:

hdr := reflect.SliceHeader{...}
s := *(*[]T)(&hdr)

as both the construction of the header and the conversion to the slice type would have to occur as one.

I can't really speak to any of the code flagged here, though; most of these slices look bizarre, as does the use of &p.ptr.

klauspost

comment created time in 10 hours

issue openeddominikh/go-tools

staticcheck: extend SA5011 to detect out of bounds accesses

Similarly to flagging if x != nil { ... }; *x we could flag if len(x) != 0 { ... }; x[0] and if x != "" { ... }; x[0]

created time in 2 days

created tagdominikh/go-tools

tag2020.1.3

Staticcheck – a collection of static analysis tools for working with Go code

created time in 5 days

created tagdominikh/go-tools

tagv0.0.1-2020.1.3

Staticcheck – a collection of static analysis tools for working with Go code

created time in 5 days

push eventdominikh/go-tools

Dominik Honnef

commit sha 62483d1f91ed017411563e7808b9c71a2843861f

lint: don't store token.Pos in the cache The token.Pos stored in the cache will not be correct once we load it from the cache, because the fset will have changed. This would lead to bogus position information for unhandled linter directives.

view details

Dominik Honnef

commit sha 848115ef872c0263870b46f014c321c9fd5bf392

lint: deduplicate line ignores Account for analyses (U1000 specifically) that don't emit problems for both a package and its test variant.

view details

Dominik Honnef

commit sha 368adf81d5cb8838c02202d7802bac89ed015c25

doc: add 2020.1.3 release notes

view details

Dominik Honnef

commit sha 41b7168e8a453eed512e428156f9456c6b340a97

doc: update install instructions to refer to latest release

view details

Dominik Honnef

commit sha 52e1977958d64cc583dd65ab5efbe1d5627e61cb

doc: fix link to JSON formatter

view details

Dominik Honnef

commit sha 508b5eb18ee2f667ce06235ed383647038e2afc5

Version 2020.1.3

view details

push time in 5 days

push eventdominikh/go-tools

Dominik Honnef

commit sha 709e8b461c1be7861a110889599bcdd09677a272

doc: add 2020.1.3 release notes

view details

Dominik Honnef

commit sha 9b987539b3110a8065545705f2f5c97ac136bf4b

doc: update install instructions to refer to latest release

view details

Dominik Honnef

commit sha c702d0a1c8d58bb55e039d028e92ae714040936c

doc: fix link to JSON formatter

view details

push time in 5 days

push eventdominikh/go-tools

Dominik Honnef

commit sha 5bf9fe98906dff156bdb9de7b4e393a7ef60c242

lint: don't store token.Pos in the cache The token.Pos stored in the cache will not be correct once we load it from the cache, because the fset will have changed. This would lead to bogus position information for unhandled linter directives.

view details

Dominik Honnef

commit sha 37fcbfbb57c58f156decf06c733719a8f3005045

lint: deduplicate line ignores Account for analyses (U1000 specifically) that don't emit problems for both a package and its test variant.

view details

push time in 6 days

push eventdominikh/go-tools

Dominik Honnef

commit sha de7feb5aefe2d2eeddea0884056c93c969523f4f

doc: update 2020.1 release notes to include minor versions

view details

push time in 6 days

created tagdominikh/go-tools

tagv0.0.1-2020.1.2

Staticcheck – a collection of static analysis tools for working with Go code

created time in 6 days

created tagdominikh/go-tools

tag2020.1.2

Staticcheck – a collection of static analysis tools for working with Go code

created time in 6 days

push eventdominikh/go-tools

Dominik Honnef

commit sha d3ed47d218fc714d1718749c1a3b3b021e8d703a

Version 2020.1.2

view details

push time in 6 days

push eventdominikh/go-tools

Dominik Honnef

commit sha b450aabdba48c6dcee14a51a421227a006199865

Version 2020.1

view details

push time in 6 days

created tagdominikh/go-tools

tagv0.0.1-2020.1.1

Staticcheck – a collection of static analysis tools for working with Go code

created time in 6 days

created tagdominikh/go-tools

tag2020.1.1

Staticcheck – a collection of static analysis tools for working with Go code

created time in 6 days

created tagdominikh/go-tools

tag2020.1

Staticcheck – a collection of static analysis tools for working with Go code

created time in 6 days

created tagdominikh/go-tools

tagv0.0.1-2020.1

Staticcheck – a collection of static analysis tools for working with Go code

created time in 6 days

create barnchdominikh/go-tools

branch : release.2020.1

created branch time in 6 days

push eventdominikh/go-tools

Dominik Honnef

commit sha e1176e28bfa984885b7540fbd3e703935c128fd9

doc: minor improvements to 2020.1 release notes

view details

push time in 6 days

push eventdominikh/go-tools

Dominik Honnef

commit sha 633c4fe08760811a1220663a35fbdb10360ba7a4

deprecated: update for Go 1.13 and 1.14 Also fix two incorrectly formatted entries for the syscall package.

view details

push time in 7 days

push eventdominikh/go-tools

Dominik Honnef

commit sha 012fffb640953dd9dddd6372e4943454a6ba56b2

Add 2020.1 release notes

view details

Dominik Honnef

commit sha 6f2dd728b89edb625de038f10037bff4e4e4c5de

dist: use -trimpath when building binaries Closes gh-470

view details

Dominik Honnef

commit sha fc5f6e32c5b39bdeef0e33ab60e6f63be7d7e7c7

dist: build binaries for some ARM platforms

view details

Dominik Honnef

commit sha 7de7fff594cd49f4db947c6482993696f1778ac4

Add documentation to more checks

view details

Dominik Honnef

commit sha fa025e8da7d7364ff99658ed5009a8dd8f207f1d

Make minor improvements on release notes

view details

Dominik Honnef

commit sha 6f7bccf949c95770b7836595417ff1f601d67088

Be consistent about capitalizing Staticcheck

view details

Dominik Honnef

commit sha 15a7e1496f87e1255d4d7c5c6c24c1daa6c9b879

internal/renameio, internal/robustio: import upstream changes This imports the following commits from upstream: commit a38a917aee626a9b9d5ce2b93964f586bf759ea0 all: remove the nacl port (part 1) commit 9cce08d72470eb6ae2a2870bb9c70d1893441b0f cmd/go/internal/renameio,runtime: avoid leaking temp directory in test commit 033299fab66b08d434be30e05d11f7db63efa71c all: add a space before +build in build tag comments commit 81c6bac06f5f8a45f0837cb42b2793df64de08a7 cmd/go/internal/robustio: extend filesystem workarounds to darwin platforms

view details

push time in 7 days

delete branch dominikh/go-tools

delete branch : tmp

delete time in 7 days

push eventdominikh/go-tools

Dominik Honnef

commit sha 15a7e1496f87e1255d4d7c5c6c24c1daa6c9b879

internal/renameio, internal/robustio: import upstream changes This imports the following commits from upstream: commit a38a917aee626a9b9d5ce2b93964f586bf759ea0 all: remove the nacl port (part 1) commit 9cce08d72470eb6ae2a2870bb9c70d1893441b0f cmd/go/internal/renameio,runtime: avoid leaking temp directory in test commit 033299fab66b08d434be30e05d11f7db63efa71c all: add a space before +build in build tag comments commit 81c6bac06f5f8a45f0837cb42b2793df64de08a7 cmd/go/internal/robustio: extend filesystem workarounds to darwin platforms

view details

push time in 7 days

create barnchdominikh/go-tools

branch : tmp

created branch time in 7 days

issue closeddominikh/go-tools

Vendor our dependencies

At the least we'll want to vendor github.com/kisielk/gotool – our behaviour depends too much on having an up-to-date version of gotool installed.

We should also vendor those parts of x/tools that we aren't going to rewrite/fork.

closed time in 8 days

dominikh

issue commentdominikh/go-tools

Vendor our dependencies

Thanks to Go modules, this is no longer relevant.

dominikh

comment created time in 8 days

issue commentdominikh/go-tools

staticcheck verbose mode

What's the desired purpose of such a flag? Is it to verify that all files in a project were analyzed? An ordinary print what we're doing flag likely wouldn't fulfill that requirement, because staticcheck heavily relies on caching and may not look at all files. We could of course print a list of files we would have to look at were the cache empty, but such output would not qualify as "verbose output" in my opinion.

Printing which files belong to a given build may not be staticcheck's job at all. One could argue that this constitutes a different kind of analysis, one that can be implemented with the appropriate calls to go list.

disconnect3d

comment created time in 9 days

issue commentdominikh/go-tools

Compiler error "./lift.go:623:25: constant 2147483648 overflows int" on 32-bit platforms

Sorry for breaking the build. Your fix was correct, but I've opted for a more explicit one.

tcmitchell

comment created time in 10 days

push eventdominikh/go-tools

Dominik Honnef

commit sha b7853fc02a7714b1ab246401febf15b46095450e

ir: fix build on 32-bit platforms Closes gh-698

view details

push time in 10 days

issue closeddominikh/go-tools

Compiler error "./lift.go:623:25: constant 2147483648 overflows int" on 32-bit platforms

There is an integer overflow on 32-bit platforms like Raspberry Pi. To recreate the error:

$ cd go-tools/ir
$ GOOS=linux GOARCH=arm GOARM=7 go build
# honnef.co/go/tools/ir
./lift.go:623:25: constant 2147483648 overflows int

To make it compile I did the following, although I don't know if it's the right fix:

diff --git a/ir/lift.go b/ir/lift.go
index 977c6e3..aa1fe87 100644
--- a/ir/lift.go
+++ b/ir/lift.go
@@ -620,7 +620,7 @@ func transitiveClosure(fn *Function) *closure {
                        n := interval(l<<numBits | start)
                        c.reachables = append(c.reachables, n)
                } else {
-                       n1 := interval(1<<31 | start)
+                       n1 := interval(1<<31 | interval(start))
                        n2 := interval(end)
                        c.reachables = append(c.reachables, n1, n2)
                }

The tests pass with that change.

closed time in 10 days

tcmitchell

issue commentdominikh/go-tools

staticcheck: find nonsensical checks for sql.ErrNoRows and alike

On a more general level, staticcheck could have a list of “exclusive” errors, which are returned only from one or two functions, and flag all cases where programmers await them in the wrong places. Like:

Not unless we can detect which functions return which errors, because a user could write their own function that returns *xml.SyntaxError.

ainar-g

comment created time in 14 days

issue closeddominikh/go-tools

U1000 flags function that's only unused on current GOOS

staticcheck flagged a U1000 unused function on listPortsNetstat of https://github.com/tailscale/tailscale/blob/master/portlist/netstat.go .

For GOOS=linux, staticcheck is correct, that function is unused. However, it's used for all other GOOS values (notably darwin and windows), via build-tagged source files (https://github.com/tailscale/tailscale/blob/master/portlist/portlist_darwin.go , https://github.com/tailscale/tailscale/blob/master/portlist/portlist_windows.go , and https://github.com/tailscale/tailscale/blob/master/portlist/portlist_other.go)

I considered fixing this by adding a // +build !linux to netstat.go. This is strictly correct, but it means that we can't run the netstat unit tests on GOOS=linux, even though it provides valuable test coverage on our main development machines.

IMO, it would be better if staticcheck could figure out that code is used on some platform, even if it's unused on the current one.

Version infos for various tools:

$ staticcheck -debug.version
staticcheck 2019.2.3

Compiled with Go version: go1.13.7
Main module:
	honnef.co/go/tools@v0.0.1-2019.2.3 (sum: h1:3JgtbtFHMiCmsznwGVTUWbgGov+pVqnlf1dEJTNAXeM=)
Dependencies:
	github.com/BurntSushi/toml@v0.3.1 (sum: h1:WXkYYl6Yr3qBf1K79EBnL4mak0OimBfB0XUf9Vl28OQ=)
	golang.org/x/tools@v0.0.0-20190621195816-6e04913cbbac (sum: h1:MQEvx39qSf8vyrx3XRaOe+j1UDIzKwkYOVObRgGPVqI=)

$ go version
go version go1.13.7 linux/amd64

$ go env
GO111MODULE=""
GOARCH="amd64"
GOBIN=""
GOCACHE="/home/dave/.cache/go-build"
GOENV="/home/dave/.config/go/env"
GOEXE=""
GOFLAGS=""
GOHOSTARCH="amd64"
GOHOSTOS="linux"
GONOPROXY=""
GONOSUMDB=""
GOOS="linux"
GOPATH="/home/dave/hack/go"
GOPRIVATE=""
GOPROXY="https://proxy.golang.org,direct"
GOROOT="/usr/lib/go"
GOSUMDB="sum.golang.org"
GOTMPDIR=""
GOTOOLDIR="/usr/lib/go/pkg/tool/linux_amd64"
GCCGO="gccgo"
AR="ar"
CC="gcc"
CXX="g++"
CGO_ENABLED="1"
GOMOD="/home/dave/tail/oss/go.mod"
CGO_CFLAGS="-g -O2"
CGO_CPPFLAGS=""
CGO_CXXFLAGS="-g -O2"
CGO_FFLAGS="-g -O2"
CGO_LDFLAGS="-g -O2"
PKG_CONFIG="pkg-config"
GOGCCFLAGS="-fPIC -m64 -pthread -fmessage-length=0 -fdebug-prefix-map=/tmp/go-build794878447=/tmp/go-build -gno-record-gcc-switches"

<!-- Please make sure to include the following information in your issue report:

  • The output of 'staticcheck -version'
  • The output of 'staticcheck -debug.version' (it is fine if this command fails)
  • The output of 'go version'
  • The output of 'go env'
  • Exactly which command you ran
  • Output of the command and what's wrong with the output
  • Where we can read the code you're running staticcheck on (GitHub repo, link to playground, code embedded in the issue, ...) -->

closed time in 15 days

danderson

issue commentdominikh/go-tools

U1000 flags function that's only unused on current GOOS

I considered fixing this by adding a // +build !linux to netstat.go. This is strictly correct, but it means that we can't run the netstat unit tests on GOOS=linux, even though it provides valuable test coverage on our main development machines.

You could move just that function to a new file, with the appropriate build tag. The only other alternative right now is using //lint:ignore.

In general, this is a known issue (#48) and affects any use of build tags.

IMO, it would be better if staticcheck could figure out that code is used on some platform, even if it's unused on the current one.

This is not viable with the current infrastructure, because we would have to analyze packages with all possible combinations of build tags (GOOS, GOARCH, custom build tags), and the amount of combinations is simply too large (yes, that contradicts what I said in #48, I didn't know any better at the time.)

I am currently planning a redesign of the unused check to address some of its other issues. I'll keep the build tag issue in mind and try to design something that handles build tags better. Failing that, the alternative would be to explicitly specify all desired combinations of build tags. This might also benefit other checks that depend on the current platform, such as alignment checks for atomics.

I'm going to close this issue in favour of the existing one.

danderson

comment created time in 15 days

issue openeddominikh/go-tools

purity: update list of stdlib functions

The purity check doesn't detect a number of pure stdlib functions. For example, a lot of functions in strings defer to the internal/bytealg package, which is implemented in assembly on several architectures.

In the past, our hard-coded list of pure functions only covered a subset of stdlib, the subset that didn't get detected automatically. We should probably make the list exhaustive, both to be safe against future changes to the stdlib, as well as to speed up its analysis.

created time in 16 days

issue commentgolang/go

Please allow empty go files

This change would require changing the language specification as well as multiple build systems, libraries for processing Go code, and existing tooling that expects to find package declarations in Go files. That seems vastly out of proportion for something that can be better solved by adding a // +build ignore directive at the top of the file, or finding a new key combination that doesn't comment out the package declaration.

kstenerud

comment created time in 17 days

issue openeddominikh/go-tools

simple: simplify allocation followed by assignment

Simplify

x := new(T)
*x = T{...}

to

x := &T{...}

unless the struct initializer references x.

created time in 18 days

issue commentdominikh/go-tools

simple: replace WriteString(fmt.Sprint*(...)) with fmt.Fprint*

One concern with this is consistency. Say someone wrote this:

buf.WriteString("static string")
buf.WriteString(fmt.Sprintf(...))

should the second call be replaced with an Fprintf? Personally I'd argue that using Fprintf for the second call would be a bad change, breaking consistency of the code.

We could check surrounding code (e.g. the entire function) for buf.WriteString calls that do not use Sprintf, and bail from the check. But I am not convinced this will work perfectly.

Maybe this check belongs in the quickfix category, a set of purely optional code changes that is only surfaced in editors (via gopls), and not on the CLI. I will have to think more about this.

buyology

comment created time in 19 days

push eventdominikh/go-tools

Dominik Honnef

commit sha 4d6348fedd3596c1982c5a5919b6858e0737382d

ir: remove Comment fields

view details

Dominik Honnef

commit sha 90dfb6335095e0d50c9a4ad28e75d12d41ab8cd8

ir: avoid allocating phis/sigmas we can easily prove are dead

view details

Dominik Honnef

commit sha 3b54dc1d61e2974391a12711ac070b5fa12a8cf6

ir: fix documentation of Package.Functions The list does not actually include anonymous functions.

view details

Dominik Honnef

commit sha 5f60cb41390985645e204892efb29754c27607cc

ir: don't allocate space for builder state for body-less functions We primarily use ir in the context of go/analysis and the buildir pass, which creates a new IR program for each package under analysis. For large code bases, this creates millions of instances of Function, created from export data. These functions do not need any of the transient builder state to be built. Moving this state into a separate struct that gets allocated conditionally saves approximately 50% of space for these repeated allocations, or a reduction of 10 GB when analysing cockroachdb.

view details

Dominik Honnef

commit sha b4d1e7ffb09f1e4a80f23ba5eb678586f5e6edad

ir: don't keep Sigmas or Phis alive because of DebugRefs

view details

Dominik Honnef

commit sha 7d8abf88f488ecdeba00184f8da504d755195b91

ir: don't leave useless RunDefers in functions without allocs

view details

Dominik Honnef

commit sha 0becd241c5ce4191884363530430c5ff70904073

ir: only loads count as future uses of allocs

view details

Dominik Honnef

commit sha f807b603c818203b7788e7f375d84346812187bc

Revert "ir: don't keep Sigmas or Phis alive because of DebugRefs" This reverts commit b4d1e7ffb09f1e4a80f23ba5eb678586f5e6edad. Some analyses depend on mapping from AST to IR. SA4006 in particular depends on this to find pointless assignments. If we eliminate the value and the associated DebugRef, then we have no way of telling if he assigned value is ever read.

view details

Dominik Honnef

commit sha 104ba5a2aac5d20ec6b404f18f67569e8fa181b2

staticcheck: in SA4006, follow through sigmas and phis to find real usage

view details

push time in 20 days

issue openeddominikh/go-tools

Do less work when we have cached results

Right now, we process the dependency graph in a single pass, bottom up. For example, for staticcheck A, where A has two dependencies B and C (A -> B, A -> C), we will first process B and C before processing A. Processing B and C may either mean loading them from source and analysing them, or loading them from export data and cached facts. Once we process A, we can be sure that B and C have been fully processed.

However, this bottom up approach is wasteful when none of A, B, or C have changed, and we have cached results for A. In that case, we only need B's and C's checksum, to confirm A's checksum and load A's cached results. We need neither facts nor export data. When checking large code bases, we may spend multiple seconds and hundreds of megabytes of memory needlessly loading data.

Instead, the first pass, when encountering a dependency that hasn't changed, should only do enough work to compute the checksum. Loading other data should be delayed until a dependent explicitly requests it.

created time in 20 days

issue openeddominikh/go-tools

Don't print overly nested errors for common failure conditions

Right now, we print the following kind of error for a missing transitive dependency:

-: could not analyze dependency sandbox/bar of sandbox/foo: 
	could not analyze dependency sandbox/baz of sandbox/bar: 
	could not analyze dependency missing of sandbox/baz: 
	../../../../../sandbox/baz/baz.go:3:8: cannot find package "missing" in any of:
	/usr/lib/go/src/missing (from $GOROOT)
	/home/dominikh/prj/src/missing (from $GOPATH) (compile)

This is hard to grasp for our users (and, frankly, myself).

Compare this with the much more succinct output of go build:

../../../../../sandbox/baz/baz.go:3:8: cannot find package "missing" in any of:
	/usr/lib/go/src/missing (from $GOROOT)
	/home/dominikh/prj/src/missing (from $GOPATH)

We should use the same format. Displaying the nested structure of errors should either be limited to less common errors (which may well indicate bugs in staticcheck), or be hidden behind a debug flag.

created time in 21 days

issue commentdominikh/go-tools

Staticcheck execution not picking up vendor directory.

  • What's the result of go list -e -json -test -compiled ./config? (You may have to redact sensitive information or let me know in private).

  • Do go build ./config and go test ./config work? How do you normally build the code?

jackdw-concur

comment created time in 21 days

issue commentgolang/go

proposal: cmd/vet: flag accidental integer division inside float casts

I also note that staticcheck doesn't check this either.

Correct, I share your concern about false positives.

Staticcheck has a related check, however, which flags math.Ceil(float64(<integer expression>)) (and identically for math.Floor). This catches one of the common instances of the mistake, with no real false positives to my knowledge. However, that check likely doesn't meet vet's frequency criterion.

jktomer

comment created time in 21 days

issue openeddominikh/go-tools

Flag `continue` as final statement in block

for cond1 {
  // code here
  if cond2 {
    continue
  }
}

The continue is either useless, or indicative of a bug (such as missing code, or meaning to continue an outer loop). Might become its own check, or get folded into SA4011.

created time in 22 days

issue commentdominikh/go-tools

honnef.co/go/tools/unused: TestAll fails with Go 1.14 beta1

This was fixed in 7398d928b10cbeeef873ee02a66742af75a1d4e9 (coincidentally) when we updated our dependency on golang.org/x/tools. The commit in golang.org/x/tools that seems to have fixed this failure is golang/tools@db0687cefd95dc155728a53f4a5416d1aa1bcf1f.

I am planning to release Staticcheck 2020.1 shortly before Go 1.14 releases. In the meantime, you should be able to apply the following patch:

diff --git a/go.mod b/go.mod
index 9ae497b9..7d4e3801 100644
--- a/go.mod
+++ b/go.mod
@@ -8,5 +8,5 @@ require (
        github.com/kisielk/gotool v1.0.0
        github.com/rogpeppe/go-internal v1.3.0
        golang.org/x/mod v0.0.0-20190513183733-4bf6d317e70e
-       golang.org/x/tools v0.0.0-20190826182127-07722704da13
+       golang.org/x/tools v0.0.0-20191022074931-774d2ec196ee
 )
eclipseo

comment created time in 22 days

issue closeddominikh/go-tools

honnef.co/go/tools/unused: TestAll fails with Go 1.14 beta1

Fedora Rawhide with Go 1.14 beta1:

honnef.co/go/tools/unused
--- FAIL: TestAll (0.32s)
    unused_test.go:143: /builddir/build/BUILD/go-tools-2019.2.3/_build/src/honnef.co/go/tools/unused/testdata/src/tests/tests.go:3:6: unexpected: fn
FAIL
exit status 1
FAIL	honnef.co/go/tools/unused	0.331s

closed time in 22 days

eclipseo

issue commentdominikh/go-tools

Tool idea: convert strftime format to time.Parse format

@fortytw2 SA1002 detects definitely wrong format strings, by seeing whether time.Parse accepts the format or not. But like you already said, this won't and can't catch things like 2007.

This issue is about adding a new check, which detects format strings that are valid strftime format strings, and provides an automatic fix to convert them into Go's format.

dominikh

comment created time in 22 days

issue openeddominikh/go-tools

staticcheck: log.Fatal("x:", err) -> log.Fatalln

log.Fatal will not add spaces between its arguments, but the presence of a colon suggests that a space was desired. See if we run into any false positives.

created time in 23 days

issue commentdominikh/go-tools

Tool idea: convert strftime format to time.Parse format

Possibly nasty, possibly genius idea: detect calls such as time.Parse("%m/%d/%Y", "...") and provide suggested fixes (usable via gopls) that converts the format string into actual Go format. That way we don't need to provide an external tool, and get integration with editors for free. On the downside, virtually nobody would ever write a time.Parse call with a strftime format in the first place. And I'm not sure we want to encourage people to do so, either.

/cc @stamblerre

dominikh

comment created time in 23 days

issue commentdominikh/go-tools

staticcheck: SA4006 false-negative when a defer is used

From an implementation point of view: the anonymous function refers to err, which means that the variable can't be lifted into registers; it'll be an allocation. The way we check for unread assignments is by checking whether the register gets read.

For allocations, this isn't nearly as trivial (nor solvable for all cases.) For example, err could be aliased and read via the alias, or g could panic, leading to the deferred function reading the value. We could handle some of these cases (e.g. handle allocations that can't be aliased), but for your concrete example, we still couldn't claim that err is unread, due to the possibility of g panicking and thus reading that value.

ainar-g

comment created time in 23 days

issue commentgolang/go

x/tools/gopls: reduce CPU usage

I would even argue that not all diagnostics should run at the same rate (say, muir's 500ms). Some analyses (particularly in staticcheck) are much more expensive than others, and also point out larger bugs than what can be affected by typing 5 characters. A simple differentiator could be those analyses that work purely on the AST, and those that rely on an IR (go/ssa, staticcheck's IR). Building the IR form is an expensive operation.

stamblerre

comment created time in 24 days

GollumEvent

issue openeddominikh/go-tools

Adopt gcvis

gcvis is no longer maintained, and it hasn't kept up with format changes in the output of the scavenger. It's a useful tool that I rely on, it's small and self-contained, and licensed under a BSD 2-clause license. Let's maintain a fork of gcvis.

created time in a month

issue commentgolang/go

x/tools/gopls: stylistic diagnostics emitted for generated code

but I guess what you're saying is that we can also rely on staticcheck to make a reasonable decision about if a diagnostic is worth showing in a generated file?

That is correct.

muirdm

comment created time in a month

issue closeddominikh/go-tools

stylecheck: ignore method receiver name matches from generated files

Command run: staticcheck -checks 'all,-ST1000' -unused.whole-program ./...

Output line in question:

internal/bot/access_level.go:39:22: methods on the same type should have the same receiver name (seen 3x "a", 1x "i") (ST1016)

Repo is: https://github.com/hortbot/hortbot

This lint message is technically correct, however the receiver name conflict comes from a file generated by stringer (which does not allow you to override the receiver name; a separate issue I may file on the Go issue tracker).

I think it's a good idea to throw away names discovered in generated files, as linter errors from generated files in general are thrown away already. The method receiver name check is unique in that a generated file's names can potentially cause a mismatch message in non-generated files.

Version/Go info (though I don't think it's helpful in this case):

staticcheck 2019.2.3

Compiled with Go version: go1.13.7
Main module:
	honnef.co/go/tools@v0.0.1-2019.2.3 (sum: h1:3JgtbtFHMiCmsznwGVTUWbgGov+pVqnlf1dEJTNAXeM=)
Dependencies:
	github.com/BurntSushi/toml@v0.3.1 (sum: h1:WXkYYl6Yr3qBf1K79EBnL4mak0OimBfB0XUf9Vl28OQ=)
	golang.org/x/tools@v0.0.0-20190621195816-6e04913cbbac (sum: h1:MQEvx39qSf8vyrx3XRaOe+j1UDIzKwkYOVObRgGPVqI=)
go version go1.13.7 linux/amd64
GO111MODULE=""
GOARCH="amd64"
GOBIN=""
GOCACHE="/home/jake/.cache/go-build"
GOENV="/home/jake/.config/go/env"
GOEXE=""
GOFLAGS=""
GOHOSTARCH="amd64"
GOHOSTOS="linux"
GONOPROXY=""
GONOSUMDB=""
GOOS="linux"
GOPATH="/home/jake/go"
GOPRIVATE=""
GOPROXY="https://proxy.golang.org,direct"
GOROOT="/usr/lib/go"
GOSUMDB="sum.golang.org"
GOTMPDIR=""
GOTOOLDIR="/usr/lib/go/pkg/tool/linux_amd64"
GCCGO="gccgo"
AR="ar"
CC="gcc"
CXX="g++"
CGO_ENABLED="1"
GOMOD="/home/jake/zikaeroh/hortbot/hortbot/go.mod"
CGO_CFLAGS="-g -O2"
CGO_CPPFLAGS=""
CGO_CXXFLAGS="-g -O2"
CGO_FFLAGS="-g -O2"
CGO_LDFLAGS="-g -O2"
PKG_CONFIG="pkg-config"
GOGCCFLAGS="-fPIC -m64 -pthread -fmessage-length=0 -fdebug-prefix-map=/tmp/go-build161958862=/tmp/go-build -gno-record-gcc-switches"

closed time in a month

zikaeroh

issue commentdominikh/go-tools

stylecheck: ignore method receiver name matches from generated files

This was fixed in https://github.com/dominikh/go-tools/commit/27a660a4b58b40c032f1dd332053c0e4c537496c and will be part of the next release of staticcheck.

zikaeroh

comment created time in a month

issue commentgolang/go

x/tools/gopls: stylistic diagnostics emitted for generated code

For people watching at home: AFAIK gopls has no notion of hiding diagnostics in generated files, but the checks in staticcheck use a special analysis (honnef.co/go/tools/facts.Generated) to detect generated files. As such, using staticcheck's analyses in gopls (or any other runner) still benefits from the detection of generated files. Each analysis itself gets to decide whether a diagnostic should be hidden from generated files or not, without the runner's involvement.

muirdm

comment created time in a month

issue commentdominikh/go-mode.el

Support rename by gopls

I'd rather not see us shell out to the gopls CLI. People should indeed use lsp-mode (or similar).

Also, wasn't goimports updated to support modules a while ago?

on99

comment created time in a month

issue commentgolang/go

x/tools/gopls: stylistic diagnostics emitted for generated code

The issue here seems to be that your "code generated by" comment doesn't match the agreed upon format, nor any of the explicit exceptions that staticcheck handles. See https://github.com/golang/go/issues/13560 and https://github.com/golang/go/issues/13560#issuecomment-277804473 in particular.

muirdm

comment created time in a month

GollumEvent

issue commentdominikh/go-tools

staticcheck: flag string(int)

You meant to link to golang/go#32479, not golang/go#4483.

As for adding this check to staticcheck, I'll wait and see how well its integration with go vet will go. There's still the chance that it will flag too much code and that the spec change won't be made, after all. Personally, I am torn on whether string(int) is a good idea or not.

ainar-g

comment created time in a month

issue openeddominikh/go-tools

SA4015: more wrong float math

Seen this original code in the wild: int(math.Ceil(float64(gap / 2))) (for var gap int) – staticcheck pointed out that the call to math.Ceil was pointless, so the code got changed to int(float64(gap / 2)), but the code very likely was supposed to read int(math.Ceil(float64(gap) / 2)).

created time in a month

pull request commentolekukonko/tablewriter

Remove call to math.Ceil.

Note that int(float64(gap / 2)) is the same as int(gap / 2) which is the same as gap / 2. Are you sure you didn't mean float64(gap) / 2? int(math.Ceil(float64(gap) / 2)) would actually make sense.

bogosj

comment created time in a month

issue openeddominikh/go-tools

SA3000: improve message

SA3000 currently prints

TestMain should call os.Exit to set exit code

but it doesn't say what the exit code should be. Explicitly state that TestMain must exit with the value returned by Run.

created time in a month

Pull request review commentdgraph-io/ristretto

Sets with TTL

 func TestCacheMetricsClear(t *testing.T) { 	c.Metrics = nil 	c.Metrics.Clear() }++func TestMain(m *testing.M) {+	// Set bucketSizeSecs to 1 to avoid waiting too much during the tests.+	bucketDurationSecs = 1+	m.Run()+	os.Exit(0)

You are supposed to exit with the return value of m.Run, so that the exit status of the test binary reflects whether tests have passed or failed.

But the whole TestMain function can probably be replaced with a func init() { bucketDurationSecs = 1 } in cache_test.go

martinmr

comment created time in a month

issue commentdominikh/go-tools

Unused may report stale results

First actual problem: in an analysis, the only way to obtain a package's dependencies is via types.Package. Which means that we have no way of passing in a package's dependents. But we need our dependents to be able to import their package facts.

dominikh

comment created time in a month

issue commentdominikh/go-tools

Unused may report stale results

One nuisance is that we cannot express "package A uses object B.O" as an object fact. Object facts need to concern objects from the package under analysis, and the same object fact may not exist twice – that is, two packages can't both export an object fact saying that B.O is used".

However, we should be able to use package facts instead, i.e. a single fact on package A listing all the objects that it uses. We'd just have to take care of serializing object identifiers ourselves instead of relying on the analysis runner.

dominikh

comment created time in a month

issue commentdominikh/go-tools

Unused may report stale results

For analyses that aren't unused, we traverse the dependency graph in a DFS, recording and using facts. If package B depends on package A, then we have the graph B -> A, and A is processed before B. When a dependency's code changes, all dependents have to be analyzed again, because facts go stale.

unused could be expressed as the same problem but in the reverse direction. Since we're interested in dependents using identifiers, we have the dependent graph A -> B, where we process B before A, and where B contributes "identifier is being used" information towards A. When a dependent's code changes, all dependencies have to be analyzed again. For unused's non-global mode, we could optimize this to only consider test dependents, because exported identifiers are always used, and only tests can contribute to the use of unexported identifiers.

Unless I'm missing something obvious, this should allow us to fit neatly into the go/analysis framework, with the only oddity being that we need a second runner operating in reverse order. Other than that, this should be a normal, modular analysis.

dominikh

comment created time in a month

issue commentdominikh/go-tools

stylecheck: (optional?) check for different names used for the same, aliased type in the same scope

So, this would definitely have to be optional, and we'd have to carefully consider how to apply the check. For example, we cannot simply flag function bodies that use multiple aliases of the same type; different aliases may have different semantic meaning (but not enough so to justify distinct types).

The specific case of literals and assignment, like your return example, could probably be flagged. But it'd still need to be optional. And as always, people are prone to accidentally turning on optional checks, so we'll have to evaluate how much harm the check could do.

ainar-g

comment created time in a month

push eventdominikh/go-tools

Jeff Hodges

commit sha 2774002210e8cbf35b5445a3805e6f173c6bec1f

facts: fix detection of goyacc generated files The "Code generated by" comment includes the optional arguments passed to goyacc. Closes: gh-677 Closes: gh-678 [via git-merge-pr]

view details

push time in a month

PR closed dominikh/go-tools

correct goyacc generated file detection

Fixes #677

+4 -0

3 comments

1 changed file

jmhodges

pr closed time in a month

issue closeddominikh/go-tools

SA4006 is documented as not occuring in goyacc code, but is

Running staticcheck github.com/vitessio/vitess/go/vt/sqlparser will get you errors about SA40006 in github.com/vitessio/vitess/go/vt/sqlparser/sql.go. However, that sql.go is generated by goyacc which is supposed to be ignored as of: https://staticcheck.io/changes/2019.2

I tried installing staticcheck both with and without GO111MODULE on, and there didn't seem to be a difference.

$  staticcheck -version
staticcheck (no version)
$  staticcheck -debug.version
staticcheck (no version)

Compiled with Go version: go1.13.6
Built without Go modules
$  go version
go version go1.13.6 darwin/amd64
$  go env
GO111MODULE=""
GOARCH="amd64"
GOBIN=""
GOCACHE="/Users/jmhodges/Library/Caches/go-build"
GOENV="/Users/jmhodges/Library/Application Support/go/env"
GOEXE=""
GOFLAGS=""
GOHOSTARCH="amd64"
GOHOSTOS="darwin"
GONOPROXY=""
GONOSUMDB=""
GOOS="darwin"
GOPATH="/Users/jmhodges"
GOPRIVATE=""
GOPROXY="https://proxy.golang.org,direct"
GOROOT="/usr/local/Cellar/go/1.13.6/libexec"
GOSUMDB="sum.golang.org"
GOTMPDIR=""
GOTOOLDIR="/usr/local/Cellar/go/1.13.6/libexec/pkg/tool/darwin_amd64"
GCCGO="gccgo"
AR="ar"
CC="clang"
CXX="clang++"
CGO_ENABLED="1"
GOMOD="/Users/jmhodges/src/github.com/vitessio/vitess/go.mod"
CGO_CFLAGS="-g -O2"
CGO_CPPFLAGS=""
CGO_CXXFLAGS="-g -O2"
CGO_FFLAGS="-g -O2"
CGO_LDFLAGS="-g -O2"
PKG_CONFIG="pkg-config"
GOGCCFLAGS="-fPIC -m64 -pthread -fno-caret-diagnostics -Qunused-arguments -fmessage-length=0 -fdebug-prefix-map=/var/folders/5n/04tgfq3d2616vmydv89kfkq00000gn/T/go-build243029850=/tmp/go-build -gno-record-gcc-switches -fno-common"

<!-- Please make sure to include the following information in your issue report:

  • The output of 'staticcheck -version'
  • The output of 'staticcheck -debug.version' (it is fine if this command fails)
  • The output of 'go version'
  • The output of 'go env'
  • Exactly which command you ran
  • Output of the command and what's wrong with the output
  • Where we can read the code you're running staticcheck on (GitHub repo, link to playground, code embedded in the issue, ...) -->

closed time in a month

jmhodges

pull request commentdominikh/go-tools

correct goyacc generated file detection

Ah, command line flags. Fun. Thank you!

jmhodges

comment created time in a month

pull request commentdominikh/go-tools

correct goyacc generated file detection

Can you show me the actual Code generated by... comment you're seeing in your files, as well as point me to the specific variant of goyacc you're using? Because when I added handling of goyacc, https://github.com/dominikh/go-tools/pull/678/files#diff-0a10453e20c877702d4fd624982381dcR50 was sufficient.

jmhodges

comment created time in a month

issue commentdominikh/go-tools

//lint:ignore U1000 should consider that used, not just silence one message

//lint:ignore is purely a post-processing step, filtering the list of reported problems, which is why you're seeing the current behavior.

I'm not convinced that it is worth implementing extra logic in unused for this when var _ exists and can be documented.

tv42

comment created time in a month

issue commentkubernetes/kubernetes

[Flaky test] staticcheck reports used functions as unused

If this is sporadic then it's probably https://github.com/dominikh/go-tools/issues/642 -- there's a fix for that on master (https://github.com/dominikh/go-tools/commit/a9480a3ec3bcedcf32d00a67bb464c058ba03281) but it's not part of a release yet.

liggitt

comment created time in a month

issue commentdominikh/go-tools

False positive triggered by cgo pre-processed code in the go build cache

Note that where your build cache is located at isn't actually relevant for this false positive. It would occur even with a build cache located outside of the repository.

When checking packages that use cgo, we're really checking the output of the cgo preprocessor (as before preprocessing, the code isn't technically valid Go). In the normal case, when we find an issue in a generated file, we report the error in the original file – that's what the //line directives are for: so that the compiler and tools can report useful errors that don't point into the preprocessed files.

The reason we're reporting the error in the generated file, by the looks of it, is that the error technically occurs "before" (or rather exactly on) the first //line directive, so we don't have a valid mapping to the source file yet. We should probably look into fixing that. Ideally we never report errors in the build cache, and always in the source file.

The rest of your analysis is correct. Go places the //line directive in an unfortunate manner, and we should work around that in ST1000.

jvmatl

comment created time in a month

issue commentdominikh/go-tools

Does this code have any effect?

Looks like dead code that can be removed.

jvmatl

comment created time in a month

issue openeddominikh/go-tools

Unused may report stale results

Our analysis runner doesn't load packages from source if it doesn't have to, e.g. because they haven't changed. In those cases, it uses export data and cached problems/facts. However, this breaks unused in whole-program mode, because changing one package may affect the list of unused identifiers in another package.

  1. have a package A define an exported identifier, have package B use the identifier
  2. run staticcheck -unused.whole-program on A and B
  3. modify B to remove the use of A's identifier
  4. rerun staticcheck -unused.whole-program on A and B
  5. observe that we do not flag the identifier in A.

A similar problem arises where we cache A's identifier as being unused, then start using it in another package. We will not recheck package A.

Unfortunately, this problem even exists when not running in whole-program mode, because of test variants.

  1. define an unexported identifier in foo.go
  2. run staticcheck
  3. add a foo_test.go and use the previously defined identifier
  4. rerun staticcheck
  5. observe that we still flag the identifier as unused

Both of these problems are caused by the fact that we cache the found problems per package. It seems that in whole-program mode, we must re-analyse all reverse dependencies. In normal mode, it should be enough to re-analyse a package when its tests change.

created time in a month

issue closeddominikh/go-tools

Cannot check unused func in interface

I have code define in interface already implemented but not used any where, but i want to check unused func inside of interface i try to use unused linter but still cannot check UnusedFunc()

type SomeInterface interface {
  UnusedFunc()
}

why the unused linter cannot check this case ?

closed time in 2 months

zainul

issue commentdominikh/go-tools

Cannot check unused func in interface

Interfaces cannot be checked as strictly as you'd like, because they're used for more than just calling methods. Quoting the comments from unused's implementation:

- (8.0) How we handle interfaces:
  - (8.1) We do not technically care about interfaces that only consist of
    exported methods. Exported methods on concrete types are always
    marked as used.
  - Any concrete type implements all known interfaces. Even if it isn't
    assigned to any interfaces in our code, the user may receive a value
    of the type and expect to pass it back to us through an interface.

    Concrete types use their methods that implement interfaces. If the
    type is used, it uses those methods. Otherwise, it doesn't. This
    way, types aren't incorrectly marked reachable through the edge
    from method to type.

  - (8.3) All interface methods are marked as used, even if they never get
    called. This is to accomodate sum types (unexported interface
    method that must exist but never gets called.)

  - (8.4) All embedded interfaces are marked as used. This is an
    extension of 8.3, but we have to explicitly track embedded
    interfaces because in a chain C->B->A, B wouldn't be marked as
    used by 8.3 just because it contributes A's methods to C.

8.3 in particular is of interest. An example for 8.3 is the following piece of code:

type fact interface {
	isFact()
}

type t struct{}

func (t) isFact() {}

func processFact(f fact) {
	// ...
}

func fn() {
	processFact(t{})
}

here, the isFact method merely exists to implement a sum type.

Of course, your example uses exported names for both the interface and the method, so even if we were more strict, we couldn't mark these as unused; they might be used by a package that imports your package.

zainul

comment created time in 2 months

issue closeddominikh/go-tools

Is staticcheck working with Go 1.14 (beta1) ?

  • The output of 'staticcheck -version'
staticcheck 2019.2.3
  • The output of 'staticcheck -debug.version' (it is fine if this command fails)
staticcheck 2019.2.3

Compiled with Go version: go1.14beta1
Main module:
	honnef.co/go/tools@v0.0.1-2019.2.3 (sum: h1:3JgtbtFHMiCmsznwGVTUWbgGov+pVqnlf1dEJTNAXeM=)
Dependencies:
	github.com/BurntSushi/toml@v0.3.1 (sum: h1:WXkYYl6Yr3qBf1K79EBnL4mak0OimBfB0XUf9Vl28OQ=)
	golang.org/x/tools@v0.0.0-20190621195816-6e04913cbbac (sum: h1:MQEvx39qSf8vyrx3XRaOe+j1UDIzKwkYOVObRgGPVqI=)
  • The output of 'go version'
go version go1.14beta1 linux/amd64
  • The output of 'go env'
GO111MODULE=""
GOARCH="amd64"
GOBIN=""
GOCACHE="/home/pierre/.cache/go-build"
GOENV="/home/pierre/.config/go/env"
GOEXE=""
GOFLAGS=""
GOHOSTARCH="amd64"
GOHOSTOS="linux"
GOINSECURE=""
GONOPROXY=""
GONOSUMDB=""
GOOS="linux"
GOPATH="/home/pierre/go"
GOPRIVATE=""
GOPROXY="https://proxy.golang.org,direct"
GOROOT="/home/pierre/.gimme/versions/go1.14beta1.src"
GOSUMDB="sum.golang.org"
GOTMPDIR=""
GOTOOLDIR="/home/pierre/.gimme/versions/go1.14beta1.src/pkg/tool/linux_amd64"
GCCGO="gccgo"
AR="ar"
CC="gcc"
CXX="g++"
CGO_ENABLED="1"
GOMOD="/home/pierre/gosrc/github.com/xxx/yyy/go.mod"
CGO_CFLAGS="-g -O2"
CGO_CPPFLAGS=""
CGO_CXXFLAGS="-g -O2"
CGO_FFLAGS="-g -O2"
CGO_LDFLAGS="-g -O2"
PKG_CONFIG="pkg-config"
GOGCCFLAGS="-fPIC -m64 -pthread -fmessage-length=0 -fdebug-prefix-map=/tmp/go-build718020238=/tmp/go-build -gno-record-gcc-switches"
  • Exactly which command you ran

I'm trying to use it with Go 1.14 beta1. First, I tried with the official binary distribution (same as below), so I decided to compile from source instead. I used this command: cd /tmp && GO111MODULE=on GOBIN=/home/pierre/go/pkg/staticcheck/2019.2.3-mod go get -v honnef.co/go/tools/cmd/staticcheck@v0.0.1-2019.2.3.

  • Output of the command and what's wrong with the output I'm running /home/pierre/go/pkg/staticcheck/2019.2.3-mod/staticcheck -tests ./.... Sorry I can't share the code, because it's a private project, but there is nothing special. It throws a lot of errors similar to:
-: could not analyze dependency bytes of github.com/xxx/yyy/zzz [github.com/xxx/yyy/zzz.test]: 
	could not analyze dependency errors of bytes: 
	could not analyze dependency internal/reflectlite of errors: 
	could not analyze dependency runtime of internal/reflectlite: 
	could not analyze dependency runtime/internal/atomic of runtime: 
	could not load export data: cannot import "runtime/internal/atomic" (unknown iexport format version 1), export data is newer version - update tool (compile)

FYI it was working perfectly fine with Go 1.13 and the binary release of staticcheck.

closed time in 2 months

pierrre

issue commentdominikh/go-tools

Is staticcheck working with Go 1.14 (beta1) ?

This is fixed in the master branch of staticcheck (as of 7398d928b10cbeeef873ee02a66742af75a1d4e9, which pulls in golang/tools@db0687cefd95dc155728a53f4a5416d1aa1bcf1f)

We'll have to make a new release in time for Go 1.14.

pierrre

comment created time in 2 months

fork dominikh/GregTech

GregTech rewrite for modern versions of Minecraft

fork in 2 months

issue commentgo-critic/go-critic

checkers/dupSubExpr_checker.go - Clarification / false positive?

This is a false positive, caused by a peculiarity in cgo. Given the following input

package pkg

// void foo(void **p) {}
import "C"
import "unsafe"

func Foo() {
	var p unsafe.Pointer

	C.foo(&p)
}

go tool cgo will rewrite the code to read as such:

// Code generated by cmd/cgo; DO NOT EDIT.

//line foo.go:1:1
package pkg

// void foo(void **p) {}
import _ "unsafe"
import "unsafe"

func Foo() {
	var p unsafe.Pointer

	func() { _cgoBase0 := /*line :10:8*/&p; _cgo0 := _cgoBase0; _cgoCheckPointer(_cgoBase0, 0 == 0); _Cfunc_foo(_cgo0); }()
}

Note the 0 == 0 in the call to _cgoCheckPointer. 0 == 0 is used instead of true to avoid a rare edge case where the identifier true might be shadowed. It's this comparison that go-critic is flagging.

IIRC this comparison is used in places other than calls to _cgoCheckPointer, too, but someone else will have to confirm that.

dertseha

comment created time in 2 months

issue closeddominikh/go-tools

SA4018: don't flag self-assignment with side effects

SA4018 shouldn't flag this: x[fn()] = x[fn()] – the results of fn on the lhs and rhs may differ.

closed time in 2 months

dominikh

issue commentdominikh/go-tools

SA4018: don't flag self-assignment with side effects

Closed by 9774f3b9ff1812e89d2b42fc5dc5cd4474d86faf

dominikh

comment created time in 2 months

PR closed dominikh/go-tools

Don't flag self–assignments with side effects

Fix SA4018 to not flag self–assignments of the form x[e] = x[e] where e may have side effects (e.g. a function call we know isn't pure or a channel read).

This also includes a change that unties the implementation of the purity fact from SA4017, making it available for reuse in SA4018 and potentially other checks in the future.

+82 -8

4 comments

6 changed files

ksurent

pr closed time in 2 months

pull request commentdominikh/go-tools

Don't flag self–assignments with side effects

Merged as 9774f3b9ff1812e89d2b42fc5dc5cd4474d86faf.

ksurent

comment created time in 2 months

delete branch dominikh/go-tools

delete branch : impure-self-assignment

delete time in 2 months

push eventdominikh/go-tools

Dominik Honnef

commit sha 6cdd070ff900b239448093f4683e21d490f0e67f

facts: fix purity detection for allocations Neither make nor new should have ever been considered pure. They allocate memory and different invocations return different addresses. The ir.UnOp case has never handled allocations correctly (there was no '&' UnOp), and loads were broken when we introduced the Load instruction.

view details

Dominik Honnef

commit sha 2fc7317e106eb2ae6975b577889c2147e35f893a

code: optionally make use of purity information in MayHaveSideEffects

view details

Dominik Honnef

commit sha 9774f3b9ff1812e89d2b42fc5dc5cd4474d86faf

staticcheck: don't flag self-assignments with side effects Co-authored-by: Alexey Surikov <ksurent@gmail.com>

view details

Dominik Honnef

commit sha f433d9cd4c036a9b0f627f7b8c167054be5632bf

staticcheck: when checking printf verbs, recognize unsafe.Pointer as a pointer Closes gh-665

view details

Dominik Honnef

commit sha bb290c3c5ea0c4028d4aea9853706960640cf1f0

staticcheck: the %x and %X verbs now support floats and complex numbers Go 1.13 changed fmt to allow the use of floats and complex numbers with the %x and %X verbs. Adjust our check accordingly. Note that we do not check for the Go version, and assume that %x always behaves as in 1.13. This only causes false negatives, and it's probably not worth complicating the code to fix them.

view details

Dominik Honnef

commit sha 717cd7a0595327ea87bc8016753ce6e0ac546200

staticcheck: validate the new %O verb

view details

push time in 2 months

issue closeddominikh/go-tools

SA5009: unsafe.Pointer formatting with "%x"

<!-- Please make sure to include the following information in your issue report:

  • The output of 'staticcheck -version'
  • The output of 'staticcheck -debug.version' (it is fine if this command fails)
  • The output of 'go version'
  • The output of 'go env'
  • Exactly which command you ran
  • Output of the command and what's wrong with the output
  • Where we can read the code you're running staticcheck on (GitHub repo, link to playground, code embedded in the issue, ...) -->

Informations

$ staticcheck -version
staticcheck 2019.2.3
$ go version
go version go1.13.4 darwin/amd64
$ go env
GOARCH="amd64"
GOBIN=""
GOCACHE="/Users/will/Library/Caches/go-build"
GOENV="/Users/will/Library/Application Support/go/env"
GOEXE=""
GOFLAGS=""
GOHOSTARCH="amd64"
GOHOSTOS="darwin"
GONOPROXY=""
GONOSUMDB=""
GOOS="darwin"
GOPATH="/Users/will/go"
GOPRIVATE=""
GOPROXY="https://proxy.golang.org,direct"
GOROOT="/usr/local/opt/go/libexec"
GOSUMDB="sum.golang.org"
GOTMPDIR=""
GOTOOLDIR="/usr/local/opt/go/libexec/pkg/tool/darwin_amd64"
GCCGO="gccgo"
AR="ar"
CC="clang"
CXX="clang++"
CGO_ENABLED="1"
GOMOD="/Users/will/github/wI2L/jettison/go.mod"
CGO_CFLAGS="-g -O2"
CGO_CPPFLAGS=""
CGO_CXXFLAGS="-g -O2"
CGO_FFLAGS="-g -O2"
CGO_LDFLAGS="-g -O2"
PKG_CONFIG="pkg-config"
GOGCCFLAGS="-fPIC -m64 -pthread -fno-caret-diagnostics -Qunused-arguments -fmessage-length=0 -fdebug-prefix-map=/var/folders/rw/cyt9bjxx34qglfg2jsfm27jr0000gn/T/go-build168005285=/tmp/go-build -gno-record-gcc-switches -fno-common"

The following code is valid, per the fmt documentation.

var p unsafe.Pointer
id := fmt.Sprintf("%x", p)

Pointer: %p base 16 notation, with leading 0x The %b, %d, %o, %x and %X verbs also work with pointers, formatting the value exactly as if it were an integer.

Staticcheck warns with error code SA5009.

Printf format %x has arg #1 of wrong type unsafe.Pointer (SA5009)

closed time in 2 months

wI2L

issue commentdominikh/go-tools

SA1019: flag stuff in our own package

Please see https://github.com/dominikh/go-tools/issues/508#issuecomment-500682935 for why intra-package use of deprecated APIs is currently permitted, and why we can't change that retroactively. The same argument applies to making it configurable, as such configuration would likely be too coarse (at best it can be local to a subtree of packages, which IMO is too coarse.)

¹: That's because staticcheck.conf applies to packages and all sub-packages rooted in the same directory.

tharvik

comment created time in 2 months

issue commentdominikh/go-tools

staticcheck: suggest ctx.Err() instead of select

Based on https://twitter.com/dominikhonnef/status/1202499783669276672 I am inclined to make this an opt-in style check. I don't think there is enough consensus for me to force it on people, and I can see how the select is more explicit in what is happening. At the same time, people who are aware of the alternative may want it enforced. And people who blindly (and against recommendation) enable all checks will not be making harmful changes to their code based on the suggestion.

egonelbre

comment created time in 3 months

issue openeddominikh/go-tools

Document that ST is for style

All the other categories have one-line descriptions on https://staticcheck.io/docs/checks, ST does not.

created time in 3 months

more