8000 go-tools/staticcheck/lint.go at 2019.2 · dominikh/go-tools · GitHub
[go: up one dir, main page]

Skip to content

Latest commit

 

History

History
3346 lines (3135 loc) · 88.3 KB

lint.go

File metadata and controls

3346 lines (3135 loc) · 88.3 KB
// Package staticcheck contains a linter for Go source code.
package staticcheck // import "honnef.co/go/tools/staticcheck"
import (
"fmt"
"go/ast"
"go/constant"
"go/token"
"go/types"
htmltemplate "html/template"
"net/http"
"reflect"
"regexp"
"regexp/syntax"
"sort"
"strconv"
"strings"
texttemplate "text/template"
"unicode"
. "honnef.co/go/tools/arg"
"honnef.co/go/tools/deprecated"
"honnef.co/go/tools/facts"
"honnef.co/go/tools/functions"
"honnef.co/go/tools/internal/passes/buildssa"
"honnef.co/go/tools/internal/sharedcheck"
"honnef.co/go/tools/lint"
. "honnef.co/go/tools/lint/lintdsl"
"honnef.co/go/tools/printf"
"honnef.co/go/tools/ssa"
"honnef.co/go/tools/ssautil"
"honnef.co/go/tools/staticcheck/vrp"
"golang.org/x/tools/go/analysis"
"golang.org/x/tools/go/analysis/passes/inspect"
"golang.org/x/tools/go/ast/astutil"
"golang.org/x/tools/go/ast/inspector"
"golang.org/x/tools/go/types/typeutil"
)
func validRegexp(call *Call) {
arg := call.Args[0]
err := ValidateRegexp(arg.Value)
if err != nil {
arg.Invalid(err.Error())
}
}
type runeSlice []rune
func (rs runeSlice) Len() int { return len(rs) }
func (rs runeSlice) Less(i int, j int) bool { return rs[i] < rs[j] }
func (rs runeSlice) Swap(i int, j int) { rs[i], rs[j] = rs[j], rs[i] }
func utf8Cutset(call *Call) {
arg := call.Args[1]
if InvalidUTF8(arg.Value) {
arg.Invalid(MsgInvalidUTF8)
}
}
func uniqueCutset(call *Call) {
arg := call.Args[1]
if !UniqueStringCutset(arg.Value) {
arg.Invalid(MsgNonUniqueCutset)
}
}
func unmarshalPointer(name string, arg int) CallCheck {
return func(call *Call) {
if !Pointer(call.Args[arg].Value) {
call.Args[arg].Invalid(fmt.Sprintf("%s expects to unmarshal into a pointer, but the provided value is not a pointer", name))
}
}
}
func pointlessIntMath(call *Call) {
if ConvertedFromInt(call.Args[0].Value) {
call.Invalid(fmt.Sprintf("calling %s on a converted integer is pointless", CallName(call.Instr.Common())))
}
}
func checkValidHostPort(arg int) CallCheck {
return func(call *Call) {
if !ValidHostPort(call.Args[arg].Value) {
call.Args[arg].Invalid(MsgInvalidHostPort)
}
}
}
var (
checkRegexpRules = map[string]CallCheck{
"regexp.MustCompile": validRegexp,
"regexp.Compile": validRegexp,
"regexp.Match": validRegexp,
"regexp.MatchReader": validRegexp,
"regexp.MatchString": validRegexp,
}
checkTimeParseRules = map[string]CallCheck{
"time.Parse": func(call *Call) {
arg := call.Args[Arg("time.Parse.layout")]
err := ValidateTimeLayout(arg.Value)
if err != nil {
arg.Invalid(err.Error())
}
},
}
checkEncodingBinaryRules = map[string]CallCheck{
"encoding/binary.Write": func(call *Call) {
arg := call.Args[Arg("encoding/binary.Write.data")]
if !CanBinaryMarshal(call.Pass, arg.Value) {
arg.Invalid(fmt.Sprintf("value of type %s cannot be used with binary.Write", arg.Value.Value.Type()))
}
},
}
checkURLsRules = map[string]CallCheck{
"net/url.Parse": func(call *Call) {
arg := call.Args[Arg("net/url.Parse.rawurl")]
err := ValidateURL(arg.Value)
if err != nil {
arg.Invalid(err.Error())
}
},
}
checkSyncPoolValueRules = map[string]CallCheck{
"(*sync.Pool).Put": func(call *Call) {
arg := call.Args[Arg("(*sync.Pool).Put.x")]
typ := arg.Value.Value.Type()
if !IsPointerLike(typ) {
arg.Invalid("argument should be pointer-like to avoid allocations")
}
},
}
checkRegexpFindAllRules = map[string]CallCheck{
"(*regexp.Regexp).FindAll": RepeatZeroTimes("a FindAll method", 1),
"(*regexp.Regexp).FindAllIndex": RepeatZeroTimes("a FindAll method", 1),
"(*regexp.Regexp).FindAllString": RepeatZeroTimes("a FindAll method", 1),
"(*regexp.Regexp).FindAllStringIndex": RepeatZeroTimes("a FindAll method", 1),
"(*regexp.Regexp).FindAllStringSubmatch": RepeatZeroTimes("a FindAll method", 1),
"(*regexp.Regexp).FindAllStringSubmatchIndex": RepeatZeroTimes("a FindAll method", 1),
"(*regexp.Regexp).FindAllSubmatch": RepeatZeroTimes("a FindAll method", 1),
"(*regexp.Regexp).FindAllSubmatchIndex": RepeatZeroTimes("a FindAll method", 1),
}
checkUTF8CutsetRules = map[string]CallCheck{
"strings.IndexAny": utf8Cutset,
"strings.LastIndexAny": utf8Cutset,
"strings.ContainsAny": utf8Cutset,
"strings.Trim": utf8Cutset,
"strings.TrimLeft": utf8Cutset,
"strings.TrimRight": utf8Cutset,
}
checkUniqueCutsetRules = map[string]CallCheck{
"strings.Trim": uniqueCutset,
"strings.TrimLeft": uniqueCutset,
"strings.TrimRight": uniqueCutset,
}
checkUnmarshalPointerRules = map[string]CallCheck{
"encoding/xml.Unmarshal": unmarshalPointer("xml.Unmarshal", 1),
"(*encoding/xml.Decoder).Decode": unmarshalPointer("Decode", 0),
"(*encoding/xml.Decoder).DecodeElement": unmarshalPointer("DecodeElement", 0),
"encoding/json.Unmarshal": unmarshalPointer("json.Unmarshal", 1),
"(*encoding/json.Decoder).Decode": unmarshalPointer("Decode", 0),
}
checkUnbufferedSignalChanRules = map[string]CallCheck{
"os/signal.Notify": func(call *Call) {
arg := call.Args[Arg("os/signal.Notify.c")]
if UnbufferedChannel(arg.Value) {
arg.Invalid("the channel used with signal.Notify should be buffered")
}
},
}
checkMathIntRules = map[string]CallCheck{
"math.Ceil": pointlessIntMath,
"math.Floor": pointlessIntMath,
"math.IsNaN": pointlessIntMath,
"math.Trunc": pointlessIntMath,
"math.IsInf": pointlessIntMath,
}
checkStringsReplaceZeroRules = map[string]CallCheck{
"strings.Replace": RepeatZeroTimes("strings.Replace", 3),
"bytes.Replace": RepeatZeroTimes("bytes.Replace", 3),
}
checkListenAddressRules = map[string]CallCheck{
"net/http.ListenAndServe": checkValidHostPort(0),
"net/http.ListenAndServeTLS": checkValidHostPort(0),
}
checkBytesEqualIPRules = map[string]CallCheck{
"bytes.Equal": func(call *Call) {
if ConvertedFrom(call.Args[Arg("bytes.Equal.a")].Value, "net.IP") &&
ConvertedFrom(call.Args[Arg("bytes.Equal.b")].Value, "net.IP") {
call.Invalid("use net.IP.Equal to compare net.IPs, not bytes.Equal")
}
},
}
checkRegexpMatchLoopRules = map[string]CallCheck{
"regexp.Match": loopedRegexp("regexp.Match"),
"regexp.MatchReader": loopedRegexp("regexp.MatchReader"),
"regexp.MatchString": loopedRegexp("regexp.MatchString"),
}
checkNoopMarshal = map[string]CallCheck{
// TODO(dh): should we really flag XML? Even an empty struct
// produces a non-zero amount of data, namely its type name.
// Let's see if we encounter any false positives.
//
// Also, should we flag gob?
"encoding/json.Marshal": checkNoopMarshalImpl(Arg("json.Marshal.v"), "MarshalJSON", "MarshalText"),
"encoding/xml.Marshal": checkNoopMarshalImpl(Arg("xml.Marshal.v"), "MarshalXML", "MarshalText"),
"(*encoding/json.Encoder).Encode": checkNoopMarshalImpl(Arg("(*encoding/json.Encoder).Encode.v"), "MarshalJSON", "MarshalText"),
"(*encoding/xml.Encoder).Encode": checkNoopMarshalImpl(Arg("(*encoding/xml.Encoder).Encode.v"), "MarshalXML", "MarshalText"),
"encoding/json.Unmarshal": checkNoopMarshalImpl(Arg("json.Unmarshal.v"), "UnmarshalJSON", "UnmarshalText"),
"encoding/xml.Unmarshal": checkNoopMarshalImpl(Arg("xml.Unmarshal.v"), "UnmarshalXML", "UnmarshalText"),
"(*encoding/json.Decoder).Decode": checkNoopMarshalImpl(Arg("(*encoding/json.Decoder).Decode.v"), "UnmarshalJSON", "UnmarshalText"),
"(*encoding/xml.Decoder).Decode": checkNoopMarshalImpl(Arg("(*encoding/xml.Decoder).Decode.v"), "UnmarshalXML", "UnmarshalTe E870 xt"),
}
checkUnsupportedMarshal = map[string]CallCheck{
"encoding/json.Marshal": checkUnsupportedMarshalImpl(Arg("json.Marshal.v"), "json", "MarshalJSON", "MarshalText"),
"encoding/xml.Marshal": checkUnsupportedMarshalImpl(Arg("xml.Marshal.v"), "xml", "MarshalXML", "MarshalText"),
"(*encoding/json.Encoder).Encode": checkUnsupportedMarshalImpl(Arg("(*encoding/json.Encoder).Encode.v"), "json", "MarshalJSON", "MarshalText"),
"(*encoding/xml.Encoder).Encode": checkUnsupportedMarshalImpl(Arg("(*encoding/xml.Encoder).Encode.v"), "xml", "MarshalXML", "MarshalText"),
}
checkAtomicAlignment = map[string]CallCheck{
"sync/atomic.AddInt64": checkAtomicAlignmentImpl,
"sync/atomic.AddUint64": checkAtomicAlignmentImpl,
"sync/atomic.CompareAndSwapInt64": checkAtomicAlignmentImpl,
"sync/atomic.CompareAndSwapUint64": checkAtomicAlignmentImpl,
"sync/atomic.LoadInt64": checkAtomicAlignmentImpl,
"sync/atomic.LoadUint64": checkAtomicAlignmentImpl,
"sync/atomic.StoreInt64": checkAtomicAlignmentImpl,
"sync/atomic.StoreUint64": checkAtomicAlignmentImpl,
"sync/atomic.SwapInt64": checkAtomicAlignmentImpl,
"sync/atomic.SwapUint64": checkAtomicAlignmentImpl,
}
// TODO(dh): detect printf wrappers
checkPrintfRules = map[string]CallCheck{
"fmt.Errorf": func(call *Call) { checkPrintfCall(call, 0, 1) },
"fmt.Printf": func(call *Call) { checkPrintfCall(call, 0, 1) },
"fmt.Sprintf": func(call *Call) { checkPrintfCall(call, 0, 1) },
"fmt.Fprintf": func(call *Call) { checkPrintfCall(call, 1, 2) },
}
)
func checkPrintfCall(call *Call, fIdx, vIdx int) {
f := call.Args[fIdx]
var args []ssa.Value
switch v := call.Args[vIdx].Value.Value.(type) {
case *ssa.Slice:
var ok bool
args, ok = ssautil.Vararg(v)
if !ok {
// We don't know what the actual arguments to the function are
return
}
case *ssa.Const:
// nil, i.e. no arguments
default:
// We don't know what the actual arguments to the function are
return
}
checkPrintfCallImpl(call, f.Value.Value, args)
}
type verbFlag int
const (
isInt verbFlag = 1 << iota
isBool
isFP
isString
isPointer
isPseudoPointer
isSlice
isAny
noRecurse
)
var verbs = [...]verbFlag{
'b': isPseudoPointer | isInt | isFP,
'c': isInt,
'd': isPseudoPointer | isInt,
'e': isFP,
'E': isFP,
'f': isFP,
'F': isFP,
'g': isFP,
'G': isFP,
'o': isPseudoPointer | isInt,
'p': isSlice | isPointer | noRecurse,
'q': isInt | isString,
's': isString,
't': isBool,
'T': isAny,
'U': isInt,
'v': isAny,
'X': isPseudoPointer | isInt | isString,
'x': isPseudoPointer | isInt | isString,
}
func checkPrintfCallImpl(call *Call, f ssa.Value, args []ssa.Value) {
var msCache *typeutil.MethodSetCache
if f.Parent() != nil {
msCache = &f.Parent().Prog.MethodSets
}
elem := func(T types.Type, verb rune) ([]types.Type, bool) {
if verbs[verb]&noRecurse != 0 {
return []types.Type{T}, false
}
switch T := T.(type) {
case *types.Slice:
if verbs[verb]&isSlice != 0 {
return []types.Type{T}, false
}
if verbs[verb]&isString != 0 && IsType(T.Elem().Underlying(), "byte") {
return []types.Type{T}, false
}
return []types.Type{T.Elem()}, true
case *types.Map:
key := T.Key()
val := T.Elem()
return []types.Type{key, val}, true
case *types.Struct:
out := make([]types.Type, 0, T.NumFields())
for i := 0; i < T.NumFields(); i++ {
out = append(out, T.Field(i).Type())
}
return out, true
case *types.Array:
return []types.Type{T.Elem()}, true
default:
return []types.Type{T}, false
}
}
isInfo := func(T types.Type, info types.BasicInfo) bool {
basic, ok := T.Underlying().(*types.Basic)
return ok && basic.Info()&info != 0
}
isStringer := func(T types.Type, ms *types.MethodSet) bool {
sel := ms.Lookup(nil, "String")
if sel == nil {
return false
}
fn, ok := sel.Obj().(*types.Func)
if !ok {
// should be unreachable
return false
}
sig := fn.Type().(*types.Signature)
if sig.Params().Len() != 0 {
return false
}
if sig.Results().Len() != 1 {
return false
}
if !IsType(sig.Results().At(0).Type(), "string") {
return false
}
return true
}
isError := func(T types.Type, ms *types.MethodSet) bool {
sel := ms.Lookup(nil, "Error")
if sel == nil {
return false
}
fn, ok := sel.Obj().(*types.Func)
if !ok {
// should be unreachable
return false
}
sig := fn.Type().(*types.Signature)
if sig.Params().Len() != 0 {
return false
}
if sig.Results().Len() != 1 {
return false
}
if !IsType(sig.Results().At(0).Type(), "string") {
return false
}
return true
}
isFormatter := func(T types.Type, ms *types.MethodSet) bool {
sel := ms.Lookup(nil, "Format")
if sel == nil {
return false
}
fn, ok := sel.Obj().(*types.Func)
if !ok {
// should be unreachable
return false
}
sig := fn.Type().(*types.Signature)
if sig.Params().Len() != 2 {
return false
}
// TODO(dh): check the types of the arguments for more
// precision
if sig.Results().Len() != 0 {
return false
}
return true
}
seen := map[types.Type]bool{}
var checkType func(verb rune, T types.Type, top bool) bool
checkType = func(verb rune, T types.Type, top bool) bool {
if top {
for k := range seen {
delete(seen, k)
}
}
if seen[T] {
return true
}
seen[T] = true
if int(verb) >= len(verbs) {
// Unknown verb
return true
}
flags := verbs[verb]
if flags == 0 {
// Unknown verb
return true
}
ms := msCache.MethodSet(T)
if isFormatter(T, ms) {
// the value is responsible for formatting itself
return true
}
if flags&isString != 0 && (isStringer(T, ms) || isError(T, ms)) {
// Check for stringer early because we're about to dereference
return true
}
T = T.Underlying()
if flags&(isPointer|isPseudoPointer) == 0 && top {
T = Dereference(T)
}
if flags&isPseudoPointer != 0 && top {
t := Dereference(T)
if _, ok := t.Underlying().(*types.Struct); ok {
T = t
}
}
if _, ok := T.(*types.Interface); ok {
// We don't know what's in the interface
return true
}
var info types.BasicInfo
if flags&isInt != 0 {
info |= types.IsInteger
}
if flags&isBool != 0 {
info |= types.IsBoolean
}
if flags&isFP != 0 {
info |= types.IsFloat | types.IsComplex
}
if flags&isString != 0 {
info |= types.IsString
}
if info != 0 && isInfo(T, info) {
return true
}
if flags&isString != 0 && (IsType(T, "[]byte") || isStringer(T, ms) || isError(T, ms)) {
return true
}
if flags&isPointer != 0 && IsPointerLike(T) {
return true
}
if flags&isPseudoPointer != 0 {
switch U := T.Underlying().(type) {
case *types.Pointer:
if !top {
return true
}
if _, ok := U.Elem().Underlying().(*types.Struct); !ok {
return true
}
case *types.Chan, *types.Signature:
return true
}
}
if flags&isSlice != 0 {
if _, ok := T.(*types.Slice); ok {
return true
}
}
if flags&isAny != 0 {
return true
}
elems, ok := elem(T.Underlying(), verb)
if !ok {
return false
}
for _, elem := range elems {
if !checkType(verb, elem, false) {
return false
}
}
return true
}
k, ok := f.(*ssa.Const)
if !ok {
return
}
actions, err := printf.Parse(constant.StringVal(k.Value))
if err != nil {
call.Invalid("couldn't parse format string")
return
}
ptr := 1
hasExplicit := false
checkStar := func(verb printf.Verb, star printf.Argument) bool {
if star, ok := star.(printf.Star); ok {
idx := 0
if star.Index == -1 {
idx = ptr
ptr++
} else {
hasExplicit = true
idx = star.Index
ptr = star.Index + 1
}
if idx == 0 {
call.Invalid(fmt.Sprintf("Printf format %s reads invalid arg 0; indices are 1-based", verb.Raw))
return false
}
if idx > len(args) {
call.Invalid(
fmt.Sprintf("Printf format %s reads arg #%d, but call has only %d args",
verb.Raw, idx, len(args)))
return false
}
if arg, ok := args[idx-1].(*ssa.MakeInterface); ok {
if !isInfo(arg.X.Type(), types.IsInteger) {
call.Invalid(fmt.Sprintf("Printf format %s reads non-int arg #%d as argument of *", verb.Raw, idx))
}
}
}
return true
}
// We only report one problem per format string. Making a
// mistake with an index tends to invalidate all future
// implicit indices.
for _, action := range actions {
verb, ok := action.(printf.Verb)
if !ok {
continue
}
if !checkStar(verb, verb.Width) || !checkStar(verb, verb.Precision) {
return
}
off := ptr
if verb.Value != -1 {
hasExplicit = true
off = verb.Value
}
if off > len(args) {
call.Invalid(
fmt.Sprintf("Printf format %s reads arg #%d, but call has only %d args",
verb.Raw, off, len(args)))
return
} else if verb.Value == 0 && verb.Letter != '%' {
call.Invalid(fmt.Sprintf("Printf format %s reads invalid arg 0; indices are 1-based", verb.Raw))
return
} else if off != 0 {
arg, ok := args[off-1].(*ssa.MakeInterface)
if ok {
if !checkType(verb.Letter, arg.X.Type(), true) {
call.Invalid(fmt.Sprintf("Printf format %s has arg #%d of wrong type %s",
verb.Raw, ptr, args[ptr-1].(*ssa.MakeInterface).X.Type()))
return
}
}
}
switch verb.Value {
case -1:
// Consume next argument
ptr++
case 0:
// Don't consume any arguments
default:
ptr = verb.Value + 1
}
}
if !hasExplicit && ptr <= len(args) {
call.Invalid(fmt.Sprintf("Printf call needs %d args but has %d args", ptr-1, len(args)))
}
}
func checkAtomicAlignmentImpl(call *Call) {
sizes := call.Pass.TypesSizes
if sizes.Sizeof(types.Typ[types.Uintptr]) != 4 {
// Not running on a 32-bit platform
return
}
v, ok := call.Args[0].Value.Value.(*ssa.FieldAddr)
if !ok {
// TODO(dh): also check indexing into arrays and slices
return
}
T := v.X.Type().Underlying().(*types.Pointer).Elem().Underlying().(*types.Struct)
fields := make([]*types.Var, 0, T.NumFields())
for i := 0; i < T.NumFields() && i <= v.Field; i++ {
fields = append(fields, T.Field(i))
}
off := sizes.Offsetsof(fields)[v.Field]
if off%8 != 0 {
msg := fmt.Sprintf("address of non 64-bit aligned field %s passed to %s",
T.Field(v.Field).Name(),
CallName(call.Instr.Common()))
call.Invalid(msg)
}
}
func checkNoopMarshalImpl(argN int, meths ...string) CallCheck {
return func(call *Call) {
if IsGenerated(call.Pass, call.Instr.Pos()) {
return
}
arg := call.Args[argN]
T := arg.Value.Value.Type()
Ts, ok := Dereference(T).Underlying().(*types.Struct)
if !ok {
return
}
if Ts.NumFields() == 0 {
return
}
fields := FlattenFields(Ts)
for _, field := range fields {
if field.Var.Exported() {
return
}
}
// OPT(dh): we could use a method set cache here
ms := call.Instr.Parent().Prog.MethodSets.MethodSet(T)
// TODO(dh): we're not checking the signature, which can cause false negatives.
// This isn't a huge problem, however, since vet complains about incorrect signatures.
for _, meth := range meths {
if ms.Lookup(nil, meth) != nil {
return
}
}
arg.Invalid("struct doesn't have any exported fields, nor custom marshaling")
}
}
func checkUnsupportedMarshalImpl(argN int, tag string, meths ...string) CallCheck {
// TODO(dh): flag slices and maps of unsupported types
return func(call *Call) {
msCache := &call.Instr.Parent().Prog.MethodSets
arg := call.Args[argN]
T := arg.Value.Value.Type()
Ts, ok := Dereference(T).Underlying().(*types.Struct)
if !ok {
return
}
ms := msCache.MethodSet(T)
// TODO(dh): we're not checking the signature, which can cause false negatives.
// This isn't a huge problem, however, since vet complains about incorrect signatures.
for _, meth := range meths {
if ms.Lookup(nil, meth) != nil {
return
}
}
fields := FlattenFields(Ts)
for _, field := range fields {
if !(field.Var.Exported()) {
continue
}
if reflect.StructTag(field.Tag).Get(tag) == "-" {
continue
}
ms := msCache.MethodSet(field.Var.Type())
// TODO(dh): we're not checking the signature, which can cause false negatives.
// This isn't a huge problem, however, since vet complains about incorrect signatures.
for _, meth := range meths {
if ms.Lookup(nil, meth) != nil {
return
}
}
switch field.Var.Type().Underlying().(type) {
case *types.Chan, *types.Signature:
arg.Invalid(fmt.Sprintf("trying to marshal chan or func value, field %s", fieldPath(T, field.Path)))
}
}
}
}
func fieldPath(start types.Type, indices []int) string {
p := start.String()
for _, idx := range indices {
field := Dereference(start).Underlying().(*types.Struct).Field(idx)
start = field.Type()
p += "." + field.Name()
}
return p
}
func isInLoop(b *ssa.BasicBlock) bool {
sets := functions.FindLoops(b.Parent())
for _, set := range sets {
if set.Has(b) {
return true
}
}
return false
}
func CheckUntrappableSignal(pass *analysis.Pass) (interface{}, error) {
fn := func(node ast.Node) {
call := node.(*ast.CallExpr)
if !IsCallToAnyAST(pass, call,
"os/signal.Ignore", "os/signal.Notify", "os/signal.Reset") {
return
}
for _, arg := range call.Args {
if conv, ok := arg.(*ast.CallExpr); ok && isName(pass, conv.Fun, "os.Signal") {
arg = conv.Args[0]
}
if isName(pass, arg, "os.Kill") || isName(pass, arg, "syscall.SIGKILL") {
ReportNodef(pass, arg, "%s cannot be trapped (did you mean syscall.SIGTERM?)", Render(pass, arg))
}
if isName(pass, arg, "syscall.SIGSTOP") {
ReportNodef(pass, arg, "%s signal cannot be trapped", Render(pass, arg))
}
}
}
pass.ResultOf[inspect.Analyzer].(*inspector.Inspector).Preorder([]ast.Node{(*ast.CallExpr)(nil)}, fn)
return nil, nil
}
func CheckTemplate(pass *analysis.Pass) (interface{}, error) {
fn := func(node ast.Node) {
call := node.(*ast.CallExpr)
var kind string
if IsCallToAST(pass, call, "(*text/template.Template).Parse") {
kind = "text"
} else if IsCallToAST(pass, call, "(*html/template.Template).Parse") {
kind = "html"
} else {
return
}
sel := call.Fun.(*ast.SelectorExpr)
if !IsCallToAST(pass, sel.X, "text/template.New") &&
!IsCallToAST(pass, sel.X, "html/template.New") {
// TODO(dh): this is a cheap workaround for templates with
// different delims. A better solution with less false
// negatives would use data flow analysis to see where the
// template comes from and where it has been
return
}
s, ok := ExprToString(pass, call.Args[Arg("(*text/template.Template).Parse.text")])
if !ok {
return
}
var err error
switch kind {
case "text":
_, err = texttemplate.New("").Parse(s)
case "html":
_, err = htmltemplate.New("").Parse(s)
}
if err != nil {
// TODO(dominikh): whitelist other parse errors, if any
if strings.Contains(err.Error(), "unexpected") {
ReportNodef(pass, call.Args[Arg("(*text/template.Template).Parse.text")], "%s", err)
}
}
}
pass.ResultOf[inspect.Analyzer].(*inspector.Inspector).Preorder([]ast.Node{(*ast.CallExpr)(nil)}, fn)
return nil, nil
}
func CheckTimeSleepConstant(pass *analysis.Pass) (interface{}, error) {
fn := func(node ast.Node) {
call := node.(*ast.CallExpr)
if !IsCallToAST(pass, call, "time.Sleep") {
return
}
lit, ok := call.Args[Arg("time.Sleep.d")].(*ast.BasicLit)
if !ok {
return
}
n, err := strconv.Atoi(lit.Value)
if err != nil {
return
}
if n == 0 || n > 120 {
// time.Sleep(0) is a seldom used pattern in concurrency
// tests. >120 might be intentional. 120 was chosen
// because the user could've meant 2 minutes.
return
}
recommendation := "time.Sleep(time.Nanosecond)"
if n != 1 {
recommendation = fmt.Sprintf("time.Sleep(%d * time.Nanosecond)", n)
}
ReportNodef(pass, call.Args[Arg("time.Sleep.d")],
"sleeping for %d nanoseconds is probably a bug. Be explicit if it isn't: %s", n, recommendation)
}
pass.ResultOf[inspect.Analyzer].(*inspector.Inspector).Preorder([]ast.Node{(*ast.CallExpr)(nil)}, fn)
return nil, nil
}
func CheckWaitgroupAdd(pass *analysis.Pass) (interface{}, error) {
fn := func(node ast.Node) {
g := node.(*ast.GoStmt)
fun, ok := g.Call.Fun.(*ast.FuncLit)
if !ok {
return
}
if len(fun.Body.List) == 0 {
return
}
stmt, ok := fun.Body.List[0].(*ast.ExprStmt)
if !ok {
return
}
if IsCallToAST(pass, stmt.X, "(*sync.WaitGroup).Add") {
ReportNodef(pass, stmt, "should call %s before starting the goroutine to avoid a race",
Render(pass, stmt))
}
}
pass.ResultOf[inspect.Analyzer].(*inspector.Inspector).Preorder([]ast.Node{(*ast.GoStmt)(nil)}, fn)
return nil, nil
}
func CheckInfiniteEmptyLoop(pass *analysis.Pass) (interface{}, error) {
fn := func(node ast.Node) {
loop := node.(*ast.ForStmt)
if len(loop.Body.List) != 0 || loop.Post != nil {
return
}
if loop.Init != nil {
// TODO(dh): this isn't strictly necessary, it just makes
// the check easier.
return
}
// An empty loop is bad news in two cases: 1) The loop has no
// condition. In that case, it's just a loop that spins
// forever and as fast as it can, keeping a core busy. 2) The
// loop condition only consists of variable or field reads and
// operators on those. The only way those could change their
// value is with unsynchronised access, which constitutes a
// data race.
//
// If the condition contains any function calls, its behaviour
// is dynamic and the loop might terminate. Similarly for
// channel receives.
if loop.Cond != nil {
if hasSideEffects(loop.Cond) {
return
}
if ident, ok := loop.Cond.(*ast.Ident); ok {
if k, ok := pass.TypesInfo.ObjectOf(ident).(*types.Const); ok {
if !constant.BoolVal(k.Val()) {
// don't flag `for false {}` loops. They're a debug aid.
return
}
}
}
ReportNodef(pass, loop, "loop condition never changes or has a race condition")
}
ReportNodef(pass, loop, "this loop will spin, using 100%% CPU")
}
pass.ResultOf[inspect.Analyzer].(*inspector.Inspector).Preorder([]ast.Node{(*ast.ForStmt)(nil)}, fn)
return nil, nil
}
func CheckDeferInInfiniteLoop(pass *analysis.Pass) (interface{}, error) {
fn := func(node ast.Node) {
mightExit := false
var defers []ast.Stmt
loop := node.(*ast.ForStmt)
if loop.Cond != nil {
return
}
fn2 := func(node ast.Node) bool {
switch stmt := node.(type) {
case *ast.ReturnStmt:
mightExit = true
return false
case *ast.BranchStmt:
// TODO(dominikh): if this sees a break in a switch or
// select, it doesn't check if it breaks the loop or
// just the select/switch. This causes some false
// negatives.
if stmt.Tok == token.BREAK {
mightExit = true
return false
}
case *ast.DeferStmt:
defers = append(defers, stmt)
case *ast.FuncLit:
// Don't look into function bodies
return false
}
return true
}
ast.Inspect(loop.Body, fn2)
if mightExit {
return
}
for _, stmt := range defers {
ReportNodef(pass, stmt, "defers in this infinite loop will never run")
}
}
pass.ResultOf[inspect.Analyzer].(*inspector.Inspector).Preorder([]ast.Node{(*ast.ForStmt)(nil)}, fn)
return nil, nil
}
func CheckDubiousDeferInChannelRangeLoop(pass *analysis.Pass) (interface{}, error) {
fn := func(node ast.Node) {
loop := node.(*ast.RangeStmt)
typ := pass.TypesInfo.TypeOf(loop.X)
_, ok := typ.Underlying().(*types.Chan)
if !ok {
return
}
fn2 := func(node ast.Node) bool {
switch stmt := node.(type) {
case *ast.DeferStmt:
ReportNodef(pass, stmt, "defers in this range loop won't run unless the channel gets closed")
case *ast.FuncLit:
// Don't look into function bodies
return false
}
return true
}
ast.Inspect(loop.Body, fn2)
}
pass.ResultOf[inspect.Analyzer].(*inspector.Inspector).Preorder([]ast.Node{(*ast.RangeStmt)(nil)}, fn)
return nil, nil
}
func CheckTestMainExit(pass *analysis.Pass) (interface{}, error) {
var (
fnmain ast.Node
callsExit bool
callsRun bool
arg types.Object
)
fn := func(node ast.Node, push bool) bool {
if !push {
if fnmain != nil && node == fnmain {
if !callsExit && callsRun {
ReportNodef(pass, fnmain, "TestMain should call os.Exit to set exit code")
}
fnmain = nil
callsExit = false
callsRun = false
0