README

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.

Documentation

Overview

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 using the go command by running "go vet":

go vet

vets the package in the current directory.

go vet package/path/name

vets the package whose path is provided.

Use "go help packages" to see other ways of specifying which packages to vet.

Vet's exit code is 2 for erroneous invocation of the tool, 1 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.

By default the -all flag is set so 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, -printf=false runs all checks except the printf check.

By default vet uses the object files generated by 'go install some/pkg' to typecheck the code. If the -source flag is provided, vet uses only source code.

Available checks:

Assembly declarations

Flag: -asmdecl

Mismatches between assembly files and Go function declarations.

Useless assignments

Flag: -assign

Check for useless assignments.

Atomic mistakes

Flag: -atomic

Common mistaken usages of the sync/atomic package.

Boolean conditions

Flag: -bool

Mistakes involving boolean operators.

Build tags

Flag: -buildtags

Badly formed or misplaced +build tags.

Invalid uses of cgo

Flag: -cgocall

Detect some violations of the cgo pointer passing rules.

Unkeyed composite literals

Flag: -composites

Composite struct literals that do not use the field-keyed syntax.

Copying locks

Flag: -copylocks

Locks that are erroneously passed by value.

HTTP responses used incorrectly

Flag: -httpresponse

Mistakes deferring a function call on an HTTP response before checking whether the error returned with the response was nil.

Failure to call the cancelation function returned by WithCancel

Flag: -lostcancel

The cancelation function returned by context.WithCancel, WithTimeout, and WithDeadline must be called or the new context will remain live until its parent context is cancelled. (The background context is never cancelled.)

Methods

Flag: -methods

Non-standard signatures for methods with familiar names, including:

Format GobEncode GobDecode MarshalJSON MarshalXML
Peek ReadByte ReadFrom ReadRune Scan Seek
UnmarshalJSON UnreadByte UnreadRune WriteByte
WriteTo

Nil function comparison

Flag: -nilfunc

Comparisons between functions and nil.

Printf family

Flag: -printf

Suspicious calls to functions in the Printf family, including any functions with these names, disregarding case:

Print Printf Println
Fprint Fprintf Fprintln
Sprint Sprintf Sprintln
Error Errorf
Fatal Fatalf
Log Logf
Panic Panicf Panicln

The -printfuncs flag can be used to redefine this list. If the function name ends with an 'f', the function is assumed to take a format descriptor string in the manner of fmt.Printf. If not, vet complains about arguments that look like format descriptor strings.

It also checks for errors such as using a Writer as the first argument of Printf.

Range loop variables

Flag: -rangeloops

Incorrect uses of range loop variables in closures.

Shadowed variables

Flag: -shadow=false (experimental; must be set explicitly)

Variables that may have been unintentionally shadowed.

Shifts

Flag: -shift

Shifts equal to or longer than the variable's length.

Struct tags

Flag: -structtags

Struct tags that do not follow the format understood by reflect.StructTag.Get. Well-known encoding struct tags (json, xml) used with unexported fields.

Tests and documentation examples

Flag: -tests

Mistakes involving tests including functions with incorrect names or signatures and example tests that document identifiers not in the package.

Unreachable code

Flag: -unreachable

Unreachable code.

Misuse of unsafe Pointers

Flag: -unsafeptr

Likely incorrect uses of unsafe.Pointer to convert integers to pointers. A conversion from uintptr to unsafe.Pointer is invalid if it implies that there is a uintptr-typed word in memory that holds a pointer value, because that word will be invisible to stack copying and to the garbage collector.

Unused result of certain function calls

Flag: -unusedresult

Calls to well-known functions and methods that return a value that is discarded. By default, this includes functions like fmt.Errorf and fmt.Sprintf and methods like String and Error. The flags -unusedfuncs and -unusedstringmethods control the set.

Other flags

These flags configure the behavior of vet:

-all (default true)
	Enable all non-experimental checks.
-v
	Verbose mode
-printfuncs
	A comma-separated list of print-like function names
	to supplement the standard list.
	For more information, see the discussion of the -printf flag.
-shadowstrict
	Whether to be strict about shadowing; can be noisy.

Using vet directly

For testing and debugging vet can be run directly by invoking "go tool vet" or just running the binary. Run this way, vet might not have up to date information for imported packages.

go tool vet source/directory/*.go

vets the files named, all of which must be in the same package.

go tool vet source/directory

recursively descends the directory, vetting each package it finds.

Vet is a simple checker for static errors in Go source code. See doc.go for more information.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Printf

func Printf(format string, args ...interface{})

    Printf is fmt.Printf guarded by -v.

    func Println

    func Println(args ...interface{})

      Println is fmt.Println guarded by -v.

      func Usage

      func Usage()

        Usage is a replacement usage function for the flags package.

        Types

        type File

        type File struct {
        	// contains filtered or unexported fields
        }

          File is a wrapper for the state of a file used in the parser. The parse tree walkers are all methods of this type.

          func (*File) Bad

          func (f *File) Bad(pos token.Pos, args ...interface{})

            Bad reports an error and sets the exit code..

            func (*File) Badf

            func (f *File) Badf(pos token.Pos, format string, args ...interface{})

              Badf reports a formatted error and sets the exit code.

              func (*File) Visit

              func (f *File) Visit(node ast.Node) ast.Visitor

                Visit implements the ast.Visitor interface.

                func (*File) Warn

                func (f *File) Warn(pos token.Pos, args ...interface{})

                  Warn reports an error but does not set the exit code.

                  func (*File) Warnf

                  func (f *File) Warnf(pos token.Pos, format string, args ...interface{})

                    Warnf reports a formatted error but does not set the exit code.

                    type Issue

                    type Issue struct {
                    	Pos     token.Position
                    	Message string
                    }

                    func Analyze

                    func Analyze(files []*ast.File, fset *token.FileSet, pkgInfo *loader.PackageInfo, checkShadowing bool, pg astFilePathGetter) ([]Issue, error)

                    type MethodSig

                    type MethodSig struct {
                    	// contains filtered or unexported fields
                    }

                    type Package

                    type Package struct {
                    	// contains filtered or unexported fields
                    }

                    type Span

                    type Span struct {
                    	// contains filtered or unexported fields
                    }

                      Span stores the minimum range of byte positions in the file in which a given variable (types.Object) is mentioned. It is lexically defined: it spans from the beginning of its first mention to the end of its last mention. A variable is considered shadowed (if *strictShadowing is off) only if the shadowing variable is declared within the span of the shadowed variable. In other words, if a variable is shadowed but not used after the shadowed variable is declared, it is inconsequential and not worth complaining about. This simple check dramatically reduces the nuisance rate for the shadowing check, at least until something cleverer comes along.

                      One wrinkle: A "naked return" is a silent use of a variable that the Span will not capture, but the compilers catch naked returns of shadowed variables so we don't need to.

                      Cases this gets wrong (TODO): - If a for loop's continuation statement mentions a variable redeclared in the block, we should complain about it but don't. - A variable declared inside a function literal can falsely be identified as shadowing a variable in the outer function.

                      Directories

                      Path Synopsis
                      lib
                      cfg
                      This package constructs a simple control-flow graph (CFG) of the statements and expressions within a single function.
                      This package constructs a simple control-flow graph (CFG) of the statements and expressions within a single function.
                      whitelist
                      Package whitelist defines exceptions for the vet tool.
                      Package whitelist defines exceptions for the vet tool.