2018-10-01 21:24:17 +02:00
|
|
|
package rule
|
|
|
|
|
|
|
|
import (
|
|
|
|
"go/ast"
|
|
|
|
"go/token"
|
|
|
|
"go/types"
|
|
|
|
|
|
|
|
"github.com/mgechev/revive/lint"
|
|
|
|
)
|
|
|
|
|
|
|
|
// AtomicRule lints given else constructs.
|
|
|
|
type AtomicRule struct{}
|
|
|
|
|
|
|
|
// Apply applies the rule to given file.
|
|
|
|
func (r *AtomicRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failure {
|
|
|
|
var failures []lint.Failure
|
|
|
|
walker := atomic{
|
2018-10-03 20:56:57 +02:00
|
|
|
pkgTypesInfo: file.Pkg.TypesInfo,
|
2018-10-01 21:24:17 +02:00
|
|
|
onFailure: func(failure lint.Failure) {
|
|
|
|
failures = append(failures, failure)
|
|
|
|
},
|
|
|
|
}
|
|
|
|
|
|
|
|
ast.Walk(walker, file.AST)
|
|
|
|
|
|
|
|
return failures
|
|
|
|
}
|
|
|
|
|
|
|
|
// Name returns the rule name.
|
|
|
|
func (r *AtomicRule) Name() string {
|
|
|
|
return "atomic"
|
|
|
|
}
|
|
|
|
|
|
|
|
type atomic struct {
|
2018-10-03 20:56:57 +02:00
|
|
|
pkgTypesInfo *types.Info
|
|
|
|
onFailure func(lint.Failure)
|
2018-10-01 21:24:17 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
func (w atomic) Visit(node ast.Node) ast.Visitor {
|
|
|
|
n, ok := node.(*ast.AssignStmt)
|
|
|
|
if !ok {
|
|
|
|
return w
|
|
|
|
}
|
|
|
|
|
|
|
|
if len(n.Lhs) != len(n.Rhs) {
|
2018-10-03 20:56:57 +02:00
|
|
|
return nil // skip assignment sub-tree
|
2018-10-01 21:24:17 +02:00
|
|
|
}
|
|
|
|
if len(n.Lhs) == 1 && n.Tok == token.DEFINE {
|
2018-10-03 20:56:57 +02:00
|
|
|
return nil // skip assignment sub-tree
|
2018-10-01 21:24:17 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
for i, right := range n.Rhs {
|
|
|
|
call, ok := right.(*ast.CallExpr)
|
|
|
|
if !ok {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
sel, ok := call.Fun.(*ast.SelectorExpr)
|
|
|
|
if !ok {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
pkgIdent, _ := sel.X.(*ast.Ident)
|
2018-10-03 20:56:57 +02:00
|
|
|
if w.pkgTypesInfo != nil {
|
|
|
|
pkgName, ok := w.pkgTypesInfo.Uses[pkgIdent].(*types.PkgName)
|
2018-10-01 21:24:17 +02:00
|
|
|
if !ok || pkgName.Imported().Path() != "sync/atomic" {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
switch sel.Sel.Name {
|
|
|
|
case "AddInt32", "AddInt64", "AddUint32", "AddUint64", "AddUintptr":
|
|
|
|
left := n.Lhs[i]
|
|
|
|
if len(call.Args) != 2 {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
arg := call.Args[0]
|
|
|
|
broken := false
|
|
|
|
|
|
|
|
if uarg, ok := arg.(*ast.UnaryExpr); ok && uarg.Op == token.AND {
|
2018-10-03 20:56:57 +02:00
|
|
|
broken = gofmt(left) == gofmt(uarg.X)
|
2018-10-01 21:24:17 +02:00
|
|
|
} else if star, ok := left.(*ast.StarExpr); ok {
|
2018-10-03 20:56:57 +02:00
|
|
|
broken = gofmt(star.X) == gofmt(arg)
|
2018-10-01 21:24:17 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
if broken {
|
|
|
|
w.onFailure(lint.Failure{
|
|
|
|
Confidence: 1,
|
2018-10-03 20:56:57 +02:00
|
|
|
Failure: "direct assignment to atomic value",
|
2018-10-01 21:24:17 +02:00
|
|
|
Node: n,
|
|
|
|
})
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return w
|
|
|
|
}
|