diff options
Diffstat (limited to 'src/cmd/vet')
29 files changed, 1619 insertions, 0 deletions
diff --git a/src/cmd/vet/README b/src/cmd/vet/README new file mode 100644 index 0000000..5ab7549 --- /dev/null +++ b/src/cmd/vet/README @@ -0,0 +1,33 @@ +Vet is a tool that checks correctness of Go programs. It runs a suite of tests, +each tailored to check for a particular class of errors. Examples include incorrect +Printf format verbs and malformed build tags. + +Over time many checks have been added to vet's suite, but many more have been +rejected as not appropriate for the tool. The criteria applied when selecting which +checks to add are: + +Correctness: + +Vet's checks are about correctness, not style. A vet check must identify real or +potential bugs that could cause incorrect compilation or execution. A check that +only identifies stylistic points or alternative correct approaches to a situation +is not acceptable. + +Frequency: + +Vet is run every day by many programmers, often as part of every compilation or +submission. The cost in execution time is considerable, especially in aggregate, +so checks must be likely enough to find real problems that they are worth the +overhead of the added check. A new check that finds only a handful of problems +across all existing programs, even if the problem is significant, is not worth +adding to the suite everyone runs daily. + +Precision: + +Most of vet's checks are heuristic and can generate both false positives (flagging +correct programs) and false negatives (not flagging incorrect ones). The rate of +both these failures must be very small. A check that is too noisy will be ignored +by the programmer overwhelmed by the output; a check that misses too many of the +cases it's looking for will give a false sense of security. Neither is acceptable. +A vet check must be accurate enough that everything it reports is worth examining, +and complete enough to encourage real confidence. diff --git a/src/cmd/vet/doc.go b/src/cmd/vet/doc.go new file mode 100644 index 0000000..279d081 --- /dev/null +++ b/src/cmd/vet/doc.go @@ -0,0 +1,71 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +/* + +Vet examines Go source code and reports suspicious constructs, such as Printf +calls whose arguments do not align with the format string. Vet uses heuristics +that do not guarantee all reports are genuine problems, but it can find errors +not caught by the compilers. + +Vet is normally invoked through the go command. +This command vets the package in the current directory: + + go vet + +whereas this one vets the packages whose path is provided: + + go vet my/project/... + +Use "go help packages" to see other ways of specifying which packages to vet. + +Vet's exit code is non-zero for erroneous invocation of the tool or if a +problem was reported, and 0 otherwise. Note that the tool does not +check every possible problem and depends on unreliable heuristics, +so it should be used as guidance only, not as a firm indicator of +program correctness. + +To list the available checks, run "go tool vet help": + + asmdecl report mismatches between assembly files and Go declarations + assign check for useless assignments + atomic check for common mistakes using the sync/atomic package + bools check for common mistakes involving boolean operators + buildtag check that +build tags are well-formed and correctly located + cgocall detect some violations of the cgo pointer passing rules + composites check for unkeyed composite literals + copylocks check for locks erroneously passed by value + httpresponse check for mistakes using HTTP responses + loopclosure check references to loop variables from within nested functions + lostcancel check cancel func returned by context.WithCancel is called + nilfunc check for useless comparisons between functions and nil + printf check consistency of Printf format strings and arguments + shift check for shifts that equal or exceed the width of the integer + stdmethods check signature of methods of well-known interfaces + structtag check that struct field tags conform to reflect.StructTag.Get + tests check for common mistaken usages of tests and examples + unmarshal report passing non-pointer or non-interface values to unmarshal + unreachable check for unreachable code + unsafeptr check for invalid conversions of uintptr to unsafe.Pointer + unusedresult check for unused results of calls to some functions + +For details and flags of a particular check, such as printf, run "go tool vet help printf". + +By default, all checks are performed. +If any flags are explicitly set to true, only those tests are run. +Conversely, if any flag is explicitly set to false, only those tests are disabled. +Thus -printf=true runs the printf check, +and -printf=false runs all checks except the printf check. + +For information on writing a new check, see golang.org/x/tools/go/analysis. + +Core flags: + + -c=N + display offending line plus N lines of surrounding context + -json + emit analysis diagnostics (and errors) in JSON format + +*/ +package main diff --git a/src/cmd/vet/main.go b/src/cmd/vet/main.go new file mode 100644 index 0000000..d50c45d --- /dev/null +++ b/src/cmd/vet/main.go @@ -0,0 +1,67 @@ +package main + +import ( + "cmd/internal/objabi" + + "golang.org/x/tools/go/analysis/unitchecker" + + "golang.org/x/tools/go/analysis/passes/asmdecl" + "golang.org/x/tools/go/analysis/passes/assign" + "golang.org/x/tools/go/analysis/passes/atomic" + "golang.org/x/tools/go/analysis/passes/bools" + "golang.org/x/tools/go/analysis/passes/buildtag" + "golang.org/x/tools/go/analysis/passes/cgocall" + "golang.org/x/tools/go/analysis/passes/composite" + "golang.org/x/tools/go/analysis/passes/copylock" + "golang.org/x/tools/go/analysis/passes/errorsas" + "golang.org/x/tools/go/analysis/passes/framepointer" + "golang.org/x/tools/go/analysis/passes/httpresponse" + "golang.org/x/tools/go/analysis/passes/ifaceassert" + "golang.org/x/tools/go/analysis/passes/loopclosure" + "golang.org/x/tools/go/analysis/passes/lostcancel" + "golang.org/x/tools/go/analysis/passes/nilfunc" + "golang.org/x/tools/go/analysis/passes/printf" + "golang.org/x/tools/go/analysis/passes/shift" + "golang.org/x/tools/go/analysis/passes/stdmethods" + "golang.org/x/tools/go/analysis/passes/stringintconv" + "golang.org/x/tools/go/analysis/passes/structtag" + "golang.org/x/tools/go/analysis/passes/testinggoroutine" + "golang.org/x/tools/go/analysis/passes/tests" + "golang.org/x/tools/go/analysis/passes/unmarshal" + "golang.org/x/tools/go/analysis/passes/unreachable" + "golang.org/x/tools/go/analysis/passes/unsafeptr" + "golang.org/x/tools/go/analysis/passes/unusedresult" +) + +func main() { + objabi.AddVersionFlag() + + unitchecker.Main( + asmdecl.Analyzer, + assign.Analyzer, + atomic.Analyzer, + bools.Analyzer, + buildtag.Analyzer, + cgocall.Analyzer, + composite.Analyzer, + copylock.Analyzer, + errorsas.Analyzer, + framepointer.Analyzer, + httpresponse.Analyzer, + ifaceassert.Analyzer, + loopclosure.Analyzer, + lostcancel.Analyzer, + nilfunc.Analyzer, + printf.Analyzer, + shift.Analyzer, + stdmethods.Analyzer, + stringintconv.Analyzer, + structtag.Analyzer, + tests.Analyzer, + testinggoroutine.Analyzer, + unmarshal.Analyzer, + unreachable.Analyzer, + unsafeptr.Analyzer, + unusedresult.Analyzer, + ) +} diff --git a/src/cmd/vet/testdata/asm/asm.go b/src/cmd/vet/testdata/asm/asm.go new file mode 100644 index 0000000..1e60d8b --- /dev/null +++ b/src/cmd/vet/testdata/asm/asm.go @@ -0,0 +1,11 @@ +// Copyright 2010 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// This file contains declarations to test the assembly in asm1.s. + +package testdata + +func arg1(x int8, y uint8) + +func cpx(x complex64, y complex128) diff --git a/src/cmd/vet/testdata/asm/asm1.s b/src/cmd/vet/testdata/asm/asm1.s new file mode 100644 index 0000000..a5bb6dd --- /dev/null +++ b/src/cmd/vet/testdata/asm/asm1.s @@ -0,0 +1,23 @@ +// Copyright 2013 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// +build amd64 + +TEXT ·arg1(SB),0,$0-2 + MOVW x+0(FP), AX // ERROR "\[amd64\] arg1: invalid MOVW of x\+0\(FP\); int8 is 1-byte value" + +TEXT ·cpx(SB),0,$0-24 + // These are ok + MOVSS x_real+0(FP), X0 + MOVSS x_imag+4(FP), X0 + MOVSD y_real+8(FP), X0 + MOVSD y_imag+16(FP), X0 + // Loading both parts of a complex is ok: see issue 35264. + MOVSD x+0(FP), X0 + MOVO y+8(FP), X0 + MOVOU y+8(FP), X0 + + // These are not ok. + MOVO x+0(FP), X0 // ERROR "\[amd64\] cpx: invalid MOVO of x\+0\(FP\); complex64 is 8-byte value containing x_real\+0\(FP\) and x_imag\+4\(FP\)" + MOVSD y+8(FP), X0 // ERROR "\[amd64\] cpx: invalid MOVSD of y\+8\(FP\); complex128 is 16-byte value containing y_real\+8\(FP\) and y_imag\+16\(FP\)" diff --git a/src/cmd/vet/testdata/assign/assign.go b/src/cmd/vet/testdata/assign/assign.go new file mode 100644 index 0000000..112614e --- /dev/null +++ b/src/cmd/vet/testdata/assign/assign.go @@ -0,0 +1,31 @@ +// Copyright 2013 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// This file contains tests for the useless-assignment checker. + +package assign + +import "math/rand" + +type ST struct { + x int + l []int +} + +func (s *ST) SetX(x int, ch chan int) { + // Accidental self-assignment; it should be "s.x = x" + x = x // ERROR "self-assignment of x to x" + // Another mistake + s.x = s.x // ERROR "self-assignment of s.x to s.x" + + s.l[0] = s.l[0] // ERROR "self-assignment of s.l.0. to s.l.0." + + // Bail on any potential side effects to avoid false positives + s.l[num()] = s.l[num()] + rng := rand.New(rand.NewSource(0)) + s.l[rng.Intn(len(s.l))] = s.l[rng.Intn(len(s.l))] + s.l[<-ch] = s.l[<-ch] +} + +func num() int { return 2 } diff --git a/src/cmd/vet/testdata/atomic/atomic.go b/src/cmd/vet/testdata/atomic/atomic.go new file mode 100644 index 0000000..650d56b --- /dev/null +++ b/src/cmd/vet/testdata/atomic/atomic.go @@ -0,0 +1,14 @@ +// Copyright 2013 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// This file contains tests for the atomic checker. + +package atomic + +import "sync/atomic" + +func AtomicTests() { + x := uint64(1) + x = atomic.AddUint64(&x, 1) // ERROR "direct assignment to atomic value" +} diff --git a/src/cmd/vet/testdata/bool/bool.go b/src/cmd/vet/testdata/bool/bool.go new file mode 100644 index 0000000..20e01aa --- /dev/null +++ b/src/cmd/vet/testdata/bool/bool.go @@ -0,0 +1,14 @@ +// Copyright 2014 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// This file contains tests for the bool checker. + +package bool + +func _() { + var f, g func() int + + if v, w := f(), g(); v == w || v == w { // ERROR "redundant or: v == w || v == w" + } +} diff --git a/src/cmd/vet/testdata/buildtag/buildtag.go b/src/cmd/vet/testdata/buildtag/buildtag.go new file mode 100644 index 0000000..c2fd6aa --- /dev/null +++ b/src/cmd/vet/testdata/buildtag/buildtag.go @@ -0,0 +1,18 @@ +// Copyright 2013 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// This file contains tests for the buildtag checker. + +// +builder // ERROR "possible malformed \+build comment" +// +build !ignore + +package testdata + +// +build toolate // ERROR "build comment must appear before package clause and be followed by a blank line$" + +var _ = 3 + +var _ = ` +// +build notacomment +` diff --git a/src/cmd/vet/testdata/cgo/cgo.go b/src/cmd/vet/testdata/cgo/cgo.go new file mode 100644 index 0000000..292d7fd --- /dev/null +++ b/src/cmd/vet/testdata/cgo/cgo.go @@ -0,0 +1,18 @@ +// Copyright 2015 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// This file contains tests for the cgo checker. + +package testdata + +// void f(void *p) {} +import "C" + +import "unsafe" + +func CgoTests() { + var c chan bool + C.f(*(*unsafe.Pointer)(unsafe.Pointer(&c))) // ERROR "embedded pointer" + C.f(unsafe.Pointer(&c)) // ERROR "embedded pointer" +} diff --git a/src/cmd/vet/testdata/composite/composite.go b/src/cmd/vet/testdata/composite/composite.go new file mode 100644 index 0000000..63a2837 --- /dev/null +++ b/src/cmd/vet/testdata/composite/composite.go @@ -0,0 +1,24 @@ +// Copyright 2012 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// This file contains the test for untagged struct literals. + +package composite + +import "flag" + +// Testing is awkward because we need to reference things from a separate package +// to trigger the warnings. + +var goodStructLiteral = flag.Flag{ + Name: "Name", + Usage: "Usage", +} + +var badStructLiteral = flag.Flag{ // ERROR "unkeyed fields" + "Name", + "Usage", + nil, // Value + "DefValue", +} diff --git a/src/cmd/vet/testdata/copylock/copylock.go b/src/cmd/vet/testdata/copylock/copylock.go new file mode 100644 index 0000000..8079cf3 --- /dev/null +++ b/src/cmd/vet/testdata/copylock/copylock.go @@ -0,0 +1,11 @@ +package copylock + +import "sync" + +func BadFunc() { + var x *sync.Mutex + p := x + var y sync.Mutex + p = &y + *p = *x // ERROR "assignment copies lock value to \*p: sync.Mutex" +} diff --git a/src/cmd/vet/testdata/deadcode/deadcode.go b/src/cmd/vet/testdata/deadcode/deadcode.go new file mode 100644 index 0000000..af83cdf --- /dev/null +++ b/src/cmd/vet/testdata/deadcode/deadcode.go @@ -0,0 +1,14 @@ +// Copyright 2013 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// This file contains tests for the dead code checker. + +package deadcode + +func _() int { + print(1) + return 2 + println() // ERROR "unreachable code" + return 3 +} diff --git a/src/cmd/vet/testdata/httpresponse/httpresponse.go b/src/cmd/vet/testdata/httpresponse/httpresponse.go new file mode 100644 index 0000000..6141f6e --- /dev/null +++ b/src/cmd/vet/testdata/httpresponse/httpresponse.go @@ -0,0 +1,22 @@ +package httpresponse + +import ( + "log" + "net/http" +) + +func goodHTTPGet() { + res, err := http.Get("http://foo.com") + if err != nil { + log.Fatal(err) + } + defer res.Body.Close() +} + +func badHTTPGet() { + res, err := http.Get("http://foo.com") + defer res.Body.Close() // ERROR "using res before checking for errors" + if err != nil { + log.Fatal(err) + } +} diff --git a/src/cmd/vet/testdata/lostcancel/lostcancel.go b/src/cmd/vet/testdata/lostcancel/lostcancel.go new file mode 100644 index 0000000..1bbb22d --- /dev/null +++ b/src/cmd/vet/testdata/lostcancel/lostcancel.go @@ -0,0 +1,14 @@ +// Copyright 2016 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package lostcancel + +import "context" + +func _() { + var _, cancel = context.WithCancel(context.Background()) // ERROR "the cancel function is not used on all paths \(possible context leak\)" + if false { + _ = cancel + } +} // ERROR "this return statement may be reached without using the cancel var defined on line 10" diff --git a/src/cmd/vet/testdata/method/method.go b/src/cmd/vet/testdata/method/method.go new file mode 100644 index 0000000..51c3f65 --- /dev/null +++ b/src/cmd/vet/testdata/method/method.go @@ -0,0 +1,14 @@ +// Copyright 2010 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// This file contains the code to check canonical methods. + +package method + +import "fmt" + +type MethodTest int + +func (t *MethodTest) Scan(x fmt.ScanState, c byte) { // ERROR "should have signature Scan\(fmt\.ScanState, rune\) error" +} diff --git a/src/cmd/vet/testdata/nilfunc/nilfunc.go b/src/cmd/vet/testdata/nilfunc/nilfunc.go new file mode 100644 index 0000000..c34d60e --- /dev/null +++ b/src/cmd/vet/testdata/nilfunc/nilfunc.go @@ -0,0 +1,13 @@ +// Copyright 2013 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package nilfunc + +func F() {} + +func Comparison() { + if F == nil { // ERROR "comparison of function F == nil is always false" + panic("can't happen") + } +} diff --git a/src/cmd/vet/testdata/print/print.go b/src/cmd/vet/testdata/print/print.go new file mode 100644 index 0000000..fca5949 --- /dev/null +++ b/src/cmd/vet/testdata/print/print.go @@ -0,0 +1,680 @@ +// Copyright 2010 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// This file contains tests for the printf checker. + +package print + +import ( + "fmt" + logpkg "log" // renamed to make it harder to see + "math" + "os" + "testing" + "unsafe" // just for test case printing unsafe.Pointer + // For testing printf-like functions from external package. + // "github.com/foobar/externalprintf" +) + +func UnsafePointerPrintfTest() { + var up unsafe.Pointer + fmt.Printf("%p, %x %X", up, up, up) +} + +// Error methods that do not satisfy the Error interface and should be checked. +type errorTest1 int + +func (errorTest1) Error(...interface{}) string { + return "hi" +} + +type errorTest2 int // Analogous to testing's *T type. +func (errorTest2) Error(...interface{}) { +} + +type errorTest3 int + +func (errorTest3) Error() { // No return value. +} + +type errorTest4 int + +func (errorTest4) Error() int { // Different return type. + return 3 +} + +type errorTest5 int + +func (errorTest5) error() { // niladic; don't complain if no args (was bug) +} + +// This function never executes, but it serves as a simple test for the program. +// Test with make test. +func PrintfTests() { + var b bool + var i int + var r rune + var s string + var x float64 + var p *int + var imap map[int]int + var fslice []float64 + var c complex64 + // Some good format/argtypes + fmt.Printf("") + fmt.Printf("%b %b %b", 3, i, x) + fmt.Printf("%c %c %c %c", 3, i, 'x', r) + fmt.Printf("%d %d %d", 3, i, imap) + fmt.Printf("%e %e %e %e", 3e9, x, fslice, c) + fmt.Printf("%E %E %E %E", 3e9, x, fslice, c) + fmt.Printf("%f %f %f %f", 3e9, x, fslice, c) + fmt.Printf("%F %F %F %F", 3e9, x, fslice, c) + fmt.Printf("%g %g %g %g", 3e9, x, fslice, c) + fmt.Printf("%G %G %G %G", 3e9, x, fslice, c) + fmt.Printf("%b %b %b %b", 3e9, x, fslice, c) + fmt.Printf("%o %o", 3, i) + fmt.Printf("%p", p) + fmt.Printf("%q %q %q %q", 3, i, 'x', r) + fmt.Printf("%s %s %s", "hi", s, []byte{65}) + fmt.Printf("%t %t", true, b) + fmt.Printf("%T %T", 3, i) + fmt.Printf("%U %U", 3, i) + fmt.Printf("%v %v", 3, i) + fmt.Printf("%x %x %x %x %x %x %x", 3, i, "hi", s, x, c, fslice) + fmt.Printf("%X %X %X %X %X %X %X", 3, i, "hi", s, x, c, fslice) + fmt.Printf("%.*s %d %g", 3, "hi", 23, 2.3) + fmt.Printf("%s", &stringerv) + fmt.Printf("%v", &stringerv) + fmt.Printf("%T", &stringerv) + fmt.Printf("%s", &embeddedStringerv) + fmt.Printf("%v", &embeddedStringerv) + fmt.Printf("%T", &embeddedStringerv) + fmt.Printf("%v", notstringerv) + fmt.Printf("%T", notstringerv) + fmt.Printf("%q", stringerarrayv) + fmt.Printf("%v", stringerarrayv) + fmt.Printf("%s", stringerarrayv) + fmt.Printf("%v", notstringerarrayv) + fmt.Printf("%T", notstringerarrayv) + fmt.Printf("%d", new(fmt.Formatter)) + fmt.Printf("%*%", 2) // Ridiculous but allowed. + fmt.Printf("%s", interface{}(nil)) // Nothing useful we can say. + + fmt.Printf("%g", 1+2i) + fmt.Printf("%#e %#E %#f %#F %#g %#G", 1.2, 1.2, 1.2, 1.2, 1.2, 1.2) // OK since Go 1.9 + // Some bad format/argTypes + fmt.Printf("%b", "hi") // ERROR "Printf format %b has arg \x22hi\x22 of wrong type string" + fmt.Printf("%t", c) // ERROR "Printf format %t has arg c of wrong type complex64" + fmt.Printf("%t", 1+2i) // ERROR "Printf format %t has arg 1 \+ 2i of wrong type complex128" + fmt.Printf("%c", 2.3) // ERROR "Printf format %c has arg 2.3 of wrong type float64" + fmt.Printf("%d", 2.3) // ERROR "Printf format %d has arg 2.3 of wrong type float64" + fmt.Printf("%e", "hi") // ERROR "Printf format %e has arg \x22hi\x22 of wrong type string" + fmt.Printf("%E", true) // ERROR "Printf format %E has arg true of wrong type bool" + fmt.Printf("%f", "hi") // ERROR "Printf format %f has arg \x22hi\x22 of wrong type string" + fmt.Printf("%F", 'x') // ERROR "Printf format %F has arg 'x' of wrong type rune" + fmt.Printf("%g", "hi") // ERROR "Printf format %g has arg \x22hi\x22 of wrong type string" + fmt.Printf("%g", imap) // ERROR "Printf format %g has arg imap of wrong type map\[int\]int" + fmt.Printf("%G", i) // ERROR "Printf format %G has arg i of wrong type int" + fmt.Printf("%o", x) // ERROR "Printf format %o has arg x of wrong type float64" + fmt.Printf("%p", nil) // ERROR "Printf format %p has arg nil of wrong type untyped nil" + fmt.Printf("%p", 23) // ERROR "Printf format %p has arg 23 of wrong type int" + fmt.Printf("%q", x) // ERROR "Printf format %q has arg x of wrong type float64" + fmt.Printf("%s", b) // ERROR "Printf format %s has arg b of wrong type bool" + fmt.Printf("%s", byte(65)) // ERROR "Printf format %s has arg byte\(65\) of wrong type byte" + fmt.Printf("%t", 23) // ERROR "Printf format %t has arg 23 of wrong type int" + fmt.Printf("%U", x) // ERROR "Printf format %U has arg x of wrong type float64" + fmt.Printf("%x", nil) // ERROR "Printf format %x has arg nil of wrong type untyped nil" + fmt.Printf("%s", stringerv) // ERROR "Printf format %s has arg stringerv of wrong type .*print.ptrStringer" + fmt.Printf("%t", stringerv) // ERROR "Printf format %t has arg stringerv of wrong type .*print.ptrStringer" + fmt.Printf("%s", embeddedStringerv) // ERROR "Printf format %s has arg embeddedStringerv of wrong type .*print.embeddedStringer" + fmt.Printf("%t", embeddedStringerv) // ERROR "Printf format %t has arg embeddedStringerv of wrong type .*print.embeddedStringer" + fmt.Printf("%q", notstringerv) // ERROR "Printf format %q has arg notstringerv of wrong type .*print.notstringer" + fmt.Printf("%t", notstringerv) // ERROR "Printf format %t has arg notstringerv of wrong type .*print.notstringer" + fmt.Printf("%t", stringerarrayv) // ERROR "Printf format %t has arg stringerarrayv of wrong type .*print.stringerarray" + fmt.Printf("%t", notstringerarrayv) // ERROR "Printf format %t has arg notstringerarrayv of wrong type .*print.notstringerarray" + fmt.Printf("%q", notstringerarrayv) // ERROR "Printf format %q has arg notstringerarrayv of wrong type .*print.notstringerarray" + fmt.Printf("%d", BoolFormatter(true)) // ERROR "Printf format %d has arg BoolFormatter\(true\) of wrong type .*print.BoolFormatter" + fmt.Printf("%z", FormatterVal(true)) // correct (the type is responsible for formatting) + fmt.Printf("%d", FormatterVal(true)) // correct (the type is responsible for formatting) + fmt.Printf("%s", nonemptyinterface) // correct (the type is responsible for formatting) + fmt.Printf("%.*s %d %6g", 3, "hi", 23, 'x') // ERROR "Printf format %6g has arg 'x' of wrong type rune" + fmt.Println() // not an error + fmt.Println("%s", "hi") // ERROR "Println call has possible formatting directive %s" + fmt.Println("%v", "hi") // ERROR "Println call has possible formatting directive %v" + fmt.Println("%T", "hi") // ERROR "Println call has possible formatting directive %T" + fmt.Println("0.0%") // correct (trailing % couldn't be a formatting directive) + fmt.Printf("%s", "hi", 3) // ERROR "Printf call needs 1 arg but has 2 args" + _ = fmt.Sprintf("%"+("s"), "hi", 3) // ERROR "Sprintf call needs 1 arg but has 2 args" + fmt.Printf("%s%%%d", "hi", 3) // correct + fmt.Printf("%08s", "woo") // correct + fmt.Printf("% 8s", "woo") // correct + fmt.Printf("%.*d", 3, 3) // correct + fmt.Printf("%.*d x", 3, 3, 3, 3) // ERROR "Printf call needs 2 args but has 4 args" + fmt.Printf("%.*d x", "hi", 3) // ERROR "Printf format %.*d uses non-int \x22hi\x22 as argument of \*" + fmt.Printf("%.*d x", i, 3) // correct + fmt.Printf("%.*d x", s, 3) // ERROR "Printf format %.\*d uses non-int s as argument of \*" + fmt.Printf("%*% x", 0.22) // ERROR "Printf format %\*% uses non-int 0.22 as argument of \*" + fmt.Printf("%q %q", multi()...) // ok + fmt.Printf("%#q", `blah`) // ok + // printf("now is the time", "buddy") // no error "printf call has arguments but no formatting directives" + Printf("now is the time", "buddy") // ERROR "Printf call has arguments but no formatting directives" + Printf("hi") // ok + const format = "%s %s\n" + Printf(format, "hi", "there") + Printf(format, "hi") // ERROR "Printf format %s reads arg #2, but call has 1 arg$" + Printf("%s %d %.3v %q", "str", 4) // ERROR "Printf format %.3v reads arg #3, but call has 2 args" + f := new(ptrStringer) + f.Warn(0, "%s", "hello", 3) // ERROR "Warn call has possible formatting directive %s" + f.Warnf(0, "%s", "hello", 3) // ERROR "Warnf call needs 1 arg but has 2 args" + f.Warnf(0, "%r", "hello") // ERROR "Warnf format %r has unknown verb r" + f.Warnf(0, "%#s", "hello") // ERROR "Warnf format %#s has unrecognized flag #" + f.Warn2(0, "%s", "hello", 3) // ERROR "Warn2 call has possible formatting directive %s" + f.Warnf2(0, "%s", "hello", 3) // ERROR "Warnf2 call needs 1 arg but has 2 args" + f.Warnf2(0, "%r", "hello") // ERROR "Warnf2 format %r has unknown verb r" + f.Warnf2(0, "%#s", "hello") // ERROR "Warnf2 format %#s has unrecognized flag #" + f.Wrap(0, "%s", "hello", 3) // ERROR "Wrap call has possible formatting directive %s" + f.Wrapf(0, "%s", "hello", 3) // ERROR "Wrapf call needs 1 arg but has 2 args" + f.Wrapf(0, "%r", "hello") // ERROR "Wrapf format %r has unknown verb r" + f.Wrapf(0, "%#s", "hello") // ERROR "Wrapf format %#s has unrecognized flag #" + f.Wrap2(0, "%s", "hello", 3) // ERROR "Wrap2 call has possible formatting directive %s" + f.Wrapf2(0, "%s", "hello", 3) // ERROR "Wrapf2 call needs 1 arg but has 2 args" + f.Wrapf2(0, "%r", "hello") // ERROR "Wrapf2 format %r has unknown verb r" + f.Wrapf2(0, "%#s", "hello") // ERROR "Wrapf2 format %#s has unrecognized flag #" + fmt.Printf("%#s", FormatterVal(true)) // correct (the type is responsible for formatting) + Printf("d%", 2) // ERROR "Printf format % is missing verb at end of string" + Printf("%d", percentDV) + Printf("%d", &percentDV) + Printf("%d", notPercentDV) // ERROR "Printf format %d has arg notPercentDV of wrong type .*print.notPercentDStruct" + Printf("%d", ¬PercentDV) // ERROR "Printf format %d has arg ¬PercentDV of wrong type \*.*print.notPercentDStruct" + Printf("%p", ¬PercentDV) // Works regardless: we print it as a pointer. + Printf("%q", &percentDV) // ERROR "Printf format %q has arg &percentDV of wrong type \*.*print.percentDStruct" + Printf("%s", percentSV) + Printf("%s", &percentSV) + // Good argument reorderings. + Printf("%[1]d", 3) + Printf("%[1]*d", 3, 1) + Printf("%[2]*[1]d", 1, 3) + Printf("%[2]*.[1]*[3]d", 2, 3, 4) + fmt.Fprintf(os.Stderr, "%[2]*.[1]*[3]d", 2, 3, 4) // Use Fprintf to make sure we count arguments correctly. + // Bad argument reorderings. + Printf("%[xd", 3) // ERROR "Printf format %\[xd is missing closing \]" + Printf("%[x]d x", 3) // ERROR "Printf format has invalid argument index \[x\]" + Printf("%[3]*s x", "hi", 2) // ERROR "Printf format has invalid argument index \[3\]" + _ = fmt.Sprintf("%[3]d x", 2) // ERROR "Sprintf format has invalid argument index \[3\]" + Printf("%[2]*.[1]*[3]d x", 2, "hi", 4) // ERROR "Printf format %\[2]\*\.\[1\]\*\[3\]d uses non-int \x22hi\x22 as argument of \*" + Printf("%[0]s x", "arg1") // ERROR "Printf format has invalid argument index \[0\]" + Printf("%[0]d x", 1) // ERROR "Printf format has invalid argument index \[0\]" + // Something that satisfies the error interface. + var e error + fmt.Println(e.Error()) // ok + // Something that looks like an error interface but isn't, such as the (*T).Error method + // in the testing package. + var et1 *testing.T + et1.Error() // ok + et1.Error("hi") // ok + et1.Error("%d", 3) // ERROR "Error call has possible formatting directive %d" + var et3 errorTest3 + et3.Error() // ok, not an error method. + var et4 errorTest4 + et4.Error() // ok, not an error method. + var et5 errorTest5 + et5.error() // ok, not an error method. + // Interfaces can be used with any verb. + var iface interface { + ToTheMadness() bool // Method ToTheMadness usually returns false + } + fmt.Printf("%f", iface) // ok: fmt treats interfaces as transparent and iface may well have a float concrete type + // Can't print a function. + Printf("%d", someFunction) // ERROR "Printf format %d arg someFunction is a func value, not called" + Printf("%v", someFunction) // ERROR "Printf format %v arg someFunction is a func value, not called" + Println(someFunction) // ERROR "Println arg someFunction is a func value, not called" + Printf("%p", someFunction) // ok: maybe someone wants to see the pointer + Printf("%T", someFunction) // ok: maybe someone wants to see the type + // Bug: used to recur forever. + Printf("%p %x", recursiveStructV, recursiveStructV.next) + Printf("%p %x", recursiveStruct1V, recursiveStruct1V.next) // ERROR "Printf format %x has arg recursiveStruct1V\.next of wrong type \*.*print\.RecursiveStruct2" + Printf("%p %x", recursiveSliceV, recursiveSliceV) + Printf("%p %x", recursiveMapV, recursiveMapV) + // Special handling for Log. + math.Log(3) // OK + var t *testing.T + t.Log("%d", 3) // ERROR "Log call has possible formatting directive %d" + t.Logf("%d", 3) + t.Logf("%d", "hi") // ERROR "Logf format %d has arg \x22hi\x22 of wrong type string" + + Errorf(1, "%d", 3) // OK + Errorf(1, "%d", "hi") // ERROR "Errorf format %d has arg \x22hi\x22 of wrong type string" + + // Multiple string arguments before variadic args + errorf("WARNING", "foobar") // OK + errorf("INFO", "s=%s, n=%d", "foo", 1) // OK + errorf("ERROR", "%d") // ERROR "errorf format %d reads arg #1, but call has 0 args" + + // Printf from external package + // externalprintf.Printf("%d", 42) // OK + // externalprintf.Printf("foobar") // OK + // level := 123 + // externalprintf.Logf(level, "%d", 42) // OK + // externalprintf.Errorf(level, level, "foo %q bar", "foobar") // OK + // externalprintf.Logf(level, "%d") // no error "Logf format %d reads arg #1, but call has 0 args" + // var formatStr = "%s %s" + // externalprintf.Sprintf(formatStr, "a", "b") // OK + // externalprintf.Logf(level, formatStr, "a", "b") // OK + + // user-defined Println-like functions + ss := &someStruct{} + ss.Log(someFunction, "foo") // OK + ss.Error(someFunction, someFunction) // OK + ss.Println() // OK + ss.Println(1.234, "foo") // OK + ss.Println(1, someFunction) // no error "Println arg someFunction is a func value, not called" + ss.log(someFunction) // OK + ss.log(someFunction, "bar", 1.33) // OK + ss.log(someFunction, someFunction) // no error "log arg someFunction is a func value, not called" + + // indexed arguments + Printf("%d %[3]d %d %[2]d x", 1, 2, 3, 4) // OK + Printf("%d %[0]d %d %[2]d x", 1, 2, 3, 4) // ERROR "Printf format has invalid argument index \[0\]" + Printf("%d %[3]d %d %[-2]d x", 1, 2, 3, 4) // ERROR "Printf format has invalid argument index \[-2\]" + Printf("%d %[3]d %d %[2234234234234]d x", 1, 2, 3, 4) // ERROR "Printf format has invalid argument index \[2234234234234\]" + Printf("%d %[3]d %-10d %[2]d x", 1, 2, 3) // ERROR "Printf format %-10d reads arg #4, but call has 3 args" + Printf("%[1][3]d x", 1, 2) // ERROR "Printf format %\[1\]\[ has unknown verb \[" + Printf("%[1]d x", 1, 2) // OK + Printf("%d %[3]d %d %[2]d x", 1, 2, 3, 4, 5) // OK + + // wrote Println but meant Fprintln + Printf("%p\n", os.Stdout) // OK + Println(os.Stdout, "hello") // ERROR "Println does not take io.Writer but has first arg os.Stdout" + + Printf(someString(), "hello") // OK + + // Printf wrappers in package log should be detected automatically + logpkg.Fatal("%d", 1) // ERROR "Fatal call has possible formatting directive %d" + logpkg.Fatalf("%d", "x") // ERROR "Fatalf format %d has arg \x22x\x22 of wrong type string" + logpkg.Fatalln("%d", 1) // ERROR "Fatalln call has possible formatting directive %d" + logpkg.Panic("%d", 1) // ERROR "Panic call has possible formatting directive %d" + logpkg.Panicf("%d", "x") // ERROR "Panicf format %d has arg \x22x\x22 of wrong type string" + logpkg.Panicln("%d", 1) // ERROR "Panicln call has possible formatting directive %d" + logpkg.Print("%d", 1) // ERROR "Print call has possible formatting directive %d" + logpkg.Printf("%d", "x") // ERROR "Printf format %d has arg \x22x\x22 of wrong type string" + logpkg.Println("%d", 1) // ERROR "Println call has possible formatting directive %d" + + // Methods too. + var l *logpkg.Logger + l.Fatal("%d", 1) // ERROR "Fatal call has possible formatting directive %d" + l.Fatalf("%d", "x") // ERROR "Fatalf format %d has arg \x22x\x22 of wrong type string" + l.Fatalln("%d", 1) // ERROR "Fatalln call has possible formatting directive %d" + l.Panic("%d", 1) // ERROR "Panic call has possible formatting directive %d" + l.Panicf("%d", "x") // ERROR "Panicf format %d has arg \x22x\x22 of wrong type string" + l.Panicln("%d", 1) // ERROR "Panicln call has possible formatting directive %d" + l.Print("%d", 1) // ERROR "Print call has possible formatting directive %d" + l.Printf("%d", "x") // ERROR "Printf format %d has arg \x22x\x22 of wrong type string" + l.Println("%d", 1) // ERROR "Println call has possible formatting directive %d" + + // Issue 26486 + dbg("", 1) // no error "call has arguments but no formatting directive" +} + +func someString() string { return "X" } + +type someStruct struct{} + +// Log is non-variadic user-define Println-like function. +// Calls to this func must be skipped when checking +// for Println-like arguments. +func (ss *someStruct) Log(f func(), s string) {} + +// Error is variadic user-define Println-like function. +// Calls to this func mustn't be checked for Println-like arguments, +// since variadic arguments type isn't interface{}. +func (ss *someStruct) Error(args ...func()) {} + +// Println is variadic user-defined Println-like function. +// Calls to this func must be checked for Println-like arguments. +func (ss *someStruct) Println(args ...interface{}) {} + +// log is variadic user-defined Println-like function. +// Calls to this func must be checked for Println-like arguments. +func (ss *someStruct) log(f func(), args ...interface{}) {} + +// A function we use as a function value; it has no other purpose. +func someFunction() {} + +// Printf is used by the test so we must declare it. +func Printf(format string, args ...interface{}) { + fmt.Printf(format, args...) +} + +// Println is used by the test so we must declare it. +func Println(args ...interface{}) { + fmt.Println(args...) +} + +// printf is used by the test so we must declare it. +func printf(format string, args ...interface{}) { + fmt.Printf(format, args...) +} + +// Errorf is used by the test for a case in which the first parameter +// is not a format string. +func Errorf(i int, format string, args ...interface{}) { + _ = fmt.Errorf(format, args...) +} + +// errorf is used by the test for a case in which the function accepts multiple +// string parameters before variadic arguments +func errorf(level, format string, args ...interface{}) { + _ = fmt.Errorf(format, args...) +} + +// multi is used by the test. +func multi() []interface{} { + panic("don't call - testing only") +} + +type stringer int + +func (stringer) String() string { return "string" } + +type ptrStringer float64 + +var stringerv ptrStringer + +func (*ptrStringer) String() string { + return "string" +} + +func (p *ptrStringer) Warn2(x int, args ...interface{}) string { + return p.Warn(x, args...) +} + +func (p *ptrStringer) Warnf2(x int, format string, args ...interface{}) string { + return p.Warnf(x, format, args...) +} + +func (*ptrStringer) Warn(x int, args ...interface{}) string { + return "warn" +} + +func (*ptrStringer) Warnf(x int, format string, args ...interface{}) string { + return "warnf" +} + +func (p *ptrStringer) Wrap2(x int, args ...interface{}) string { + return p.Wrap(x, args...) +} + +func (p *ptrStringer) Wrapf2(x int, format string, args ...interface{}) string { + return p.Wrapf(x, format, args...) +} + +func (*ptrStringer) Wrap(x int, args ...interface{}) string { + return fmt.Sprint(args...) +} + +func (*ptrStringer) Wrapf(x int, format string, args ...interface{}) string { + return fmt.Sprintf(format, args...) +} + +func (*ptrStringer) BadWrap(x int, args ...interface{}) string { + return fmt.Sprint(args) // ERROR "missing ... in args forwarded to print-like function" +} + +func (*ptrStringer) BadWrapf(x int, format string, args ...interface{}) string { + return fmt.Sprintf(format, args) // ERROR "missing ... in args forwarded to printf-like function" +} + +func (*ptrStringer) WrapfFalsePositive(x int, arg1 string, arg2 ...interface{}) string { + return fmt.Sprintf("%s %v", arg1, arg2) +} + +type embeddedStringer struct { + foo string + ptrStringer + bar int +} + +var embeddedStringerv embeddedStringer + +type notstringer struct { + f float64 +} + +var notstringerv notstringer + +type stringerarray [4]float64 + +func (stringerarray) String() string { + return "string" +} + +var stringerarrayv stringerarray + +type notstringerarray [4]float64 + +var notstringerarrayv notstringerarray + +var nonemptyinterface = interface { + f() +}(nil) + +// A data type we can print with "%d". +type percentDStruct struct { + a int + b []byte + c *float64 +} + +var percentDV percentDStruct + +// A data type we cannot print correctly with "%d". +type notPercentDStruct struct { + a int + b []byte + c bool +} + +var notPercentDV notPercentDStruct + +// A data type we can print with "%s". +type percentSStruct struct { + a string + b []byte + C stringerarray +} + +var percentSV percentSStruct + +type recursiveStringer int + +func (s recursiveStringer) String() string { + _ = fmt.Sprintf("%d", s) + _ = fmt.Sprintf("%#v", s) + _ = fmt.Sprintf("%v", s) // ERROR "Sprintf format %v with arg s causes recursive String method call" + _ = fmt.Sprintf("%v", &s) // ERROR "Sprintf format %v with arg &s causes recursive String method call" + _ = fmt.Sprintf("%T", s) // ok; does not recursively call String + return fmt.Sprintln(s) // ERROR "Sprintln arg s causes recursive call to String method" +} + +type recursivePtrStringer int + +func (p *recursivePtrStringer) String() string { + _ = fmt.Sprintf("%v", *p) + _ = fmt.Sprint(&p) // ok; prints address + return fmt.Sprintln(p) // ERROR "Sprintln arg p causes recursive call to String method" +} + +type BoolFormatter bool + +func (*BoolFormatter) Format(fmt.State, rune) { +} + +// Formatter with value receiver +type FormatterVal bool + +func (FormatterVal) Format(fmt.State, rune) { +} + +type RecursiveSlice []RecursiveSlice + +var recursiveSliceV = &RecursiveSlice{} + +type RecursiveMap map[int]RecursiveMap + +var recursiveMapV = make(RecursiveMap) + +type RecursiveStruct struct { + next *RecursiveStruct +} + +var recursiveStructV = &RecursiveStruct{} + +type RecursiveStruct1 struct { + next *RecursiveStruct2 +} + +type RecursiveStruct2 struct { + next *RecursiveStruct1 +} + +var recursiveStruct1V = &RecursiveStruct1{} + +type unexportedInterface struct { + f interface{} +} + +// Issue 17798: unexported ptrStringer cannot be formatted. +type unexportedStringer struct { + t ptrStringer +} +type unexportedStringerOtherFields struct { + s string + t ptrStringer + S string +} + +// Issue 17798: unexported error cannot be formatted. +type unexportedError struct { + e error +} +type unexportedErrorOtherFields struct { + s string + e error + S string +} + +type errorer struct{} + +func (e errorer) Error() string { return "errorer" } + +type unexportedCustomError struct { + e errorer +} + +type errorInterface interface { + error + ExtraMethod() +} + +type unexportedErrorInterface struct { + e errorInterface +} + +func UnexportedStringerOrError() { + fmt.Printf("%s", unexportedInterface{"foo"}) // ok; prints {foo} + fmt.Printf("%s", unexportedInterface{3}) // ok; we can't see the problem + + us := unexportedStringer{} + fmt.Printf("%s", us) // ERROR "Printf format %s has arg us of wrong type .*print.unexportedStringer" + fmt.Printf("%s", &us) // ERROR "Printf format %s has arg &us of wrong type [*].*print.unexportedStringer" + + usf := unexportedStringerOtherFields{ + s: "foo", + S: "bar", + } + fmt.Printf("%s", usf) // ERROR "Printf format %s has arg usf of wrong type .*print.unexportedStringerOtherFields" + fmt.Printf("%s", &usf) // ERROR "Printf format %s has arg &usf of wrong type [*].*print.unexportedStringerOtherFields" + + ue := unexportedError{ + e: &errorer{}, + } + fmt.Printf("%s", ue) // ERROR "Printf format %s has arg ue of wrong type .*print.unexportedError" + fmt.Printf("%s", &ue) // ERROR "Printf format %s has arg &ue of wrong type [*].*print.unexportedError" + + uef := unexportedErrorOtherFields{ + s: "foo", + e: &errorer{}, + S: "bar", + } + fmt.Printf("%s", uef) // ERROR "Printf format %s has arg uef of wrong type .*print.unexportedErrorOtherFields" + fmt.Printf("%s", &uef) // ERROR "Printf format %s has arg &uef of wrong type [*].*print.unexportedErrorOtherFields" + + uce := unexportedCustomError{ + e: errorer{}, + } + fmt.Printf("%s", uce) // ERROR "Printf format %s has arg uce of wrong type .*print.unexportedCustomError" + + uei := unexportedErrorInterface{} + fmt.Printf("%s", uei) // ERROR "Printf format %s has arg uei of wrong type .*print.unexportedErrorInterface" + fmt.Println("foo\n", "bar") // not an error + + fmt.Println("foo\n") // ERROR "Println arg list ends with redundant newline" + fmt.Println("foo\\n") // not an error + fmt.Println(`foo\n`) // not an error + + intSlice := []int{3, 4} + fmt.Printf("%s", intSlice) // ERROR "Printf format %s has arg intSlice of wrong type \[\]int" + nonStringerArray := [1]unexportedStringer{{}} + fmt.Printf("%s", nonStringerArray) // ERROR "Printf format %s has arg nonStringerArray of wrong type \[1\].*print.unexportedStringer" + fmt.Printf("%s", []stringer{3, 4}) // not an error + fmt.Printf("%s", [2]stringer{3, 4}) // not an error +} + +// TODO: Disable complaint about '0' for Go 1.10. To be fixed properly in 1.11. +// See issues 23598 and 23605. +func DisableErrorForFlag0() { + fmt.Printf("%0t", true) +} + +// Issue 26486. +func dbg(format string, args ...interface{}) { + if format == "" { + format = "%v" + } + fmt.Printf(format, args...) +} + +func PointersToCompoundTypes() { + stringSlice := []string{"a", "b"} + fmt.Printf("%s", &stringSlice) // not an error + + intSlice := []int{3, 4} + fmt.Printf("%s", &intSlice) // ERROR "Printf format %s has arg &intSlice of wrong type \*\[\]int" + + stringArray := [2]string{"a", "b"} + fmt.Printf("%s", &stringArray) // not an error + + intArray := [2]int{3, 4} + fmt.Printf("%s", &intArray) // ERROR "Printf format %s has arg &intArray of wrong type \*\[2\]int" + + stringStruct := struct{ F string }{"foo"} + fmt.Printf("%s", &stringStruct) // not an error + + intStruct := struct{ F int }{3} + fmt.Printf("%s", &intStruct) // ERROR "Printf format %s has arg &intStruct of wrong type \*struct{F int}" + + stringMap := map[string]string{"foo": "bar"} + fmt.Printf("%s", &stringMap) // not an error + + intMap := map[int]int{3: 4} + fmt.Printf("%s", &intMap) // ERROR "Printf format %s has arg &intMap of wrong type \*map\[int\]int" + + type T2 struct { + X string + } + type T1 struct { + X *T2 + } + fmt.Printf("%s\n", T1{&T2{"x"}}) // ERROR "Printf format %s has arg T1{&T2{.x.}} of wrong type .*print\.T1" +} diff --git a/src/cmd/vet/testdata/rangeloop/rangeloop.go b/src/cmd/vet/testdata/rangeloop/rangeloop.go new file mode 100644 index 0000000..4e21564 --- /dev/null +++ b/src/cmd/vet/testdata/rangeloop/rangeloop.go @@ -0,0 +1,17 @@ +// Copyright 2012 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// This file contains tests for the rangeloop checker. + +package rangeloop + +func RangeLoopTests() { + var s []int + for i, v := range s { + go func() { + println(i) // ERROR "loop variable i captured by func literal" + println(v) // ERROR "loop variable v captured by func literal" + }() + } +} diff --git a/src/cmd/vet/testdata/shift/shift.go b/src/cmd/vet/testdata/shift/shift.go new file mode 100644 index 0000000..6b7a5ac --- /dev/null +++ b/src/cmd/vet/testdata/shift/shift.go @@ -0,0 +1,13 @@ +// Copyright 2014 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// This file contains tests for the suspicious shift checker. + +package shift + +func ShiftTest() { + var i8 int8 + _ = i8 << 7 + _ = (i8 + 1) << 8 // ERROR ".i8 . 1. .8 bits. too small for shift of 8" +} diff --git a/src/cmd/vet/testdata/structtag/structtag.go b/src/cmd/vet/testdata/structtag/structtag.go new file mode 100644 index 0000000..cbcc453 --- /dev/null +++ b/src/cmd/vet/testdata/structtag/structtag.go @@ -0,0 +1,11 @@ +// Copyright 2010 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// This file contains the test for canonical struct tags. + +package structtag + +type StructTagTest struct { + A int "hello" // ERROR "`hello` not compatible with reflect.StructTag.Get: bad syntax for struct tag pair" +} diff --git a/src/cmd/vet/testdata/tagtest/file1.go b/src/cmd/vet/testdata/tagtest/file1.go new file mode 100644 index 0000000..47fe3c8 --- /dev/null +++ b/src/cmd/vet/testdata/tagtest/file1.go @@ -0,0 +1,13 @@ +// Copyright 2015 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// +build testtag + +package main + +import "fmt" + +func main() { + fmt.Printf("%s", 0) +} diff --git a/src/cmd/vet/testdata/tagtest/file2.go b/src/cmd/vet/testdata/tagtest/file2.go new file mode 100644 index 0000000..1f45efc --- /dev/null +++ b/src/cmd/vet/testdata/tagtest/file2.go @@ -0,0 +1,13 @@ +// Copyright 2015 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// +build !testtag + +package main + +import "fmt" + +func main() { + fmt.Printf("%s", 0) +} diff --git a/src/cmd/vet/testdata/testingpkg/tests.go b/src/cmd/vet/testdata/testingpkg/tests.go new file mode 100644 index 0000000..69d29d3 --- /dev/null +++ b/src/cmd/vet/testdata/testingpkg/tests.go @@ -0,0 +1 @@ +package testdata diff --git a/src/cmd/vet/testdata/testingpkg/tests_test.go b/src/cmd/vet/testdata/testingpkg/tests_test.go new file mode 100644 index 0000000..09bb98d --- /dev/null +++ b/src/cmd/vet/testdata/testingpkg/tests_test.go @@ -0,0 +1,3 @@ +package testdata + +func Example_BadSuffix() {} // ERROR "Example_BadSuffix has malformed example suffix: BadSuffix" diff --git a/src/cmd/vet/testdata/unmarshal/unmarshal.go b/src/cmd/vet/testdata/unmarshal/unmarshal.go new file mode 100644 index 0000000..b387bbb --- /dev/null +++ b/src/cmd/vet/testdata/unmarshal/unmarshal.go @@ -0,0 +1,18 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// This file contains tests for the unmarshal checker. + +package unmarshal + +import "encoding/json" + +func _() { + type t struct { + a int + } + var v t + + json.Unmarshal([]byte{}, v) // ERROR "call of Unmarshal passes non-pointer as second argument" +} diff --git a/src/cmd/vet/testdata/unsafeptr/unsafeptr.go b/src/cmd/vet/testdata/unsafeptr/unsafeptr.go new file mode 100644 index 0000000..e9b866e --- /dev/null +++ b/src/cmd/vet/testdata/unsafeptr/unsafeptr.go @@ -0,0 +1,14 @@ +// Copyright 2014 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package unsafeptr + +import "unsafe" + +func _() { + var x unsafe.Pointer + var y uintptr + x = unsafe.Pointer(y) // ERROR "possible misuse of unsafe.Pointer" + _ = x +} diff --git a/src/cmd/vet/testdata/unused/unused.go b/src/cmd/vet/testdata/unused/unused.go new file mode 100644 index 0000000..1e83e90 --- /dev/null +++ b/src/cmd/vet/testdata/unused/unused.go @@ -0,0 +1,13 @@ +// Copyright 2015 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// This file contains tests for the unusedresult checker. + +package unused + +import "fmt" + +func _() { + fmt.Errorf("") // ERROR "result of fmt.Errorf call not used" +} diff --git a/src/cmd/vet/vet_test.go b/src/cmd/vet/vet_test.go new file mode 100644 index 0000000..d15d1ce --- /dev/null +++ b/src/cmd/vet/vet_test.go @@ -0,0 +1,411 @@ +// Copyright 2013 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main_test + +import ( + "bytes" + "errors" + "fmt" + "internal/testenv" + "log" + "os" + "os/exec" + "path" + "path/filepath" + "regexp" + "strconv" + "strings" + "sync" + "testing" +) + +const dataDir = "testdata" + +var binary string + +// We implement TestMain so remove the test binary when all is done. +func TestMain(m *testing.M) { + os.Exit(testMain(m)) +} + +func testMain(m *testing.M) int { + dir, err := os.MkdirTemp("", "vet_test") + if err != nil { + fmt.Fprintln(os.Stderr, err) + return 1 + } + defer os.RemoveAll(dir) + binary = filepath.Join(dir, "testvet.exe") + + return m.Run() +} + +var ( + buildMu sync.Mutex // guards following + built = false // We have built the binary. + failed = false // We have failed to build the binary, don't try again. +) + +func Build(t *testing.T) { + buildMu.Lock() + defer buildMu.Unlock() + if built { + return + } + if failed { + t.Skip("cannot run on this environment") + } + testenv.MustHaveGoBuild(t) + cmd := exec.Command(testenv.GoToolPath(t), "build", "-o", binary) + output, err := cmd.CombinedOutput() + if err != nil { + failed = true + fmt.Fprintf(os.Stderr, "%s\n", output) + t.Fatal(err) + } + built = true +} + +func vetCmd(t *testing.T, arg, pkg string) *exec.Cmd { + cmd := exec.Command(testenv.GoToolPath(t), "vet", "-vettool="+binary, arg, path.Join("cmd/vet/testdata", pkg)) + cmd.Env = os.Environ() + return cmd +} + +func TestVet(t *testing.T) { + t.Parallel() + Build(t) + for _, pkg := range []string{ + "asm", + "assign", + "atomic", + "bool", + "buildtag", + "cgo", + "composite", + "copylock", + "deadcode", + "httpresponse", + "lostcancel", + "method", + "nilfunc", + "print", + "rangeloop", + "shift", + "structtag", + "testingpkg", + // "testtag" has its own test + "unmarshal", + "unsafeptr", + "unused", + } { + pkg := pkg + t.Run(pkg, func(t *testing.T) { + t.Parallel() + + // Skip cgo test on platforms without cgo. + if pkg == "cgo" && !cgoEnabled(t) { + return + } + + cmd := vetCmd(t, "-printfuncs=Warn,Warnf", pkg) + + // The asm test assumes amd64. + if pkg == "asm" { + cmd.Env = append(cmd.Env, "GOOS=linux", "GOARCH=amd64") + } + + dir := filepath.Join("testdata", pkg) + gos, err := filepath.Glob(filepath.Join(dir, "*.go")) + if err != nil { + t.Fatal(err) + } + asms, err := filepath.Glob(filepath.Join(dir, "*.s")) + if err != nil { + t.Fatal(err) + } + var files []string + files = append(files, gos...) + files = append(files, asms...) + + errchk(cmd, files, t) + }) + } +} + +func cgoEnabled(t *testing.T) bool { + // Don't trust build.Default.CgoEnabled as it is false for + // cross-builds unless CGO_ENABLED is explicitly specified. + // That's fine for the builders, but causes commands like + // 'GOARCH=386 go test .' to fail. + // Instead, we ask the go command. + cmd := exec.Command(testenv.GoToolPath(t), "list", "-f", "{{context.CgoEnabled}}") + out, _ := cmd.CombinedOutput() + return string(out) == "true\n" +} + +func errchk(c *exec.Cmd, files []string, t *testing.T) { + output, err := c.CombinedOutput() + if _, ok := err.(*exec.ExitError); !ok { + t.Logf("vet output:\n%s", output) + t.Fatal(err) + } + fullshort := make([]string, 0, len(files)*2) + for _, f := range files { + fullshort = append(fullshort, f, filepath.Base(f)) + } + err = errorCheck(string(output), false, fullshort...) + if err != nil { + t.Errorf("error check failed: %s", err) + } +} + +// TestTags verifies that the -tags argument controls which files to check. +func TestTags(t *testing.T) { + t.Parallel() + Build(t) + for tag, wantFile := range map[string]int{ + "testtag": 1, // file1 + "x testtag y": 1, + "othertag": 2, + } { + tag, wantFile := tag, wantFile + t.Run(tag, func(t *testing.T) { + t.Parallel() + t.Logf("-tags=%s", tag) + cmd := vetCmd(t, "-tags="+tag, "tagtest") + output, err := cmd.CombinedOutput() + + want := fmt.Sprintf("file%d.go", wantFile) + dontwant := fmt.Sprintf("file%d.go", 3-wantFile) + + // file1 has testtag and file2 has !testtag. + if !bytes.Contains(output, []byte(filepath.Join("tagtest", want))) { + t.Errorf("%s: %s was excluded, should be included", tag, want) + } + if bytes.Contains(output, []byte(filepath.Join("tagtest", dontwant))) { + t.Errorf("%s: %s was included, should be excluded", tag, dontwant) + } + if t.Failed() { + t.Logf("err=%s, output=<<%s>>", err, output) + } + }) + } +} + +// All declarations below were adapted from test/run.go. + +// errorCheck matches errors in outStr against comments in source files. +// For each line of the source files which should generate an error, +// there should be a comment of the form // ERROR "regexp". +// If outStr has an error for a line which has no such comment, +// this function will report an error. +// Likewise if outStr does not have an error for a line which has a comment, +// or if the error message does not match the <regexp>. +// The <regexp> syntax is Perl but it's best to stick to egrep. +// +// Sources files are supplied as fullshort slice. +// It consists of pairs: full path to source file and its base name. +func errorCheck(outStr string, wantAuto bool, fullshort ...string) (err error) { + var errs []error + out := splitOutput(outStr, wantAuto) + // Cut directory name. + for i := range out { + for j := 0; j < len(fullshort); j += 2 { + full, short := fullshort[j], fullshort[j+1] + out[i] = strings.ReplaceAll(out[i], full, short) + } + } + + var want []wantedError + for j := 0; j < len(fullshort); j += 2 { + full, short := fullshort[j], fullshort[j+1] + want = append(want, wantedErrors(full, short)...) + } + for _, we := range want { + var errmsgs []string + if we.auto { + errmsgs, out = partitionStrings("<autogenerated>", out) + } else { + errmsgs, out = partitionStrings(we.prefix, out) + } + if len(errmsgs) == 0 { + errs = append(errs, fmt.Errorf("%s:%d: missing error %q", we.file, we.lineNum, we.reStr)) + continue + } + matched := false + n := len(out) + for _, errmsg := range errmsgs { + // Assume errmsg says "file:line: foo". + // Cut leading "file:line: " to avoid accidental matching of file name instead of message. + text := errmsg + if i := strings.Index(text, " "); i >= 0 { + text = text[i+1:] + } + if we.re.MatchString(text) { + matched = true + } else { + out = append(out, errmsg) + } + } + if !matched { + errs = append(errs, fmt.Errorf("%s:%d: no match for %#q in:\n\t%s", we.file, we.lineNum, we.reStr, strings.Join(out[n:], "\n\t"))) + continue + } + } + + if len(out) > 0 { + errs = append(errs, fmt.Errorf("Unmatched Errors:")) + for _, errLine := range out { + errs = append(errs, fmt.Errorf("%s", errLine)) + } + } + + if len(errs) == 0 { + return nil + } + if len(errs) == 1 { + return errs[0] + } + var buf bytes.Buffer + fmt.Fprintf(&buf, "\n") + for _, err := range errs { + fmt.Fprintf(&buf, "%s\n", err.Error()) + } + return errors.New(buf.String()) +} + +func splitOutput(out string, wantAuto bool) []string { + // gc error messages continue onto additional lines with leading tabs. + // Split the output at the beginning of each line that doesn't begin with a tab. + // <autogenerated> lines are impossible to match so those are filtered out. + var res []string + for _, line := range strings.Split(out, "\n") { + line = strings.TrimSuffix(line, "\r") // normalize Windows output + if strings.HasPrefix(line, "\t") { + res[len(res)-1] += "\n" + line + } else if strings.HasPrefix(line, "go tool") || strings.HasPrefix(line, "#") || !wantAuto && strings.HasPrefix(line, "<autogenerated>") { + continue + } else if strings.TrimSpace(line) != "" { + res = append(res, line) + } + } + return res +} + +// matchPrefix reports whether s starts with file name prefix followed by a :, +// and possibly preceded by a directory name. +func matchPrefix(s, prefix string) bool { + i := strings.Index(s, ":") + if i < 0 { + return false + } + j := strings.LastIndex(s[:i], "/") + s = s[j+1:] + if len(s) <= len(prefix) || s[:len(prefix)] != prefix { + return false + } + if s[len(prefix)] == ':' { + return true + } + return false +} + +func partitionStrings(prefix string, strs []string) (matched, unmatched []string) { + for _, s := range strs { + if matchPrefix(s, prefix) { + matched = append(matched, s) + } else { + unmatched = append(unmatched, s) + } + } + return +} + +type wantedError struct { + reStr string + re *regexp.Regexp + lineNum int + auto bool // match <autogenerated> line + file string + prefix string +} + +var ( + errRx = regexp.MustCompile(`// (?:GC_)?ERROR (.*)`) + errAutoRx = regexp.MustCompile(`// (?:GC_)?ERRORAUTO (.*)`) + errQuotesRx = regexp.MustCompile(`"([^"]*)"`) + lineRx = regexp.MustCompile(`LINE(([+-])([0-9]+))?`) +) + +// wantedErrors parses expected errors from comments in a file. +func wantedErrors(file, short string) (errs []wantedError) { + cache := make(map[string]*regexp.Regexp) + + src, err := os.ReadFile(file) + if err != nil { + log.Fatal(err) + } + for i, line := range strings.Split(string(src), "\n") { + lineNum := i + 1 + if strings.Contains(line, "////") { + // double comment disables ERROR + continue + } + var auto bool + m := errAutoRx.FindStringSubmatch(line) + if m != nil { + auto = true + } else { + m = errRx.FindStringSubmatch(line) + } + if m == nil { + continue + } + all := m[1] + mm := errQuotesRx.FindAllStringSubmatch(all, -1) + if mm == nil { + log.Fatalf("%s:%d: invalid errchk line: %s", file, lineNum, line) + } + for _, m := range mm { + replacedOnce := false + rx := lineRx.ReplaceAllStringFunc(m[1], func(m string) string { + if replacedOnce { + return m + } + replacedOnce = true + n := lineNum + if strings.HasPrefix(m, "LINE+") { + delta, _ := strconv.Atoi(m[5:]) + n += delta + } else if strings.HasPrefix(m, "LINE-") { + delta, _ := strconv.Atoi(m[5:]) + n -= delta + } + return fmt.Sprintf("%s:%d", short, n) + }) + re := cache[rx] + if re == nil { + var err error + re, err = regexp.Compile(rx) + if err != nil { + log.Fatalf("%s:%d: invalid regexp \"%#q\" in ERROR line: %v", file, lineNum, rx, err) + } + cache[rx] = re + } + prefix := fmt.Sprintf("%s:%d", short, lineNum) + errs = append(errs, wantedError{ + reStr: rx, + re: re, + prefix: prefix, + auto: auto, + lineNum: lineNum, + file: short, + }) + } + } + + return +} |