Skip to content

Commit

Permalink
checkers: add stringXbytes checker
Browse files Browse the repository at this point in the history
  • Loading branch information
7phs authored and quasilyte committed Jan 18, 2019
1 parent 12f0f85 commit f54bdb6
Show file tree
Hide file tree
Showing 3 changed files with 64 additions and 0 deletions.
47 changes: 47 additions & 0 deletions checkers/stringXbytes_checker.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
package checkers

import (
"go/ast"
"strings"

"github.com/go-lintpack/lintpack"
"github.com/go-lintpack/lintpack/astwalk"
"github.com/go-toolsmith/astfmt"
"github.com/go-toolsmith/typep"
)

func init() {
var info lintpack.CheckerInfo
info.Name = "stringXbytes"
info.Tags = []string{"diagnostic", "experimental"}
info.Summary = "Detects redundant conversions between string and []byte"
info.Before = `copy(b, []byte(s))`
info.After = `copy(b, s)`

collection.AddChecker(&info, func(ctx *lintpack.CheckerContext) lintpack.FileWalker {
return astwalk.WalkerForExpr(&stringXbytes{ctx: ctx})
})
}

type stringXbytes struct {
astwalk.WalkHandler
ctx *lintpack.CheckerContext
}

func (c *stringXbytes) VisitExpr(expr ast.Expr) {
if x, ok := expr.(*ast.CallExpr); ok && qualifiedName(x.Fun) == "copy" {
src := x.Args[1]

if byteCast, ok := src.(*ast.CallExpr); ok &&
typep.IsTypeExpr(c.ctx.TypesInfo, byteCast.Fun) &&
typep.HasStringProp(c.ctx.TypesInfo.TypeOf(byteCast.Args[0])) {

c.warn(byteCast, strings.TrimSuffix(strings.TrimPrefix(astfmt.Sprint(byteCast), "[]byte("), ")"))
}
}
}

func (c *stringXbytes) warn(cause *ast.CallExpr, suggestion string) {
c.ctx.Warn(cause, "can simplify `%s` to `%s`",
cause, suggestion)
}
8 changes: 8 additions & 0 deletions checkers/testdata/stringXbytes/negative_tests.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
package checker_test

func noWarnings() {
var b []byte
var s string

copy(b, s)
}
9 changes: 9 additions & 0 deletions checkers/testdata/stringXbytes/positive_tests.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
package checker_test

func warnings() {
var b []byte
var s string

/*! can simplify `[]byte(s)` to `s` */
copy(b, []byte(s))
}

0 comments on commit f54bdb6

Please sign in to comment.