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

Skip to content

Latest commit

 

History

History
1809 lines (1708 loc) · 44.8 KB

lint.go

File metadata and controls

1809 lines (1708 loc) · 44.8 KB
// Package simple contains a linter for Go source code.
package simple // import "honnef.co/go/tools/simple"
import (
"fmt"
"go/ast"
"go/constant"
"go/token"
"go/types"
"reflect"
"sort"
"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"
. "honnef.co/go/tools/arg"
"honnef.co/go/tools/internal/passes/buildssa"
"honnef.co/go/tools/internal/sharedcheck"
"honnef.co/go/tools/lint"
. "honnef.co/go/tools/lint/lintdsl"
)
func LintSingleCaseSelect(pass *analysis.Pass) (interface{}, error) {
isSingleSelect := func(node ast.Node) bool {
v, ok := node.(*ast.SelectStmt)
if !ok {
return false
}
return len(v.Body.List) == 1
}
< 8000 div>
seen := map[ast.Node]struct{}{}
fn := func(node ast.Node) {
switch v := node.(type) {
case *ast.ForStmt:
if len(v.Body.List) != 1 {
return
}
if !isSingleSelect(v.Body.List[0]) {
return
}
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
return
}
seen[v.Body.List[0]] = struct{}{}
ReportNodefFG(pass, node, "should use for range instead of for { select {} }")
case *ast.SelectStmt:
if _, ok := seen[v]; ok {
return
}
if !isSingleSelect(v) {
return
}
ReportNodefFG(pass, node, "should use a simple channel send/receive instead of select with a single case")
}
}
pass.ResultOf[inspect.Analyzer].(*inspector.Inspector).Preorder([]ast.Node{(*ast.ForStmt)(nil), (*ast.SelectStmt)(nil)}, fn)
return nil, nil
}
func LintLoopCopy(pass *analysis.Pass) (interface{}, error) {
fn := func(node ast.Node) {
loop := node.(*ast.RangeStmt)
if loop.Key == nil {
return
}
if len(loop.Body.List) != 1 {
return
}
stmt, ok := loop.Body.List[0].(*ast.AssignStmt)
if !ok {
return
}
if stmt.Tok != token.ASSIGN || len(stmt.Lhs) != 1 || len(stmt.Rhs) != 1 {
return
}
lhs, ok := stmt.Lhs[0].(*ast.IndexExpr)
if !ok {
return
}
if _, ok := pass.TypesInfo.TypeOf(lhs.X).(*types.Slice); !ok {
return
}
lidx, ok := lhs.Index.(*ast.Ident)
if !ok {
return
}
key, ok := loop.Key.(*ast.Ident)
if !ok {
return
}
if pass.TypesInfo.TypeOf(lhs) == nil || pass.TypesInfo.TypeOf(stmt.Rhs[0]) == nil {
return
}
if pass.TypesInfo.ObjectOf(lidx) != pass.TypesInfo.ObjectOf(key) {
return
}
if !types.Identical(pass.TypesInfo.TypeOf(lhs), pass.TypesInfo.TypeOf(stmt.Rhs[0])) {
return
}
if _, ok := pass.TypesInfo.TypeOf(loop.X).(*types.Slice); !ok {
return
}
if rhs, ok := stmt.Rhs[0].(*ast.IndexExpr); ok {
rx, ok := rhs.X.(*ast.Ident)
_ = rx
if !ok {
return
}
ridx, ok := rhs.Index.(*ast.Ident)
if !ok {
return
}
if pass.TypesInfo.ObjectOf(ridx) != pass.TypesInfo.ObjectOf(key) {
return
}
} else if rhs, ok := stmt.Rhs[0].(*ast.Ident); ok {
value, ok := loop.Value.(*ast.Ident)
if !ok {
return
}
if pass.TypesInfo.ObjectOf(rhs) != pass.TypesInfo.ObjectOf(value) {
return
}
} else {
return
}
ReportNodefFG(pass, loop, "should use copy() instead of a loop")
}
pass.ResultOf[inspect.Analyzer].(*inspector.Inspector).Preorder([]ast.Node{(*ast.RangeStmt)(nil)}, fn)
return nil, nil
}
func LintIfBoolCmp(pass *analysis.Pass) (interface{}, error) {
fn := func(node ast.Node) {
expr := node.(*ast.BinaryExpr)
if expr.Op != token.EQL && expr.Op != token.NEQ {
return
}
x := IsBoolConst(pass, expr.X)
y := IsBoolConst(pass, expr.Y)
if !x && !y {
return
}
var other ast.Expr
var val bool
if x {
val = BoolConst(pass, expr.X)
other = expr.Y
} else {
val = BoolConst(pass, expr.Y)
other = expr.X
}
basic, ok := pass.TypesInfo.TypeOf(other).Underlying().(*types.Basic)
if !ok || basic.Kind() != types.Bool {
return
}
op := ""
if (expr.Op == token.EQL && !val) || (expr.Op == token.NEQ && val) {
op = "!"
}
r := op + Render(pass, other)
l1 := len(r)
r = strings.TrimLeft(r, "!")
if (l1-len(r))%2 == 1 {
r = "!" + r
}
if IsInTest(pass, node) {
return
}
ReportNodefFG(pass, expr, "should omit comparison to bool constant, can be simplified to %s", r)
}
pass.ResultOf[inspect.Analyzer].(*inspector.Inspector).Preorder([]ast.Node{(*ast.BinaryExpr)(nil)}, fn)
return nil, nil
}
func LintBytesBufferConversions(pass *analysis.Pass) (interface{}, error) {
fn := func(node ast.Node) {
call := node.(*ast.CallExpr)
if len(call.Args) != 1 {
return
}
argCall, ok := call.Args[0].(*ast.CallExpr)
if !ok {
return
}
sel, ok := argCall.Fun.(*ast.SelectorExpr)
if !ok {
return
}
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))
}
}
pass.ResultOf[inspect.Analyzer].(*inspector.Inspector).Preorder([]ast.Node{(*ast.CallExpr)(nil)}, fn)
return nil, nil
}
func LintStringsContains(pass *analysis.Pass) (interface{}, error) {
// 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},
}
fn := func(node ast.Node) {
expr := node.(*ast.BinaryExpr)
switch expr.Op {
case token.GEQ, token.GTR, token.NEQ, token.LSS, token.EQL:
default:
return
}
value, ok := ExprToInt(pass, expr.Y)
if !ok {
return
}
allowedOps, ok := allowed[value]
if !ok {
return
}
b, ok := allowedOps[expr.Op]
if !ok {
return
}
call, ok := expr.X.(*ast.CallExpr)
if !ok {
return
}
sel, ok := call.Fun.(*ast.SelectorExpr)
if !ok {
return
}
pkgIdent, ok := sel.X.(*ast.Ident)
if !ok {
return
}
funIdent := sel.Sel
if pkgIdent.Name != "strings" && pkgIdent.Name != "bytes" {
return
}
newFunc := ""
switch funIdent.Name {
case "IndexRune":
newFunc = "ContainsRune"
case "IndexAny":
newFunc = "ContainsAny"
case "Index":
newFunc = "Contains"
default:
return
}
prefix := ""
if !b {
prefix = "!"
}
ReportNodefFG(pass, node, "should use %s%s.%s(%s) instead", prefix, pkgIdent.Name, newFunc, RenderArgs(pass, call.Args))
}
pass.ResultOf[inspect.Analyzer].(*inspector.Inspector).Preorder([]ast.Node{(*ast.BinaryExpr)(nil)}, fn)
return nil, nil
}
func LintBytesCompare(pass *analysis.Pass) (interface{}, error) {
fn := func(node ast.Node) {
expr := node.(*ast.BinaryExpr)
if expr.Op != token.NEQ && expr.Op != token.EQL {
return
}
call, ok := expr.X.(*ast.CallExpr)
if !ok {
return
}
if !IsCallToAST(pass, call, "bytes.Compare") {
return
}
value, ok := ExprToInt(pass, expr.Y)
if !ok || value != 0 {
return
}
args := RenderArgs(pass, call.Args)
prefix := ""
if expr.Op == token.NEQ {
prefix = "!"
}
8BD0
ReportNodefFG(pass, node, "should use %sbytes.Equal(%s) instead", prefix, args)
}
pass.ResultOf[inspect.Analyzer].(*inspector.Inspector).Preorder([]ast.Node{(*ast.BinaryExpr)(nil)}, fn)
return nil, nil
}
func LintForTrue(pass *analysis.Pass) (interface{}, error) {
fn := func(node ast.Node) {
loop := node.(*ast.ForStmt)
if loop.Init != nil || loop.Post != nil {
return
}
if !IsBoolConst(pass, loop.Cond) || !BoolConst(pass, loop.Cond) {
return
}
ReportNodefFG(pass, loop, "should use for {} instead of for true {}")
}
pass.ResultOf[inspect.Analyzer].(*inspector.Inspector).Preorder([]ast.Node{(*ast.ForStmt)(nil)}, fn)
return nil, nil
}
func LintRegexpRaw(pass *analysis.Pass) (interface{}, error) {
fn := func(node ast.Node) {
call := node.(*ast.CallExpr)
if !IsCallToAST(pass, call, "regexp.MustCompile") &&
!IsCallToAST(pass, call, "regexp.Compile") {
return
}
sel, ok := call.Fun.(*ast.SelectorExpr)
if !ok {
return
}
if len(call.Args) != 1 {
// invalid function call
return
}
lit, ok := call.Args[Arg("regexp.Compile.expr")].(*ast.BasicLit)
if !ok {
// TODO(dominikh): support string concat, maybe support constants
return
}
if lit.Kind != token.STRING {
// invalid function call
return
}
if lit.Value[0] != '"' {
// already a raw string
return
}
val := lit.Value
if !strings.Contains(val, `\\`) {
return
}
if strings.Contains(val, "`") {
return
}
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
return
}
}
ReportNodefFG(pass, call, "should use raw string (`...`) with regexp.%s to avoid having to escape twice", sel.Sel.Name)
}
pass.ResultOf[inspect.Analyzer].(*inspector.Inspector).Preorder([]ast.Node{(*ast.CallExpr)(nil)}, fn)
return nil, nil
}
func LintIfReturn(pass *analysis.Pass) (interface{}, error) {
fn := func(node ast.Node) {
block := node.(*ast.BlockStmt)
l := len(block.List)
if l < 2 {
return
}
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
return
}
}
// 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 {
return
}
if ifs.Else != nil || ifs.Init != nil {
return
}
if len(ifs.Body.List) != 1 {
return
}
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:
return
}
}
ret1, ok := ifs.Body.List[0].(*ast.ReturnStmt)
if !ok {
return
}
if len(ret1.Results) != 1 {
return
}
if !IsBoolConst(pass, ret1.Results[0]) {
return
}
ret2, ok := n2.(*ast.ReturnStmt)
if !ok {
return
}
if len(ret2.Results) != 1 {
return
}
if !IsBoolConst(pass, ret2.Results[0]) {
return
}
ReportNodefFG(pass, n1, "should use 'return <expr>' instead of 'if <expr> { return <bool> }; return <bool>'")
}
pass.ResultOf[inspect.Analyzer].(*inspector.Inspector).Preorder([]ast.Node{(*ast.BlockStmt)(nil)}, fn)
return nil, nil
}
// 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) {
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)
if !ok {
return false, false
}
return true, c.Val().Kind() == constant.Int && c.Val().String() == "0"
}
fn := func(node ast.Node) {
// check that expr is "x || y" or "x && y"
expr := node.(*ast.BinaryExpr)
if expr.Op != token.LOR && expr.Op != token.LAND {
return
}
eqNil := expr.Op == token.LOR
// check that x is "xx == nil" or "xx != nil"
x, ok := expr.X.(*ast.BinaryExpr)
if !ok {
return
}
if eqNil && x.Op != token.EQL {
return
}
if !eqNil && x.Op != token.NEQ {
return
}
xx, ok := x.X.(*ast.Ident)
if !ok {
return
}
if !IsNil(pass, x.Y) {
return
}
// check that y is "len(xx) == 0" or "len(xx) ... "
y, ok := expr.Y.(*ast.BinaryExpr)
if !ok {
return
}
if eqNil && y.Op != token.EQL { // must be len(xx) *==* 0
return
}
yx, ok := y.X.(*ast.CallExpr)
if !ok {
return
}
yxFun, ok := yx.Fun.(*ast.Ident)
if !ok || yxFun.Name != "len" || len(yx.Args) != 1 {
return
}
yxArg, ok := yx.Args[Arg("len.v")].(*ast.Ident)
if !ok {
return
}
if yxArg.Name != xx.Name {
return
}
if eqNil && !IsZero(y.Y) { // must be len(x) == *0*
return
}
if !eqNil {
isConst, isZero := isConstZero(y.Y)
if !isConst {
return
}
switch y.Op {
case token.EQL:
// avoid false positive for "xx != nil && len(xx) == 0"
if isZero {
return
}
case token.GEQ:
// avoid false positive for "xx != nil && len(xx) >= 0"
if isZero {
return
}
case token.NEQ:
// avoid false positive for "xx != nil && len(xx) != <non-zero>"
if !isZero {
return
}
case token.GTR:
// ok
default:
return
}
}
// 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) {
case *types.Slice:
nilType = "nil slices"
case *types.Map:
nilType = "nil maps"
case *types.Chan:
nilType = "nil channels"
default:
return
}
ReportNodefFG(pass, expr, "should omit nil check; len() for %s is defined as zero", nilType)
}
pass.ResultOf[inspect.Analyzer].(*inspector.Inspector).Preorder([]ast.Node{(*ast.BinaryExpr)(nil)}, fn)
return nil, nil
}
func LintSlicing(pass *analysis.Pass) (interface{}, error) {
fn := func(node ast.Node) {
n := node.(*ast.SliceExpr)
if n.Max != nil {
return
}
s, ok := n.X.(*ast.Ident)
if !ok || s.Obj == nil {
return
}
call, ok := n.High.(*ast.CallExpr)
if !ok || len(call.Args) != 1 || call.Ellipsis.IsValid() {
return
}
fun, ok := call.Fun.(*ast.Ident)
if !ok || fun.Name != "len" {
return
}
if _, ok := pass.TypesInfo.ObjectOf(fun).(*types.Builtin); !ok {
return
}
arg, ok := call.Args[Arg("len.v")].(*ast.Ident)
if !ok || arg.Obj != s.Obj {
return
}
ReportNodefFG(pass, n, "should omit second index in slice, s[a:len(s)] is identical to s[a:]")
}
pass.ResultOf[inspect.Analyzer].(*inspector.Inspector).Preorder([]ast.Node{(*ast.SliceExpr)(nil)}, fn)
return nil, nil
}
func refersTo(pass *analysis.Pass, expr ast.Expr, ident *ast.Ident) bool {
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) {
found = true
return false
}
return true
}
ast.Inspect(expr, fn)
return found
}
func LintLoopAppend(pass *analysis.Pass) (interface{}, error) {
fn := func(node ast.Node) {
loop := node.(*ast.RangeStmt)
if !IsBlank(loop.Key) {
return
}
val, ok := loop.Value.(*ast.Ident)
if !ok {
return
}
if len(loop.Body.List) != 1 {
return
}
stmt, ok := loop.Body.List[0].(*ast.AssignStmt)
if !ok {
return
}
if stmt.Tok != token.ASSIGN || len(stmt.Lhs) != 1 || len(stmt.Rhs) != 1 {
return
}
if refersTo(pass, stmt.Lhs[0], val) {
return
}
call, ok := stmt.Rhs[0].(*ast.CallExpr)
if !ok {
return
}
if len(call.Args) != 2 || call.Ellipsis.IsValid() {
return
}
fun, ok := call.Fun.(*ast.Ident)
if !ok {
return
}
obj := pass.TypesInfo.ObjectOf(fun)
fn, ok := obj.(*types.Builtin)
if !ok || fn.Name() != "append" {
return
}
src := pass.TypesInfo.TypeOf(loop.X)
dst := pass.TypesInfo.TypeOf(call.Args[Arg("append.slice")])
// TODO(dominikh) remove nil check once Go issue #15173 has
// been fixed
if src == nil {
return
}
if !types.Identical(src, dst) {
return
}
if Render(pass, stmt.Lhs[0]) != Render(pass, call.Args[Arg("append.slice")]) {
return
}
el, ok := call.Args[Arg("append.elems")].(*ast.Ident)
if !ok {
return
}
if pass.TypesInfo.ObjectOf(val) != pass.TypesInfo.ObjectOf(el) {
return
}
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))
}
pass.ResultOf[inspect.Analyzer].(*inspector.Inspector).Preorder([]ast.Node{(*ast.RangeStmt)(nil)}, fn)
return nil, nil
}
func LintTimeSince(pass *analysis.Pass) (interface{}, error) {
fn := func(node ast.Node) {
call := node.(*ast.CallExpr)
sel, ok := call.Fun.(*ast.SelectorExpr)
if !ok {
return
}
if !IsCallToAST(pass, sel.X, "time.Now") {
return
}
if sel.Sel.Name != "Sub" {
return
}
ReportNodefFG(pass, call, "should use time.Since instead of time.Now().Sub")
}
pass.ResultOf[inspect.Analyzer].(*inspector.Inspector).Preorder([]ast.Node{(*ast.CallExpr)(nil)}, fn)
return nil, nil
}
func LintTimeUntil(pass *analysis.Pass) (interface{}, error) {
if !IsGoVersion(pass, 8) {
return nil, nil
}
fn := func(node ast.Node) {
call := node.(*ast.CallExpr)
if !IsCallToAST(pass, call, "(time.Time).Sub") {
return
}
if !IsCallToAST(pass, call.Args[Arg("(time.Time).Sub.u")], "time.Now") {
return
}
ReportNodefFG(pass, call, "should use time.Until instead of t.Sub(time.Now())")
}
pass.ResultOf[inspect.Analyzer].(*inspector.Inspector).Preorder([]ast.Node{(*ast.CallExpr)(nil)}, fn)
return nil, nil
}
func LintUnnecessaryBlank(pass *analysis.Pass) (interface{}, error) {
fn1 := func(node ast.Node) {
assign := node.(*ast.AssignStmt)
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 {
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))
}
fn2 := func(node ast.Node) {
stmt := node.(*ast.AssignStmt)
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'")
}
}
fn3 := func(node ast.Node) {
rs := node.(*ast.RangeStmt)
// 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)
}
// 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 ...`")
}
}
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)
}
return nil, nil
}
func LintSimplerStructConversion(pass *analysis.Pass) (interface{}, error) {
var skip ast.Node
fn := func(node ast.Node) {
// 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
}
return
}
if node == skip {
return
}
lit, ok := node.(*ast.CompositeLit)
if !ok {
return
}
typ1, _ := pass.TypesInfo.TypeOf(lit.Type).(*types.Named)
if typ1 == nil {
return
}
s1, ok := typ1.Underlying().(*types.Struct)
if !ok {
return
}
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)
return typ, ident, typ != nil
}
if len(lit.Elts) == 0 {
return
}
if s1.NumFields() != len(lit.Elts) {
return
}
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 {
return
}
if i >= s1.NumFields() || s1.Field(i).Name() != elt.Sel.Name {
return
}
case *ast.KeyValueExpr:
var sel *ast.SelectorExpr
sel, ok = elt.Value.(*ast.SelectorExpr)
if !ok {
return
}
if elt.Key.(*ast.Ident).Name != sel.Sel.Name {
return
}
t, id, ok = getSelType(elt.Value)
}
if !ok {
return
}
// All fields must be initialized from the same object
if ident != nil && ident.Obj != id.Obj {
return
}
typ2, _ = t.(*types.Named)
if typ2 == nil {
return
}
ident = id
}
if typ2 == nil {
return
}
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.
return
}
s2, ok := typ2.Underlying().(*types.Struct)
if !ok {
return
}
if typ1 == typ2 {
return
}
if IsGoVersion(pass, 8) {
if !types.IdenticalIgnoreTags(s1, s2) {
return
}
} else {
if !types.Identical(s1, s2) {
return
}
}
ReportNodefFG(pass, node, "should convert %s (type %s) to %s instead of using struct literal",
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
}
func LintTrim(pass *analysis.Pass) (interface{}, error) {
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)
case *ast.IndexExpr:
return Render(pass, node1) == Render(pass, node2)
}
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
}
return sameNonDynamic(call.Args[Arg("len.v")], ident)
}
fn := func(node ast.Node) {
var pkg string
var fun string
ifstmt := node.(*ast.IfStmt)
if ifstmt.Init != nil {
return
}
if ifstmt.Else != nil {
return
}
if len(ifstmt.Body.List) != 1 {
return
}
condCall, ok := ifstmt.Cond.(*ast.CallExpr)
if !ok {
return
}
switch {
case IsCallToAST(pass, condCall, "strings.HasPrefix"):
pkg = "strings"
fun = "HasPrefix"
case IsCallToAST(pass, condCall, "strings.HasSuffix"):
pkg = "strings"
fun = "HasSuffix"
case IsCallToAST(pass, condCall, "strings.Contains"):
pkg = "strings"
fun = "Contains"
case IsCallToAST(pass, condCall, "bytes.HasPrefix"):
pkg = "bytes"
fun = "HasPrefix"
case IsCallToAST(pass, condCall, "bytes.HasSuffix"):
pkg = "bytes"
fun = "HasSuffix"
case IsCallToAST(pass, condCall, "bytes.Contains"):
pkg = "bytes"
fun = "Contains"
default:
return
}
assign, ok := ifstmt.Body.List[0].(*ast.AssignStmt)
if !ok {
return
}
if assign.Tok != token.ASSIGN {
return
}
if len(assign.Lhs) != 1 || len(assign.Rhs) != 1 {
return
}
if !sameNonDynamic(condCall.Args[0], assign.Lhs[0]) {
return
}
switch rhs := assign.Rhs[0].(type) {
0