1
0
mirror of https://github.com/mgechev/revive.git synced 2025-03-31 21:55:29 +02:00

Merge pull request #75 from xuri/range-loop-var

New rule: range-loop-var
This commit is contained in:
SalvadorC 2018-09-29 07:07:33 +02:00 committed by GitHub
commit 672b7cdf37
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
6 changed files with 163 additions and 0 deletions

View File

@ -271,6 +271,7 @@ List of all available rules. The rules ported from `golint` are left unchanged a
| `redefines-builtin-id`| n/a | Warns on redefinitions of builtin identifiers | no | no |
| `function-result-limit` | int | Specifies the maximum number of results a function can return | no | no |
| `imports-blacklist` | []string | Disallows importing the specified packages | no | no |
| `range-val-in-closure`| n/a | Warns if range value is used in a closure dispatched as goroutine| no | no |
## Configurable rules

View File

@ -67,6 +67,7 @@ var allRules = append([]lint.Rule{
&rule.ImportsBlacklistRule{},
&rule.FunctionResultsLimitRule{},
&rule.MaxPublicStructsRule{},
&rule.RangeValInClosureRule{},
}, defaultRules...)
var allFormatters = []lint.Formatter{

View File

@ -0,0 +1,37 @@
package fixtures
import "fmt"
func foo() {
mySlice := []string{"A", "B", "C"}
for index, value := range mySlice {
go func() {
fmt.Printf("Index: %d\n", index) // MATCH /loop variable index captured by func literal/
fmt.Printf("Value: %s\n", value) // MATCH /loop variable value captured by func literal/
}()
}
myDict := make(map[string]int)
myDict["A"] = 1
myDict["B"] = 2
myDict["C"] = 3
for key, value := range myDict {
defer func() {
fmt.Printf("Index: %d\n", key) // MATCH /loop variable key captured by func literal/
fmt.Printf("Value: %s\n", value) // MATCH /loop variable value captured by func literal/
}()
}
for i, newg := range groups {
go func(newg int) {
newg.run(m.opts.Context,i) // MATCH /loop variable i captured by func literal/
}(newg)
}
for i, newg := range groups {
newg := newg
go func() {
newg.run(m.opts.Context,i) // MATCH /loop variable i captured by func literal/
}()
}
}

View File

@ -0,0 +1,111 @@
package rule
import (
"fmt"
"go/ast"
"github.com/mgechev/revive/lint"
)
// RangeValInClosureRule lints given else constructs.
type RangeValInClosureRule struct{}
// Apply applies the rule to given file.
func (r *RangeValInClosureRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failure {
var failures []lint.Failure
walker := rangeValInClosure{
onFailure: func(failure lint.Failure) {
failures = append(failures, failure)
},
}
ast.Walk(walker, file.AST)
return failures
}
// Name returns the rule name.
func (r *RangeValInClosureRule) Name() string {
return "range-val-in-closure"
}
type rangeValInClosure struct {
onFailure func(lint.Failure)
}
func (w rangeValInClosure) Visit(node ast.Node) ast.Visitor {
// Find the variables updated by the loop statement.
var vars []*ast.Ident
addVar := func(expr ast.Expr) {
if id, ok := expr.(*ast.Ident); ok {
vars = append(vars, id)
}
}
var body *ast.BlockStmt
switch n := node.(type) {
case *ast.RangeStmt:
body = n.Body
addVar(n.Key)
addVar(n.Value)
case *ast.ForStmt:
body = n.Body
switch post := n.Post.(type) {
case *ast.AssignStmt:
// e.g. for p = head; p != nil; p = p.next
for _, lhs := range post.Lhs {
addVar(lhs)
}
case *ast.IncDecStmt:
// e.g. for i := 0; i < n; i++
addVar(post.X)
}
}
if vars == nil {
return w
}
// Inspect a go or defer statement
// if it's the last one in the loop body.
// (We give up if there are following statements,
// because it's hard to prove go isn't followed by wait,
// or defer by return.)
if len(body.List) == 0 {
return w
}
var last *ast.CallExpr
switch s := body.List[len(body.List)-1].(type) {
case *ast.GoStmt:
last = s.Call
case *ast.DeferStmt:
last = s.Call
default:
return w
}
lit, ok := last.Fun.(*ast.FuncLit)
if !ok {
return w
}
if lit.Type == nil {
// Not referring to a variable (e.g. struct field name)
return w
}
ast.Inspect(lit.Body, func(n ast.Node) bool {
id, ok := n.(*ast.Ident)
if !ok || id.Obj == nil {
return true
}
for _, v := range vars {
if v.Obj == id.Obj {
w.onFailure(lint.Failure{
Confidence: 1,
Failure: fmt.Sprintf("loop variable %v captured by func literal", id.Name),
Node: n,
})
}
}
return true
})
return w
}

View File

@ -0,0 +1,12 @@
package test
import (
"testing"
"github.com/mgechev/revive/lint"
"github.com/mgechev/revive/rule"
)
func TestRangeValInClosure(t *testing.T) {
testRule(t, "range-val-in-closure", &rule.RangeValInClosureRule{}, &lint.RuleConfig{})
}

View File

@ -13,3 +13,4 @@
[rule.receiver-naming]
[rule.indent-error-flow]
[rule.empty-block]
[rule.range-val-in-closure]