Skip to content

Commit

Permalink
checkers: add hexLiterals (go-critic#772)
Browse files Browse the repository at this point in the history
  • Loading branch information
Delius authored and cristaloleg committed Jan 21, 2019
1 parent a800815 commit 6751be9
Show file tree
Hide file tree
Showing 3 changed files with 116 additions and 0 deletions.
94 changes: 94 additions & 0 deletions checkers/hexLiterals_checker.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
package checkers

import (
"go/ast"
"strings"
"unicode"

"github.com/go-lintpack/lintpack"
"github.com/go-lintpack/lintpack/astwalk"
"github.com/go-toolsmith/astcast"
"github.com/go-toolsmith/astp"
)

func init() {
var info lintpack.CheckerInfo
info.Name = "hexLiterals"
info.Tags = []string{"style", "experimental"}
info.Summary = ""
info.Before = `
x := 0X12
y := 0xfF`
info.After = `
x := 0x12
// (A)
y := 0xff
// (B)
y := 0xFF`

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

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

func (c *hexLiteralChecker) VisitExpr(expr ast.Expr) {
if !astp.IsBasicLit(expr) {
return
}
v := astcast.ToBasicLit(expr)

if !strings.HasPrefix(v.Value, "0X") && !strings.HasPrefix(v.Value, "0x") {
return
}

prefix := v.Value[:2]
value := v.Value[2:]

switch prefix {
case "0X":
if isAnyLetter(value) {
if isGoodHex(value) {
c.ctx.Warn(expr, "Should be 0x%s", value)
return
}
c.ctx.Warn(expr,
"Should be 0x%s or 0x%s",
strings.ToLower(value),
strings.ToUpper(value))
return
}

c.ctx.Warn(expr, "Should be 0x%s", value)
case "0x":
if isAnyLetter(value) {
if isGoodHex(value) {
return
}
c.ctx.Warn(expr,
"Should be 0x%s or 0x%s",
strings.ToLower(value),
strings.ToUpper(value))
return
}

c.ctx.Warn(expr, "Should be 0x%s", value)
}
}

func isAnyLetter(s string) bool {
for _, r := range s {
if unicode.IsLetter(r) {
return true
}
}
return false
}

func isGoodHex(value string) bool {
return value == strings.ToLower(value) || value == strings.ToUpper(value)
}
7 changes: 7 additions & 0 deletions checkers/testdata/hexLiterals/negative_tests.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package checker_test

func negatives() {
_ = 0xFF
_ = 0xff
_ = "0xfF"
}
15 changes: 15 additions & 0 deletions checkers/testdata/hexLiterals/positive_tests.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package checker_test

func someTest() {
/*! Should be 0x12 */
_ = 0X12

/*! Should be 0xff or 0xFF */
_ = 0xfF

/*! Should be 0xEE */
_ = 0XEE

/*! Should be 0xaa */
_ = 0Xaa
}

0 comments on commit 6751be9

Please sign in to comment.