vikunja-api/vendor/honnef.co/go/tools/simple/lint.go

1817 lines
45 KiB
Go
Raw Permalink Normal View History

2018-12-28 23:15:05 +01:00
// Package simple contains a linter for Go source code.
package simple // import "honnef.co/go/tools/simple"
import (
2019-04-22 12:59:42 +02:00
"fmt"
2018-12-28 23:15:05 +01:00
"go/ast"
"go/constant"
"go/token"
"go/types"
"reflect"
"sort"
2018-12-28 23:15:05 +01:00
"strings"
"golang.org/x/tools/go/analysis"
"golang.org/x/tools/go/analysis/passes/inspect"
"golang.org/x/tools/go/ast/inspector"
"golang.org/x/tools/go/types/typeutil"
2019-02-18 20:32:41 +01:00
. "honnef.co/go/tools/arg"
"honnef.co/go/tools/internal/passes/buildssa"
2018-12-28 23:15:05 +01:00
"honnef.co/go/tools/internal/sharedcheck"
"honnef.co/go/tools/lint"
. "honnef.co/go/tools/lint/lintdsl"
)
func LintSingleCaseSelect(pass *analysis.Pass) (interface{}, error) {
2018-12-28 23:15:05 +01:00
isSingleSelect := func(node ast.Node) bool {
v, ok := node.(*ast.SelectStmt)
if !ok {
return false
}
return len(v.Body.List) == 1
}
seen := map[ast.Node]struct{}{}
2019-04-22 12:59:42 +02:00
fn := func(node ast.Node) {
2018-12-28 23:15:05 +01:00
switch v := node.(type) {
case *ast.ForStmt:
if len(v.Body.List) != 1 {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
if !isSingleSelect(v.Body.List[0]) {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
if _, ok := v.Body.List[0].(*ast.SelectStmt).Body.List[0].(*ast.CommClause).Comm.(*ast.SendStmt); ok {
// Don't suggest using range for channel sends
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
seen[v.Body.List[0]] = struct{}{}
ReportNodefFG(pass, node, "should use for range instead of for { select {} }")
2018-12-28 23:15:05 +01:00
case *ast.SelectStmt:
if _, ok := seen[v]; ok {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
if !isSingleSelect(v) {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
ReportNodefFG(pass, node, "should use a simple channel send/receive instead of select with a single case")
2018-12-28 23:15:05 +01:00
}
}
pass.ResultOf[inspect.Analyzer].(*inspector.Inspector).Preorder([]ast.Node{(*ast.ForStmt)(nil), (*ast.SelectStmt)(nil)}, fn)
return nil, nil
2018-12-28 23:15:05 +01:00
}
func LintLoopCopy(pass *analysis.Pass) (interface{}, error) {
2019-04-22 12:59:42 +02:00
fn := func(node ast.Node) {
loop := node.(*ast.RangeStmt)
2018-12-28 23:15:05 +01:00
if loop.Key == nil {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
if len(loop.Body.List) != 1 {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
stmt, ok := loop.Body.List[0].(*ast.AssignStmt)
if !ok {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
if stmt.Tok != token.ASSIGN || len(stmt.Lhs) != 1 || len(stmt.Rhs) != 1 {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
lhs, ok := stmt.Lhs[0].(*ast.IndexExpr)
if !ok {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
2019-02-18 20:32:41 +01:00
if _, ok := pass.TypesInfo.TypeOf(lhs.X).(*types.Slice); !ok {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
lidx, ok := lhs.Index.(*ast.Ident)
if !ok {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
key, ok := loop.Key.(*ast.Ident)
if !ok {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
if pass.TypesInfo.TypeOf(lhs) == nil || pass.TypesInfo.TypeOf(stmt.Rhs[0]) == nil {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
if pass.TypesInfo.ObjectOf(lidx) != pass.TypesInfo.ObjectOf(key) {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
if !types.Identical(pass.TypesInfo.TypeOf(lhs), pass.TypesInfo.TypeOf(stmt.Rhs[0])) {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
if _, ok := pass.TypesInfo.TypeOf(loop.X).(*types.Slice); !ok {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
if rhs, ok := stmt.Rhs[0].(*ast.IndexExpr); ok {
rx, ok := rhs.X.(*ast.Ident)
_ = rx
if !ok {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
ridx, ok := rhs.Index.(*ast.Ident)
if !ok {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
if pass.TypesInfo.ObjectOf(ridx) != pass.TypesInfo.ObjectOf(key) {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
} else if rhs, ok := stmt.Rhs[0].(*ast.Ident); ok {
value, ok := loop.Value.(*ast.Ident)
if !ok {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
if pass.TypesInfo.ObjectOf(rhs) != pass.TypesInfo.ObjectOf(value) {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
} else {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
ReportNodefFG(pass, loop, "should use copy() instead of a loop")
2018-12-28 23:15:05 +01:00
}
pass.ResultOf[inspect.Analyzer].(*inspector.Inspector).Preorder([]ast.Node{(*ast.RangeStmt)(nil)}, fn)
return nil, nil
2018-12-28 23:15:05 +01:00
}
func LintIfBoolCmp(pass *analysis.Pass) (interface{}, error) {
2019-04-22 12:59:42 +02:00
fn := func(node ast.Node) {
expr := node.(*ast.BinaryExpr)
if expr.Op != token.EQL && expr.Op != token.NEQ {
return
2018-12-28 23:15:05 +01:00
}
x := IsBoolConst(pass, expr.X)
y := IsBoolConst(pass, expr.Y)
2018-12-28 23:15:05 +01:00
if !x && !y {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
var other ast.Expr
var val bool
if x {
val = BoolConst(pass, expr.X)
2018-12-28 23:15:05 +01:00
other = expr.Y
} else {
val = BoolConst(pass, expr.Y)
2018-12-28 23:15:05 +01:00
other = expr.X
}
basic, ok := pass.TypesInfo.TypeOf(other).Underlying().(*types.Basic)
2018-12-28 23:15:05 +01:00
if !ok || basic.Kind() != types.Bool {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
op := ""
if (expr.Op == token.EQL && !val) || (expr.Op == token.NEQ && val) {
op = "!"
}
r := op + Render(pass, other)
2018-12-28 23:15:05 +01:00
l1 := len(r)
r = strings.TrimLeft(r, "!")
if (l1-len(r))%2 == 1 {
r = "!" + r
}
if IsInTest(pass, node) {
2019-04-22 12:59:42 +02:00
return
2019-02-18 20:32:41 +01:00
}
ReportNodefFG(pass, expr, "should omit comparison to bool constant, can be simplified to %s", r)
2018-12-28 23:15:05 +01:00
}
pass.ResultOf[inspect.Analyzer].(*inspector.Inspector).Preorder([]ast.Node{(*ast.BinaryExpr)(nil)}, fn)
return nil, nil
2018-12-28 23:15:05 +01:00
}
func LintBytesBufferConversions(pass *analysis.Pass) (interface{}, error) {
2019-04-22 12:59:42 +02:00
fn := func(node ast.Node) {
call := node.(*ast.CallExpr)
if len(call.Args) != 1 {
return
2018-12-28 23:15:05 +01:00
}
argCall, ok := call.Args[0].(*ast.CallExpr)
if !ok {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
sel, ok := argCall.Fun.(*ast.SelectorExpr)
if !ok {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
typ := pass.TypesInfo.TypeOf(call.Fun)
if typ == types.Universe.Lookup("string").Type() && IsCallToAST(pass, call.Args[0], "(*bytes.Buffer).Bytes") {
ReportNodefFG(pass, call, "should use %v.String() instead of %v", Render(pass, sel.X), Render(pass, call))
} else if typ, ok := typ.(*types.Slice); ok && typ.Elem() == types.Universe.Lookup("byte").Type() && IsCallToAST(pass, call.Args[0], "(*bytes.Buffer).String") {
ReportNodefFG(pass, call, "should use %v.Bytes() instead of %v", Render(pass, sel.X), Render(pass, call))
2018-12-28 23:15:05 +01:00
}
}
pass.ResultOf[inspect.Analyzer].(*inspector.Inspector).Preorder([]ast.Node{(*ast.CallExpr)(nil)}, fn)
return nil, nil
2018-12-28 23:15:05 +01:00
}
func LintStringsContains(pass *analysis.Pass) (interface{}, error) {
2018-12-28 23:15:05 +01:00
// map of value to token to bool value
allowed := map[int64]map[token.Token]bool{
-1: {token.GTR: true, token.NEQ: true, token.EQL: false},
0: {token.GEQ: true, token.LSS: false},
}
2019-04-22 12:59:42 +02:00
fn := func(node ast.Node) {
expr := node.(*ast.BinaryExpr)
2018-12-28 23:15:05 +01:00
switch expr.Op {
case token.GEQ, token.GTR, token.NEQ, token.LSS, token.EQL:
default:
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
value, ok := ExprToInt(pass, expr.Y)
2018-12-28 23:15:05 +01:00
if !ok {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
allowedOps, ok := allowed[value]
if !ok {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
b, ok := allowedOps[expr.Op]
if !ok {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
call, ok := expr.X.(*ast.CallExpr)
if !ok {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
sel, ok := call.Fun.(*ast.SelectorExpr)
if !ok {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
pkgIdent, ok := sel.X.(*ast.Ident)
if !ok {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
funIdent := sel.Sel
if pkgIdent.Name != "strings" && pkgIdent.Name != "bytes" {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
newFunc := ""
switch funIdent.Name {
case "IndexRune":
newFunc = "ContainsRune"
case "IndexAny":
newFunc = "ContainsAny"
case "Index":
newFunc = "Contains"
default:
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
prefix := ""
if !b {
prefix = "!"
}
ReportNodefFG(pass, node, "should use %s%s.%s(%s) instead", prefix, pkgIdent.Name, newFunc, RenderArgs(pass, call.Args))
2018-12-28 23:15:05 +01:00
}
pass.ResultOf[inspect.Analyzer].(*inspector.Inspector).Preorder([]ast.Node{(*ast.BinaryExpr)(nil)}, fn)
return nil, nil
2018-12-28 23:15:05 +01:00
}
func LintBytesCompare(pass *analysis.Pass) (interface{}, error) {
2019-04-22 12:59:42 +02:00
fn := func(node ast.Node) {
expr := node.(*ast.BinaryExpr)
2018-12-28 23:15:05 +01:00
if expr.Op != token.NEQ && expr.Op != token.EQL {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
call, ok := expr.X.(*ast.CallExpr)
if !ok {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
if !IsCallToAST(pass, call, "bytes.Compare") {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
value, ok := ExprToInt(pass, expr.Y)
2018-12-28 23:15:05 +01:00
if !ok || value != 0 {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
args := RenderArgs(pass, call.Args)
2018-12-28 23:15:05 +01:00
prefix := ""
if expr.Op == token.NEQ {
prefix = "!"
}
ReportNodefFG(pass, node, "should use %sbytes.Equal(%s) instead", prefix, args)
2018-12-28 23:15:05 +01:00
}
pass.ResultOf[inspect.Analyzer].(*inspector.Inspector).Preorder([]ast.Node{(*ast.BinaryExpr)(nil)}, fn)
return nil, nil
2018-12-28 23:15:05 +01:00
}
func LintForTrue(pass *analysis.Pass) (interface{}, error) {
2019-04-22 12:59:42 +02:00
fn := func(node ast.Node) {
loop := node.(*ast.ForStmt)
2018-12-28 23:15:05 +01:00
if loop.Init != nil || loop.Post != nil {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
if !IsBoolConst(pass, loop.Cond) || !BoolConst(pass, loop.Cond) {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
ReportNodefFG(pass, loop, "should use for {} instead of for true {}")
2018-12-28 23:15:05 +01:00
}
pass.ResultOf[inspect.Analyzer].(*inspector.Inspector).Preorder([]ast.Node{(*ast.ForStmt)(nil)}, fn)
return nil, nil
2018-12-28 23:15:05 +01:00
}
func LintRegexpRaw(pass *analysis.Pass) (interface{}, error) {
2019-04-22 12:59:42 +02:00
fn := func(node ast.Node) {
call := node.(*ast.CallExpr)
if !IsCallToAST(pass, call, "regexp.MustCompile") &&
!IsCallToAST(pass, call, "regexp.Compile") {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
sel, ok := call.Fun.(*ast.SelectorExpr)
if !ok {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
if len(call.Args) != 1 {
// invalid function call
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
2019-02-18 20:32:41 +01:00
lit, ok := call.Args[Arg("regexp.Compile.expr")].(*ast.BasicLit)
2018-12-28 23:15:05 +01:00
if !ok {
// TODO(dominikh): support string concat, maybe support constants
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
if lit.Kind != token.STRING {
// invalid function call
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
if lit.Value[0] != '"' {
// already a raw string
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
val := lit.Value
if !strings.Contains(val, `\\`) {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
2019-02-18 20:32:41 +01:00
if strings.Contains(val, "`") {
2019-04-22 12:59:42 +02:00
return
2019-02-18 20:32:41 +01:00
}
2018-12-28 23:15:05 +01:00
bs := false
for _, c := range val {
if !bs && c == '\\' {
bs = true
continue
}
if bs && c == '\\' {
bs = false
continue
}
if bs {
// backslash followed by non-backslash -> escape sequence
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
}
ReportNodefFG(pass, call, "should use raw string (`...`) with regexp.%s to avoid having to escape twice", sel.Sel.Name)
2018-12-28 23:15:05 +01:00
}
pass.ResultOf[inspect.Analyzer].(*inspector.Inspector).Preorder([]ast.Node{(*ast.CallExpr)(nil)}, fn)
return nil, nil
2018-12-28 23:15:05 +01:00
}
func LintIfReturn(pass *analysis.Pass) (interface{}, error) {
2019-04-22 12:59:42 +02:00
fn := func(node ast.Node) {
block := node.(*ast.BlockStmt)
2018-12-28 23:15:05 +01:00
l := len(block.List)
if l < 2 {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
n1, n2 := block.List[l-2], block.List[l-1]
if len(block.List) >= 3 {
if _, ok := block.List[l-3].(*ast.IfStmt); ok {
// Do not flag a series of if statements
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
}
// if statement with no init, no else, a single condition
// checking an identifier or function call and just a return
// statement in the body, that returns a boolean constant
ifs, ok := n1.(*ast.IfStmt)
if !ok {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
if ifs.Else != nil || ifs.Init != nil {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
if len(ifs.Body.List) != 1 {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
if op, ok := ifs.Cond.(*ast.BinaryExpr); ok {
switch op.Op {
case token.EQL, token.LSS, token.GTR, token.NEQ, token.LEQ, token.GEQ:
default:
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
}
ret1, ok := ifs.Body.List[0].(*ast.ReturnStmt)
if !ok {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
if len(ret1.Results) != 1 {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
if !IsBoolConst(pass, ret1.Results[0]) {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
ret2, ok := n2.(*ast.ReturnStmt)
if !ok {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
if len(ret2.Results) != 1 {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
if !IsBoolConst(pass, ret2.Results[0]) {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
if ret1.Results[0].(*ast.Ident).Name == ret2.Results[0].(*ast.Ident).Name {
// we want the function to return true and false, not the
// same value both times.
return
}
ReportNodefFG(pass, n1, "should use 'return <expr>' instead of 'if <expr> { return <bool> }; return <bool>'")
2018-12-28 23:15:05 +01:00
}
pass.ResultOf[inspect.Analyzer].(*inspector.Inspector).Preorder([]ast.Node{(*ast.BlockStmt)(nil)}, fn)
return nil, nil
2018-12-28 23:15:05 +01:00
}
// LintRedundantNilCheckWithLen checks for the following reduntant nil-checks:
//
// if x == nil || len(x) == 0 {}
// if x != nil && len(x) != 0 {}
// if x != nil && len(x) == N {} (where N != 0)
// if x != nil && len(x) > N {}
// if x != nil && len(x) >= N {} (where N != 0)
//
func LintRedundantNilCheckWithLen(pass *analysis.Pass) (interface{}, error) {
2018-12-28 23:15:05 +01:00
isConstZero := func(expr ast.Expr) (isConst bool, isZero bool) {
_, ok := expr.(*ast.BasicLit)
if ok {
return true, IsZero(expr)
}
id, ok := expr.(*ast.Ident)
if !ok {
return false, false
}
c, ok := pass.TypesInfo.ObjectOf(id).(*types.Const)
2018-12-28 23:15:05 +01:00
if !ok {
return false, false
}
return true, c.Val().Kind() == constant.Int && c.Val().String() == "0"
}
2019-04-22 12:59:42 +02:00
fn := func(node ast.Node) {
2018-12-28 23:15:05 +01:00
// check that expr is "x || y" or "x && y"
2019-04-22 12:59:42 +02:00
expr := node.(*ast.BinaryExpr)
2018-12-28 23:15:05 +01:00
if expr.Op != token.LOR && expr.Op != token.LAND {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
eqNil := expr.Op == token.LOR
// check that x is "xx == nil" or "xx != nil"
x, ok := expr.X.(*ast.BinaryExpr)
if !ok {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
if eqNil && x.Op != token.EQL {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
if !eqNil && x.Op != token.NEQ {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
xx, ok := x.X.(*ast.Ident)
if !ok {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
if !IsNil(pass, x.Y) {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
// check that y is "len(xx) == 0" or "len(xx) ... "
y, ok := expr.Y.(*ast.BinaryExpr)
if !ok {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
if eqNil && y.Op != token.EQL { // must be len(xx) *==* 0
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
yx, ok := y.X.(*ast.CallExpr)
if !ok {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
yxFun, ok := yx.Fun.(*ast.Ident)
if !ok || yxFun.Name != "len" || len(yx.Args) != 1 {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
2019-02-18 20:32:41 +01:00
yxArg, ok := yx.Args[Arg("len.v")].(*ast.Ident)
2018-12-28 23:15:05 +01:00
if !ok {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
if yxArg.Name != xx.Name {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
if eqNil && !IsZero(y.Y) { // must be len(x) == *0*
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
if !eqNil {
isConst, isZero := isConstZero(y.Y)
if !isConst {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
switch y.Op {
case token.EQL:
// avoid false positive for "xx != nil && len(xx) == 0"
if isZero {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
case token.GEQ:
// avoid false positive for "xx != nil && len(xx) >= 0"
if isZero {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
case token.NEQ:
// avoid false positive for "xx != nil && len(xx) != <non-zero>"
if !isZero {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
case token.GTR:
// ok
default:
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
}
// finally check that xx type is one of array, slice, map or chan
// this is to prevent false positive in case if xx is a pointer to an array
var nilType string
switch pass.TypesInfo.TypeOf(xx).(type) {
2018-12-28 23:15:05 +01:00
case *types.Slice:
nilType = "nil slices"
case *types.Map:
nilType = "nil maps"
case *types.Chan:
nilType = "nil channels"
default:
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
ReportNodefFG(pass, expr, "should omit nil check; len() for %s is defined as zero", nilType)
2018-12-28 23:15:05 +01:00
}
pass.ResultOf[inspect.Analyzer].(*inspector.Inspector).Preorder([]ast.Node{(*ast.BinaryExpr)(nil)}, fn)
return nil, nil
2018-12-28 23:15:05 +01:00
}
func LintSlicing(pass *analysis.Pass) (interface{}, error) {
2019-04-22 12:59:42 +02:00
fn := func(node ast.Node) {
n := node.(*ast.SliceExpr)
2018-12-28 23:15:05 +01:00
if n.Max != nil {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
s, ok := n.X.(*ast.Ident)
if !ok || s.Obj == nil {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
call, ok := n.High.(*ast.CallExpr)
if !ok || len(call.Args) != 1 || call.Ellipsis.IsValid() {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
fun, ok := call.Fun.(*ast.Ident)
if !ok || fun.Name != "len" {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
if _, ok := pass.TypesInfo.ObjectOf(fun).(*types.Builtin); !ok {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
2019-02-18 20:32:41 +01:00
arg, ok := call.Args[Arg("len.v")].(*ast.Ident)
2018-12-28 23:15:05 +01:00
if !ok || arg.Obj != s.Obj {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
ReportNodefFG(pass, n, "should omit second index in slice, s[a:len(s)] is identical to s[a:]")
2018-12-28 23:15:05 +01:00
}
pass.ResultOf[inspect.Analyzer].(*inspector.Inspector).Preorder([]ast.Node{(*ast.SliceExpr)(nil)}, fn)
return nil, nil
2018-12-28 23:15:05 +01:00
}
func refersTo(pass *analysis.Pass, expr ast.Expr, ident *ast.Ident) bool {
2018-12-28 23:15:05 +01:00
found := false
fn := func(node ast.Node) bool {
ident2, ok := node.(*ast.Ident)
if !ok {
return true
}
if pass.TypesInfo.ObjectOf(ident) == pass.TypesInfo.ObjectOf(ident2) {
2018-12-28 23:15:05 +01:00
found = true
return false
}
return true
}
ast.Inspect(expr, fn)
return found
}
func LintLoopAppend(pass *analysis.Pass) (interface{}, error) {
2019-04-22 12:59:42 +02:00
fn := func(node ast.Node) {
loop := node.(*ast.RangeStmt)
2018-12-28 23:15:05 +01:00
if !IsBlank(loop.Key) {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
val, ok := loop.Value.(*ast.Ident)
if !ok {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
if len(loop.Body.List) != 1 {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
stmt, ok := loop.Body.List[0].(*ast.AssignStmt)
if !ok {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
if stmt.Tok != token.ASSIGN || len(stmt.Lhs) != 1 || len(stmt.Rhs) != 1 {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
if refersTo(pass, stmt.Lhs[0], val) {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
call, ok := stmt.Rhs[0].(*ast.CallExpr)
if !ok {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
if len(call.Args) != 2 || call.Ellipsis.IsValid() {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
fun, ok := call.Fun.(*ast.Ident)
if !ok {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
obj := pass.TypesInfo.ObjectOf(fun)
2018-12-28 23:15:05 +01:00
fn, ok := obj.(*types.Builtin)
if !ok || fn.Name() != "append" {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
src := pass.TypesInfo.TypeOf(loop.X)
dst := pass.TypesInfo.TypeOf(call.Args[Arg("append.slice")])
2018-12-28 23:15:05 +01:00
// TODO(dominikh) remove nil check once Go issue #15173 has
// been fixed
if src == nil {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
if !types.Identical(src, dst) {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
if Render(pass, stmt.Lhs[0]) != Render(pass, call.Args[Arg("append.slice")]) {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
2019-02-18 20:32:41 +01:00
el, ok := call.Args[Arg("append.elems")].(*ast.Ident)
2018-12-28 23:15:05 +01:00
if !ok {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
if pass.TypesInfo.ObjectOf(val) != pass.TypesInfo.ObjectOf(el) {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
ReportNodefFG(pass, loop, "should replace loop with %s = append(%s, %s...)",
Render(pass, stmt.Lhs[0]), Render(pass, call.Args[Arg("append.slice")]), Render(pass, loop.X))
2018-12-28 23:15:05 +01:00
}
pass.ResultOf[inspect.Analyzer].(*inspector.Inspector).Preorder([]ast.Node{(*ast.RangeStmt)(nil)}, fn)
return nil, nil
2018-12-28 23:15:05 +01:00
}
func LintTimeSince(pass *analysis.Pass) (interface{}, error) {
2019-04-22 12:59:42 +02:00
fn := func(node ast.Node) {
call := node.(*ast.CallExpr)
2018-12-28 23:15:05 +01:00
sel, ok := call.Fun.(*ast.SelectorExpr)
if !ok {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
if !IsCallToAST(pass, sel.X, "time.Now") {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
if sel.Sel.Name != "Sub" {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
ReportNodefFG(pass, call, "should use time.Since instead of time.Now().Sub")
2018-12-28 23:15:05 +01:00
}
pass.ResultOf[inspect.Analyzer].(*inspector.Inspector).Preorder([]ast.Node{(*ast.CallExpr)(nil)}, fn)
return nil, nil
2018-12-28 23:15:05 +01:00
}
func LintTimeUntil(pass *analysis.Pass) (interface{}, error) {
if !IsGoVersion(pass, 8) {
return nil, nil
2018-12-28 23:15:05 +01:00
}
2019-04-22 12:59:42 +02:00
fn := func(node ast.Node) {
call := node.(*ast.CallExpr)
if !IsCallToAST(pass, call, "(time.Time).Sub") {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
if !IsCallToAST(pass, call.Args[Arg("(time.Time).Sub.u")], "time.Now") {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
ReportNodefFG(pass, call, "should use time.Until instead of t.Sub(time.Now())")
2018-12-28 23:15:05 +01:00
}
pass.ResultOf[inspect.Analyzer].(*inspector.Inspector).Preorder([]ast.Node{(*ast.CallExpr)(nil)}, fn)
return nil, nil
2018-12-28 23:15:05 +01:00
}
func LintUnnecessaryBlank(pass *analysis.Pass) (interface{}, error) {
2018-12-28 23:15:05 +01:00
fn1 := func(node ast.Node) {
2019-04-22 12:59:42 +02:00
assign := node.(*ast.AssignStmt)
2018-12-28 23:15:05 +01:00
if len(assign.Lhs) != 2 || len(assign.Rhs) != 1 {
return
}
if !IsBlank(assign.Lhs[1]) {
return
}
switch rhs := assign.Rhs[0].(type) {
case *ast.IndexExpr:
// The type-checker should make sure that it's a map, but
// let's be safe.
if _, ok := pass.TypesInfo.TypeOf(rhs.X).Underlying().(*types.Map); !ok {
2018-12-28 23:15:05 +01:00
return
}
case *ast.UnaryExpr:
if rhs.Op != token.ARROW {
return
}
default:
return
}
cp := *assign
cp.Lhs = cp.Lhs[0:1]
ReportNodefFG(pass, assign, "should write %s instead of %s", Render(pass, &cp), Render(pass, assign))
2018-12-28 23:15:05 +01:00
}
fn2 := func(node ast.Node) {
2019-04-22 12:59:42 +02:00
stmt := node.(*ast.AssignStmt)
2018-12-28 23:15:05 +01:00
if len(stmt.Lhs) != len(stmt.Rhs) {
return
}
for i, lh := range stmt.Lhs {
rh := stmt.Rhs[i]
if !IsBlank(lh) {
continue
}
expr, ok := rh.(*ast.UnaryExpr)
if !ok {
continue
}
if expr.Op != token.ARROW {
continue
}
ReportNodefFG(pass, lh, "'_ = <-ch' can be simplified to '<-ch'")
2018-12-28 23:15:05 +01:00
}
}
fn3 := func(node ast.Node) {
2019-04-22 12:59:42 +02:00
rs := node.(*ast.RangeStmt)
2018-12-28 23:15:05 +01:00
// for x, _
if !IsBlank(rs.Key) && IsBlank(rs.Value) {
ReportNodefFG(pass, rs.Value, "should omit value from range; this loop is equivalent to `for %s %s range ...`", Render(pass, rs.Key), rs.Tok)
2018-12-28 23:15:05 +01:00
}
// for _, _ || for _
if IsBlank(rs.Key) && (IsBlank(rs.Value) || rs.Value == nil) {
ReportNodefFG(pass, rs.Key, "should omit values from range; this loop is equivalent to `for range ...`")
2018-12-28 23:15:05 +01:00
}
}
pass.ResultOf[inspect.Analyzer].(*inspector.Inspector).Preorder([]ast.Node{(*ast.AssignStmt)(nil)}, fn1)
pass.ResultOf[inspect.Analyzer].(*inspector.Inspector).Preorder([]ast.Node{(*ast.AssignStmt)(nil)}, fn2)
if IsGoVersion(pass, 4) {
pass.ResultOf[inspect.Analyzer].(*inspector.Inspector).Preorder([]ast.Node{(*ast.RangeStmt)(nil)}, fn3)
2018-12-28 23:15:05 +01:00
}
return nil, nil
2018-12-28 23:15:05 +01:00
}
func LintSimplerStructConversion(pass *analysis.Pass) (interface{}, error) {
2018-12-28 23:15:05 +01:00
var skip ast.Node
2019-04-22 12:59:42 +02:00
fn := func(node ast.Node) {
2018-12-28 23:15:05 +01:00
// Do not suggest type conversion between pointers
if unary, ok := node.(*ast.UnaryExpr); ok && unary.Op == token.AND {
if lit, ok := unary.X.(*ast.CompositeLit); ok {
skip = lit
}
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
if node == skip {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
lit, ok := node.(*ast.CompositeLit)
if !ok {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
typ1, _ := pass.TypesInfo.TypeOf(lit.Type).(*types.Named)
2018-12-28 23:15:05 +01:00
if typ1 == nil {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
s1, ok := typ1.Underlying().(*types.Struct)
if !ok {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
var typ2 *types.Named
var ident *ast.Ident
getSelType := func(expr ast.Expr) (types.Type, *ast.Ident, bool) {
sel, ok := expr.(*ast.SelectorExpr)
if !ok {
return nil, nil, false
}
ident, ok := sel.X.(*ast.Ident)
if !ok {
return nil, nil, false
}
typ := pass.TypesInfo.TypeOf(sel.X)
2018-12-28 23:15:05 +01:00
return typ, ident, typ != nil
}
if len(lit.Elts) == 0 {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
if s1.NumFields() != len(lit.Elts) {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
for i, elt := range lit.Elts {
var t types.Type
var id *ast.Ident
var ok bool
switch elt := elt.(type) {
case *ast.SelectorExpr:
t, id, ok = getSelType(elt)
if !ok {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
if i >= s1.NumFields() || s1.Field(i).Name() != elt.Sel.Name {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
case *ast.KeyValueExpr:
var sel *ast.SelectorExpr
sel, ok = elt.Value.(*ast.SelectorExpr)
if !ok {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
if elt.Key.(*ast.Ident).Name != sel.Sel.Name {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
t, id, ok = getSelType(elt.Value)
}
if !ok {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
// All fields must be initialized from the same object
if ident != nil && ident.Obj != id.Obj {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
typ2, _ = t.(*types.Named)
if typ2 == nil {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
ident = id
}
if typ2 == nil {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
if typ1.Obj().Pkg() != typ2.Obj().Pkg() {
// Do not suggest type conversions between different
// packages. Types in different packages might only match
// by coincidence. Furthermore, if the dependency ever
// adds more fields to its type, it could break the code
// that relies on the type conversion to work.
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
s2, ok := typ2.Underlying().(*types.Struct)
if !ok {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
if typ1 == typ2 {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
if IsGoVersion(pass, 8) {
2019-02-18 20:32:41 +01:00
if !types.IdenticalIgnoreTags(s1, s2) {
2019-04-22 12:59:42 +02:00
return
2019-02-18 20:32:41 +01:00
}
} else {
if !types.Identical(s1, s2) {
2019-04-22 12:59:42 +02:00
return
2019-02-18 20:32:41 +01:00
}
2018-12-28 23:15:05 +01:00
}
ReportNodefFG(pass, node, "should convert %s (type %s) to %s instead of using struct literal",
2018-12-28 23:15:05 +01:00
ident.Name, typ2.Obj().Name(), typ1.Obj().Name())
}
pass.ResultOf[inspect.Analyzer].(*inspector.Inspector).Preorder([]ast.Node{(*ast.UnaryExpr)(nil), (*ast.CompositeLit)(nil)}, fn)
return nil, nil
2018-12-28 23:15:05 +01:00
}
func LintTrim(pass *analysis.Pass) (interface{}, error) {
2018-12-28 23:15:05 +01:00
sameNonDynamic := func(node1, node2 ast.Node) bool {
if reflect.TypeOf(node1) != reflect.TypeOf(node2) {
return false
}
switch node1 := node1.(type) {
case *ast.Ident:
return node1.Obj == node2.(*ast.Ident).Obj
case *ast.SelectorExpr:
return Render(pass, node1) == Render(pass, node2)
2018-12-28 23:15:05 +01:00
case *ast.IndexExpr:
return Render(pass, node1) == Render(pass, node2)
2018-12-28 23:15:05 +01:00
}
return false
}
isLenOnIdent := func(fn ast.Expr, ident ast.Expr) bool {
call, ok := fn.(*ast.CallExpr)
if !ok {
return false
}
if fn, ok := call.Fun.(*ast.Ident); !ok || fn.Name != "len" {
return false
}
if len(call.Args) != 1 {
return false
}
2019-02-18 20:32:41 +01:00
return sameNonDynamic(call.Args[Arg("len.v")], ident)
2018-12-28 23:15:05 +01:00
}
2019-04-22 12:59:42 +02:00
fn := func(node ast.Node) {
2018-12-28 23:15:05 +01:00
var pkg string
var fun string
2019-04-22 12:59:42 +02:00
ifstmt := node.(*ast.IfStmt)
2018-12-28 23:15:05 +01:00
if ifstmt.Init != nil {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
if ifstmt.Else != nil {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
if len(ifstmt.Body.List) != 1 {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
condCall, ok := ifstmt.Cond.(*ast.CallExpr)
if !ok {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
2019-02-18 20:32:41 +01:00
switch {
case IsCallToAST(pass, condCall, "strings.HasPrefix"):
2019-02-18 20:32:41 +01:00
pkg = "strings"
fun = "HasPrefix"
case IsCallToAST(pass, condCall, "strings.HasSuffix"):
2018-12-28 23:15:05 +01:00
pkg = "strings"
2019-02-18 20:32:41 +01:00
fun = "HasSuffix"
case IsCallToAST(pass, condCall, "strings.Contains"):
2019-02-18 20:32:41 +01:00
pkg = "strings"
fun = "Contains"
case IsCallToAST(pass, condCall, "bytes.HasPrefix"):
2018-12-28 23:15:05 +01:00
pkg = "bytes"
fun = "HasPrefix"
case IsCallToAST(pass, condCall, "bytes.HasSuffix"):
2019-02-18 20:32:41 +01:00
pkg = "bytes"
2018-12-28 23:15:05 +01:00
fun = "HasSuffix"
case IsCallToAST(pass, condCall, "bytes.Contains"):
2019-02-18 20:32:41 +01:00
pkg = "bytes"
fun = "Contains"
default:
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
assign, ok := ifstmt.Body.List[0].(*ast.AssignStmt)
if !ok {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
if assign.Tok != token.ASSIGN {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
if len(assign.Lhs) != 1 || len(assign.Rhs) != 1 {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
if !sameNonDynamic(condCall.Args[0], assign.Lhs[0]) {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
2019-02-18 20:32:41 +01:00
switch rhs := assign.Rhs[0].(type) {
case *ast.CallExpr:
if len(rhs.Args) < 2 || !sameNonDynamic(condCall.Args[0], rhs.Args[0]) || !sameNonDynamic(condCall.Args[1], rhs.Args[1]) {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
if IsCallToAST(pass, condCall, "strings.HasPrefix") && IsCallToAST(pass, rhs, "strings.TrimPrefix") ||
IsCallToAST(pass, condCall, "strings.HasSuffix") && IsCallToAST(pass, rhs, "strings.TrimSuffix") ||
IsCallToAST(pass, condCall, "strings.Contains") && IsCallToAST(pass, rhs, "strings.Replace") ||
IsCallToAST(pass, condCall, "bytes.HasPrefix") && IsCallToAST(pass, rhs, "bytes.TrimPrefix") ||
IsCallToAST(pass, condCall, "bytes.HasSuffix") && IsCallToAST(pass, rhs, "bytes.TrimSuffix") ||
IsCallToAST(pass, condCall, "bytes.Contains") && IsCallToAST(pass, rhs, "bytes.Replace") {
ReportNodefFG(pass, ifstmt, "should replace this if statement with an unconditional %s", CallNameAST(pass, rhs))
2018-12-28 23:15:05 +01:00
}
2019-04-22 12:59:42 +02:00
return
2019-02-18 20:32:41 +01:00
case *ast.SliceExpr:
slice := rhs
if !ok {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
2019-02-18 20:32:41 +01:00
if slice.Slice3 {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
2019-02-18 20:32:41 +01:00
if !sameNonDynamic(slice.X, condCall.Args[0]) {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
2019-02-18 20:32:41 +01:00
var index ast.Expr
switch fun {
case "HasPrefix":
// TODO(dh) We could detect a High that is len(s), but another
// rule will already flag that, anyway.
if slice.High != nil {
2019-04-22 12:59:42 +02:00
return
2019-02-18 20:32:41 +01:00
}
index = slice.Low
case "HasSuffix":
if slice.Low != nil {
n, ok := ExprToInt(pass, slice.Low)
2019-02-18 20:32:41 +01:00
if !ok || n != 0 {
2019-04-22 12:59:42 +02:00
return
2019-02-18 20:32:41 +01:00
}
}
index = slice.High
}
switch index := index.(type) {
case *ast.CallExpr:
if fun != "HasPrefix" {
2019-04-22 12:59:42 +02:00
return
2019-02-18 20:32:41 +01:00
}
if fn, ok := index.Fun.(*ast.Ident); !ok || fn.Name != "len" {
2019-04-22 12:59:42 +02:00
return
2019-02-18 20:32:41 +01:00
}
if len(index.Args) != 1 {
2019-04-22 12:59:42 +02:00
return
2019-02-18 20:32:41 +01:00
}
id3 := index.Args[Arg("len.v")]
switch oid3 := condCall.Args[1].(type) {
case *ast.BasicLit:
if pkg != "strings" {
2019-04-22 12:59:42 +02:00
return
2019-02-18 20:32:41 +01:00
}
lit, ok := id3.(*ast.BasicLit)
if !ok {
2019-04-22 12:59:42 +02:00
return
2019-02-18 20:32:41 +01:00
}
s1, ok1 := ExprToString(pass, lit)
s2, ok2 := ExprToString(pass, condCall.Args[1])
2019-02-18 20:32:41 +01:00
if !ok1 || !ok2 || s1 != s2 {
2019-04-22 12:59:42 +02:00
return
2019-02-18 20:32:41 +01:00
}
default:
if !sameNonDynamic(id3, oid3) {
2019-04-22 12:59:42 +02:00
return
2019-02-18 20:32:41 +01:00
}
}
case *ast.BasicLit, *ast.Ident:
if fun != "HasPrefix" {
2019-04-22 12:59:42 +02:00
return
2019-02-18 20:32:41 +01:00
}
2018-12-28 23:15:05 +01:00
if pkg != "strings" {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
string, ok1 := ExprToString(pass, condCall.Args[1])
int, ok2 := ExprToInt(pass, slice.Low)
2019-02-18 20:32:41 +01:00
if !ok1 || !ok2 || int != int64(len(string)) {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
2019-02-18 20:32:41 +01:00
case *ast.BinaryExpr:
if fun != "HasSuffix" {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
2019-02-18 20:32:41 +01:00
if index.Op != token.SUB {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
2019-02-18 20:32:41 +01:00
if !isLenOnIdent(index.X, condCall.Args[0]) ||
!isLenOnIdent(index.Y, condCall.Args[1]) {
2019-04-22 12:59:42 +02:00
return
2019-02-18 20:32:41 +01:00
}
default:
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
2019-02-18 20:32:41 +01:00
var replacement string
switch fun {
case "HasPrefix":
replacement = "TrimPrefix"
case "HasSuffix":
replacement = "TrimSuffix"
2018-12-28 23:15:05 +01:00
}
ReportNodefFG(pass, ifstmt, "should replace this if statement with an unconditional %s.%s", pkg, replacement)
2018-12-28 23:15:05 +01:00
}
}
pass.ResultOf[inspect.Analyzer].(*inspector.Inspector).Preorder([]ast.Node{(*ast.IfStmt)(nil)}, fn)
return nil, nil
2018-12-28 23:15:05 +01:00
}
func LintLoopSlide(pass *analysis.Pass) (interface{}, error) {
2018-12-28 23:15:05 +01:00
// TODO(dh): detect bs[i+offset] in addition to bs[offset+i]
// TODO(dh): consider merging this function with LintLoopCopy
// TODO(dh): detect length that is an expression, not a variable name
// TODO(dh): support sliding to a different offset than the beginning of the slice
2019-04-22 12:59:42 +02:00
fn := func(node ast.Node) {
2018-12-28 23:15:05 +01:00
/*
for i := 0; i < n; i++ {
bs[i] = bs[offset+i]
}
copy(bs[:n], bs[offset:offset+n])
*/
2019-04-22 12:59:42 +02:00
loop := node.(*ast.ForStmt)
if len(loop.Body.List) != 1 || loop.Init == nil || loop.Cond == nil || loop.Post == nil {
return
2018-12-28 23:15:05 +01:00
}
assign, ok := loop.Init.(*ast.AssignStmt)
if !ok || len(assign.Lhs) != 1 || len(assign.Rhs) != 1 || !IsZero(assign.Rhs[0]) {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
initvar, ok := assign.Lhs[0].(*ast.Ident)
if !ok {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
post, ok := loop.Post.(*ast.IncDecStmt)
if !ok || post.Tok != token.INC {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
postvar, ok := post.X.(*ast.Ident)
if !ok || pass.TypesInfo.ObjectOf(postvar) != pass.TypesInfo.ObjectOf(initvar) {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
bin, ok := loop.Cond.(*ast.BinaryExpr)
if !ok || bin.Op != token.LSS {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
binx, ok := bin.X.(*ast.Ident)
if !ok || pass.TypesInfo.ObjectOf(binx) != pass.TypesInfo.ObjectOf(initvar) {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
biny, ok := bin.Y.(*ast.Ident)
if !ok {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
assign, ok = loop.Body.List[0].(*ast.AssignStmt)
if !ok || len(assign.Lhs) != 1 || len(assign.Rhs) != 1 || assign.Tok != token.ASSIGN {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
lhs, ok := assign.Lhs[0].(*ast.IndexExpr)
if !ok {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
rhs, ok := assign.Rhs[0].(*ast.IndexExpr)
if !ok {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
bs1, ok := lhs.X.(*ast.Ident)
if !ok {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
bs2, ok := rhs.X.(*ast.Ident)
if !ok {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
obj1 := pass.TypesInfo.ObjectOf(bs1)
obj2 := pass.TypesInfo.ObjectOf(bs2)
2018-12-28 23:15:05 +01:00
if obj1 != obj2 {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
if _, ok := obj1.Type().Underlying().(*types.Slice); !ok {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
index1, ok := lhs.Index.(*ast.Ident)
if !ok || pass.TypesInfo.ObjectOf(index1) != pass.TypesInfo.ObjectOf(initvar) {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
index2, ok := rhs.Index.(*ast.BinaryExpr)
if !ok || index2.Op != token.ADD {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
add1, ok := index2.X.(*ast.Ident)
if !ok {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
add2, ok := index2.Y.(*ast.Ident)
if !ok || pass.TypesInfo.ObjectOf(add2) != pass.TypesInfo.ObjectOf(initvar) {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
ReportNodefFG(pass, loop, "should use copy(%s[:%s], %s[%s:]) instead", Render(pass, bs1), Render(pass, biny), Render(pass, bs1), Render(pass, add1))
2018-12-28 23:15:05 +01:00
}
pass.ResultOf[inspect.Analyzer].(*inspector.Inspector).Preorder([]ast.Node{(*ast.ForStmt)(nil)}, fn)
return nil, nil
2018-12-28 23:15:05 +01:00
}
func LintMakeLenCap(pass *analysis.Pass) (interface{}, error) {
2019-04-22 12:59:42 +02:00
fn := func(node ast.Node) {
call := node.(*ast.CallExpr)
2018-12-28 23:15:05 +01:00
if fn, ok := call.Fun.(*ast.Ident); !ok || fn.Name != "make" {
// FIXME check whether make is indeed the built-in function
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
switch len(call.Args) {
case 2:
// make(T, len)
if _, ok := pass.TypesInfo.TypeOf(call.Args[Arg("make.t")]).Underlying().(*types.Slice); ok {
2018-12-28 23:15:05 +01:00
break
}
2019-02-18 20:32:41 +01:00
if IsZero(call.Args[Arg("make.size[0]")]) {
ReportNodefFG(pass, call.Args[Arg("make.size[0]")], "should use make(%s) instead", Render(pass, call.Args[Arg("make.t")]))
2018-12-28 23:15:05 +01:00
}
case 3:
// make(T, len, cap)
if Render(pass, call.Args[Arg("make.size[0]")]) == Render(pass, call.Args[Arg("make.size[1]")]) {
ReportNodefFG(pass, call.Args[Arg("make.size[0]")],
2019-02-18 20:32:41 +01:00
"should use make(%s, %s) instead",
Render(pass, call.Args[Arg("make.t")]), Render(pass, call.Args[Arg("make.size[0]")]))
2018-12-28 23:15:05 +01:00
}
}
}
pass.ResultOf[inspect.Analyzer].(*inspector.Inspector).Preorder([]ast.Node{(*ast.CallExpr)(nil)}, fn)
return nil, nil
2018-12-28 23:15:05 +01:00
}
func LintAssertNotNil(pass *analysis.Pass) (interface{}, error) {
2018-12-28 23:15:05 +01:00
isNilCheck := func(ident *ast.Ident, expr ast.Expr) bool {
xbinop, ok := expr.(*ast.BinaryExpr)
if !ok || xbinop.Op != token.NEQ {
return false
}
xident, ok := xbinop.X.(*ast.Ident)
if !ok || xident.Obj != ident.Obj {
return false
}
if !IsNil(pass, xbinop.Y) {
2018-12-28 23:15:05 +01:00
return false
}
return true
}
isOKCheck := func(ident *ast.Ident, expr ast.Expr) bool {
yident, ok := expr.(*ast.Ident)
if !ok || yident.Obj != ident.Obj {
return false
}
return true
}
2019-04-22 12:59:42 +02:00
fn1 := func(node ast.Node) {
ifstmt := node.(*ast.IfStmt)
2018-12-28 23:15:05 +01:00
assign, ok := ifstmt.Init.(*ast.AssignStmt)
if !ok || len(assign.Lhs) != 2 || len(assign.Rhs) != 1 || !IsBlank(assign.Lhs[0]) {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
assert, ok := assign.Rhs[0].(*ast.TypeAssertExpr)
if !ok {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
binop, ok := ifstmt.Cond.(*ast.BinaryExpr)
if !ok || binop.Op != token.LAND {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
assertIdent, ok := assert.X.(*ast.Ident)
if !ok {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
assignIdent, ok := assign.Lhs[1].(*ast.Ident)
if !ok {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
if !(isNilCheck(assertIdent, binop.X) && isOKCheck(assignIdent, binop.Y)) &&
!(isNilCheck(assertIdent, binop.Y) && isOKCheck(assignIdent, binop.X)) {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
ReportNodefFG(pass, ifstmt, "when %s is true, %s can't be nil", Render(pass, assignIdent), Render(pass, assertIdent))
2018-12-28 23:15:05 +01:00
}
2019-04-22 12:59:42 +02:00
fn2 := func(node ast.Node) {
2019-02-18 20:32:41 +01:00
// Check that outer ifstmt is an 'if x != nil {}'
2019-04-22 12:59:42 +02:00
ifstmt := node.(*ast.IfStmt)
2019-02-18 20:32:41 +01:00
if ifstmt.Init != nil {
2019-04-22 12:59:42 +02:00
return
2019-02-18 20:32:41 +01:00
}
if ifstmt.Else != nil {
2019-04-22 12:59:42 +02:00
return
2019-02-18 20:32:41 +01:00
}
if len(ifstmt.Body.List) != 1 {
2019-04-22 12:59:42 +02:00
return
2019-02-18 20:32:41 +01:00
}
binop, ok := ifstmt.Cond.(*ast.BinaryExpr)
if !ok {
2019-04-22 12:59:42 +02:00
return
2019-02-18 20:32:41 +01:00
}
if binop.Op != token.NEQ {
2019-04-22 12:59:42 +02:00
return
2019-02-18 20:32:41 +01:00
}
lhs, ok := binop.X.(*ast.Ident)
if !ok {
2019-04-22 12:59:42 +02:00
return
2019-02-18 20:32:41 +01:00
}
if !IsNil(pass, binop.Y) {
2019-04-22 12:59:42 +02:00
return
2019-02-18 20:32:41 +01:00
}
// Check that inner ifstmt is an `if _, ok := x.(T); ok {}`
ifstmt, ok = ifstmt.Body.List[0].(*ast.IfStmt)
if !ok {
2019-04-22 12:59:42 +02:00
return
2019-02-18 20:32:41 +01:00
}
assign, ok := ifstmt.Init.(*ast.AssignStmt)
if !ok || len(assign.Lhs) != 2 || len(assign.Rhs) != 1 || !IsBlank(assign.Lhs[0]) {
2019-04-22 12:59:42 +02:00
return
2019-02-18 20:32:41 +01:00
}
assert, ok := assign.Rhs[0].(*ast.TypeAssertExpr)
if !ok {
2019-04-22 12:59:42 +02:00
return
2019-02-18 20:32:41 +01:00
}
assertIdent, ok := assert.X.(*ast.Ident)
if !ok {
2019-04-22 12:59:42 +02:00
return
2019-02-18 20:32:41 +01:00
}
if lhs.Obj != assertIdent.Obj {
2019-04-22 12:59:42 +02:00
return
2019-02-18 20:32:41 +01:00
}
assignIdent, ok := assign.Lhs[1].(*ast.Ident)
if !ok {
2019-04-22 12:59:42 +02:00
return
2019-02-18 20:32:41 +01:00
}
if !isOKCheck(assignIdent, ifstmt.Cond) {
2019-04-22 12:59:42 +02:00
return
2019-02-18 20:32:41 +01:00
}
ReportNodefFG(pass, ifstmt, "when %s is true, %s can't be nil", Render(pass, assignIdent), Render(pass, assertIdent))
2018-12-28 23:15:05 +01:00
}
pass.ResultOf[inspect.Analyzer].(*inspector.Inspector).Preorder([]ast.Node{(*ast.IfStmt)(nil)}, fn1)
pass.ResultOf[inspect.Analyzer].(*inspector.Inspector).Preorder([]ast.Node{(*ast.IfStmt)(nil)}, fn2)
return nil, nil
2018-12-28 23:15:05 +01:00
}
func LintDeclareAssign(pass *analysis.Pass) (interface{}, error) {
2019-04-22 12:59:42 +02:00
hasMultipleAssignments := func(root ast.Node, ident *ast.Ident) bool {
num := 0
ast.Inspect(root, func(node ast.Node) bool {
if num >= 2 {
return false
}
assign, ok := node.(*ast.AssignStmt)
if !ok {
return true
}
for _, lhs := range assign.Lhs {
if oident, ok := lhs.(*ast.Ident); ok {
if oident.Obj == ident.Obj {
num++
}
}
}
2018-12-28 23:15:05 +01:00
return true
2019-04-22 12:59:42 +02:00
})
return num >= 2
}
fn := func(node ast.Node) {
block := node.(*ast.BlockStmt)
2018-12-28 23:15:05 +01:00
if len(block.List) < 2 {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
for i, stmt := range block.List[:len(block.List)-1] {
_ = i
decl, ok := stmt.(*ast.DeclStmt)
if !ok {
continue
}
gdecl, ok := decl.Decl.(*ast.GenDecl)
if !ok || gdecl.Tok != token.VAR || len(gdecl.Specs) != 1 {
continue
}
vspec, ok := gdecl.Specs[0].(*ast.ValueSpec)
if !ok || len(vspec.Names) != 1 || len(vspec.Values) != 0 {
continue
}
assign, ok := block.List[i+1].(*ast.AssignStmt)
if !ok || assign.Tok != token.ASSIGN {
continue
}
if len(assign.Lhs) != 1 || len(assign.Rhs) != 1 {
continue
}
ident, ok := assign.Lhs[0].(*ast.Ident)
if !ok {
continue
}
if vspec.Names[0].Obj != ident.Obj {
continue
}
if refersTo(pass, assign.Rhs[0], ident) {
2018-12-28 23:15:05 +01:00
continue
}
2019-04-22 12:59:42 +02:00
if hasMultipleAssignments(block, ident) {
continue
}
ReportNodefFG(pass, decl, "should merge variable declaration with assignment on next line")
2018-12-28 23:15:05 +01:00
}
}
pass.ResultOf[inspect.Analyzer].(*inspector.Inspector).Preorder([]ast.Node{(*ast.BlockStmt)(nil)}, fn)
return nil, nil
2018-12-28 23:15:05 +01:00
}
func LintRedundantBreak(pass *analysis.Pass) (interface{}, error) {
2018-12-28 23:15:05 +01:00
fn1 := func(node ast.Node) {
2019-04-22 12:59:42 +02:00
clause := node.(*ast.CaseClause)
2018-12-28 23:15:05 +01:00
if len(clause.Body) < 2 {
return
}
branch, ok := clause.Body[len(clause.Body)-1].(*ast.BranchStmt)
if !ok || branch.Tok != token.BREAK || branch.Label != nil {
return
}
ReportNodefFG(pass, branch, "redundant break statement")
2018-12-28 23:15:05 +01:00
}
fn2 := func(node ast.Node) {
var ret *ast.FieldList
var body *ast.BlockStmt
switch x := node.(type) {
case *ast.FuncDecl:
ret = x.Type.Results
body = x.Body
case *ast.FuncLit:
ret = x.Type.Results
body = x.Body
default:
2019-04-22 12:59:42 +02:00
panic(fmt.Sprintf("unreachable: %T", node))
2018-12-28 23:15:05 +01:00
}
// if the func has results, a return can't be redundant.
// similarly, if there are no statements, there can be
// no return.
if ret != nil || body == nil || len(body.List) < 1 {
return
}
rst, ok := body.List[len(body.List)-1].(*ast.ReturnStmt)
if !ok {
return
}
// we don't need to check rst.Results as we already
// checked x.Type.Results to be nil.
ReportNodefFG(pass, rst, "redundant return statement")
2018-12-28 23:15:05 +01:00
}
pass.ResultOf[inspect.Analyzer].(*inspector.Inspector).Preorder([]ast.Node{(*ast.CaseClause)(nil)}, fn1)
pass.ResultOf[inspect.Analyzer].(*inspector.Inspector).Preorder([]ast.Node{(*ast.FuncDecl)(nil), (*ast.FuncLit)(nil)}, fn2)
return nil, nil
2018-12-28 23:15:05 +01:00
}
func isStringer(T types.Type, msCache *typeutil.MethodSetCache) bool {
ms := msCache.MethodSet(T)
2019-04-22 12:59:42 +02:00
sel := ms.Lookup(nil, "String")
if sel == nil {
2018-12-28 23:15:05 +01:00
return false
}
2019-04-22 12:59:42 +02:00
fn, ok := sel.Obj().(*types.Func)
2018-12-28 23:15:05 +01:00
if !ok {
2019-04-22 12:59:42 +02:00
// should be unreachable
return false
}
sig := fn.Type().(*types.Signature)
if sig.Params().Len() != 0 {
2018-12-28 23:15:05 +01:00
return false
}
2019-04-22 12:59:42 +02:00
if sig.Results().Len() != 1 {
return false
}
if !IsType(sig.Results().At(0).Type(), "string") {
return false
}
return true
2018-12-28 23:15:05 +01:00
}
func LintRedundantSprintf(pass *analysis.Pass) (interface{}, error) {
2019-04-22 12:59:42 +02:00
fn := func(node ast.Node) {
call := node.(*ast.CallExpr)
if !IsCallToAST(pass, call, "fmt.Sprintf") {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
if len(call.Args) != 2 {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
if s, ok := ExprToString(pass, call.Args[Arg("fmt.Sprintf.format")]); !ok || s != "%s" {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
2019-02-18 20:32:41 +01:00
arg := call.Args[Arg("fmt.Sprintf.a[0]")]
typ := pass.TypesInfo.TypeOf(arg)
2018-12-28 23:15:05 +01:00
ssapkg := pass.ResultOf[buildssa.Analyzer].(*buildssa.SSA).Pkg
if isStringer(typ, &ssapkg.Prog.MethodSets) {
ReportNodef(pass, call, "should use String() instead of fmt.Sprintf")
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
if typ.Underlying() == types.Universe.Lookup("string").Type() {
if typ == types.Universe.Lookup("string").Type() {
ReportNodefFG(pass, call, "the argument is already a string, there's no need to use fmt.Sprintf")
2018-12-28 23:15:05 +01:00
} else {
ReportNodefFG(pass, call, "the argument's underlying type is a string, should use a simple conversion instead of fmt.Sprintf")
2018-12-28 23:15:05 +01:00
}
}
}
pass.ResultOf[inspect.Analyzer].(*inspector.Inspector).Preorder([]ast.Node{(*ast.CallExpr)(nil)}, fn)
return nil, nil
2018-12-28 23:15:05 +01:00
}
func LintErrorsNewSprintf(pass *analysis.Pass) (interface{}, error) {
2019-04-22 12:59:42 +02:00
fn := func(node ast.Node) {
if !IsCallToAST(pass, node, "errors.New") {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
call := node.(*ast.CallExpr)
if !IsCallToAST(pass, call.Args[Arg("errors.New.text")], "fmt.Sprintf") {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
ReportNodefFG(pass, node, "should use fmt.Errorf(...) instead of errors.New(fmt.Sprintf(...))")
2018-12-28 23:15:05 +01:00
}
pass.ResultOf[inspect.Analyzer].(*inspector.Inspector).Preorder([]ast.Node{(*ast.CallExpr)(nil)}, fn)
return nil, nil
2018-12-28 23:15:05 +01:00
}
func LintRangeStringRunes(pass *analysis.Pass) (interface{}, error) {
return sharedcheck.CheckRangeStringRunes(pass)
2018-12-28 23:15:05 +01:00
}
func LintNilCheckAroundRange(pass *analysis.Pass) (interface{}, error) {
2019-04-22 12:59:42 +02:00
fn := func(node ast.Node) {
ifstmt := node.(*ast.IfStmt)
2018-12-28 23:15:05 +01:00
cond, ok := ifstmt.Cond.(*ast.BinaryExpr)
if !ok {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
if cond.Op != token.NEQ || !IsNil(pass, cond.Y) || len(ifstmt.Body.List) != 1 {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
loop, ok := ifstmt.Body.List[0].(*ast.RangeStmt)
if !ok {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
ifXIdent, ok := cond.X.(*ast.Ident)
if !ok {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
rangeXIdent, ok := loop.X.(*ast.Ident)
if !ok {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
if ifXIdent.Obj != rangeXIdent.Obj {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
switch pass.TypesInfo.TypeOf(rangeXIdent).(type) {
2018-12-28 23:15:05 +01:00
case *types.Slice, *types.Map:
ReportNodefFG(pass, node, "unnecessary nil check around range")
2018-12-28 23:15:05 +01:00
}
}
pass.ResultOf[inspect.Analyzer].(*inspector.Inspector).Preorder([]ast.Node{(*ast.IfStmt)(nil)}, fn)
return nil, nil
2018-12-28 23:15:05 +01:00
}
func isPermissibleSort(pass *analysis.Pass, node ast.Node) bool {
2018-12-28 23:15:05 +01:00
call := node.(*ast.CallExpr)
typeconv, ok := call.Args[0].(*ast.CallExpr)
if !ok {
return true
}
sel, ok := typeconv.Fun.(*ast.SelectorExpr)
if !ok {
return true
}
name := SelectorName(pass, sel)
2018-12-28 23:15:05 +01:00
switch name {
case "sort.IntSlice", "sort.Float64Slice", "sort.StringSlice":
default:
return true
}
return false
}
func LintSortHelpers(pass *analysis.Pass) (interface{}, error) {
type Error struct {
node ast.Node
msg string
}
var allErrors []Error
2019-04-22 12:59:42 +02:00
fn := func(node ast.Node) {
2018-12-28 23:15:05 +01:00
var body *ast.BlockStmt
switch node := node.(type) {
case *ast.FuncLit:
body = node.Body
case *ast.FuncDecl:
body = node.Body
default:
2019-04-22 12:59:42 +02:00
panic(fmt.Sprintf("unreachable: %T", node))
2018-12-28 23:15:05 +01:00
}
if body == nil {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
var errors []Error
permissible := false
fnSorts := func(node ast.Node) bool {
if permissible {
return false
}
if !IsCallToAST(pass, node, "sort.Sort") {
2018-12-28 23:15:05 +01:00
return true
}
if isPermissibleSort(pass, node) {
2018-12-28 23:15:05 +01:00
permissible = true
return false
}
call := node.(*ast.CallExpr)
2019-02-18 20:32:41 +01:00
typeconv := call.Args[Arg("sort.Sort.data")].(*ast.CallExpr)
2018-12-28 23:15:05 +01:00
sel := typeconv.Fun.(*ast.SelectorExpr)
name := SelectorName(pass, sel)
2018-12-28 23:15:05 +01:00
switch name {
case "sort.IntSlice":
errors = append(errors, Error{node, "should use sort.Ints(...) instead of sort.Sort(sort.IntSlice(...))"})
case "sort.Float64Slice":
errors = append(errors, Error{node, "should use sort.Float64s(...) instead of sort.Sort(sort.Float64Slice(...))"})
case "sort.StringSlice":
errors = append(errors, Error{node, "should use sort.Strings(...) instead of sort.Sort(sort.StringSlice(...))"})
}
return true
}
ast.Inspect(body, fnSorts)
if permissible {
2019-04-22 12:59:42 +02:00
return
2018-12-28 23:15:05 +01:00
}
allErrors = append(allErrors, errors...)
}
pass.ResultOf[inspect.Analyzer].(*inspector.Inspector).Preorder([]ast.Node{(*ast.FuncLit)(nil), (*ast.FuncDecl)(nil)}, fn)
sort.Slice(allErrors, func(i, j int) bool {
return allErrors[i].node.Pos() < allErrors[j].node.Pos()
})
var prev token.Pos
for _, err := range allErrors {
if err.node.Pos() == prev {
continue
}
prev = err.node.Pos()
ReportNodefFG(pass, err.node, "%s", err.msg)
2018-12-28 23:15:05 +01:00
}
return nil, nil
2018-12-28 23:15:05 +01:00
}
2019-02-18 20:32:41 +01:00
func LintGuardedDelete(pass *analysis.Pass) (interface{}, error) {
2019-02-18 20:32:41 +01:00
isCommaOkMapIndex := func(stmt ast.Stmt) (b *ast.Ident, m ast.Expr, key ast.Expr, ok bool) {
// Has to be of the form `_, <b:*ast.Ident> = <m:*types.Map>[<key>]
assign, ok := stmt.(*ast.AssignStmt)
if !ok {
return nil, nil, nil, false
}
if len(assign.Lhs) != 2 || len(assign.Rhs) != 1 {
return nil, nil, nil, false
}
if !IsBlank(assign.Lhs[0]) {
return nil, nil, nil, false
}
ident, ok := assign.Lhs[1].(*ast.Ident)
if !ok {
return nil, nil, nil, false
}
index, ok := assign.Rhs[0].(*ast.IndexExpr)
if !ok {
return nil, nil, nil, false
}
if _, ok := pass.TypesInfo.TypeOf(index.X).(*types.Map); !ok {
2019-02-18 20:32:41 +01:00
return nil, nil, nil, false
}
key = index.Index
return ident, index.X, key, true
}
2019-04-22 12:59:42 +02:00
fn := func(node ast.Node) {
stmt := node.(*ast.IfStmt)
2019-02-18 20:32:41 +01:00
if len(stmt.Body.List) != 1 {
2019-04-22 12:59:42 +02:00
return
2019-02-18 20:32:41 +01:00
}
if stmt.Else != nil {
2019-04-22 12:59:42 +02:00
return
2019-02-18 20:32:41 +01:00
}
expr, ok := stmt.Body.List[0].(*ast.ExprStmt)
if !ok {
2019-04-22 12:59:42 +02:00
return
2019-02-18 20:32:41 +01:00
}
call, ok := expr.X.(*ast.CallExpr)
if !ok {
2019-04-22 12:59:42 +02:00
return
2019-02-18 20:32:41 +01:00
}
if !IsCallToAST(pass, call, "delete") {
2019-04-22 12:59:42 +02:00
return
2019-02-18 20:32:41 +01:00
}
b, m, key, ok := isCommaOkMapIndex(stmt.Init)
if !ok {
2019-04-22 12:59:42 +02:00
return
2019-02-18 20:32:41 +01:00
}
if cond, ok := stmt.Cond.(*ast.Ident); !ok || pass.TypesInfo.ObjectOf(cond) != pass.TypesInfo.ObjectOf(b) {
2019-04-22 12:59:42 +02:00
return
2019-02-18 20:32:41 +01:00
}
if Render(pass, call.Args[0]) != Render(pass, m) || Render(pass, call.Args[1]) != Render(pass, key) {
2019-04-22 12:59:42 +02:00
return
2019-02-18 20:32:41 +01:00
}
ReportNodefFG(pass, stmt, "unnecessary guard around call to delete")
2019-02-18 20:32:41 +01:00
}
pass.ResultOf[inspect.Analyzer].(*inspector.Inspector).Preorder([]ast.Node{(*ast.IfStmt)(nil)}, fn)
return nil, nil
2019-02-18 20:32:41 +01:00
}
func LintSimplifyTypeSwitch(pass *analysis.Pass) (interface{}, error) {
2019-04-22 12:59:42 +02:00
fn := func(node ast.Node) {
stmt := node.(*ast.TypeSwitchStmt)
2019-02-18 20:32:41 +01:00
if stmt.Init != nil {
// bailing out for now, can't anticipate how type switches with initializers are being used
2019-04-22 12:59:42 +02:00
return
2019-02-18 20:32:41 +01:00
}
expr, ok := stmt.Assign.(*ast.ExprStmt)
if !ok {
// the user is in fact assigning the result
2019-04-22 12:59:42 +02:00
return
2019-02-18 20:32:41 +01:00
}
assert := expr.X.(*ast.TypeAssertExpr)
ident, ok := assert.X.(*ast.Ident)
if !ok {
2019-04-22 12:59:42 +02:00
return
2019-02-18 20:32:41 +01:00
}
x := pass.TypesInfo.ObjectOf(ident)
2019-02-18 20:32:41 +01:00
var allOffenders []ast.Node
for _, clause := range stmt.Body.List {
clause := clause.(*ast.CaseClause)
if len(clause.List) != 1 {
continue
}
hasUnrelatedAssertion := false
var offenders []ast.Node
ast.Inspect(clause, func(node ast.Node) bool {
assert2, ok := node.(*ast.TypeAssertExpr)
if !ok {
return true
}
ident, ok := assert2.X.(*ast.Ident)
if !ok {
hasUnrelatedAssertion = true
return false
}
if pass.TypesInfo.ObjectOf(ident) != x {
2019-02-18 20:32:41 +01:00
hasUnrelatedAssertion = true
return false
}
if !types.Identical(pass.TypesInfo.TypeOf(clause.List[0]), pass.TypesInfo.TypeOf(assert2.Type)) {
2019-02-18 20:32:41 +01:00
hasUnrelatedAssertion = true
return false
}
offenders = append(offenders, assert2)
return true
})
if !hasUnrelatedAssertion {
// don't flag cases that have other type assertions
// unrelated to the one in the case clause. often
// times, this is done for symmetry, when two
// different values have to be asserted to the same
// type.
allOffenders = append(allOffenders, offenders...)
}
}
if len(allOffenders) != 0 {
at := ""
for _, offender := range allOffenders {
pos := lint.DisplayPosition(pass.Fset, offender.Pos())
2019-02-18 20:32:41 +01:00
at += "\n\t" + pos.String()
}
ReportNodefFG(pass, expr, "assigning the result of this type assertion to a variable (switch %s := %s.(type)) could eliminate the following type assertions:%s", Render(pass, ident), Render(pass, ident), at)
2019-02-18 20:32:41 +01:00
}
}
pass.ResultOf[inspect.Analyzer].(*inspector.Inspector).Preorder([]ast.Node{(*ast.TypeSwitchStmt)(nil)}, fn)
return nil, nil
2019-02-18 20:32:41 +01:00
}