Skip to content

Commit

Permalink
fix issue #637 (#638)
Browse files Browse the repository at this point in the history
  • Loading branch information
chavacava authored Feb 15, 2022
1 parent baa70eb commit d4fbc92
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 4 deletions.
15 changes: 13 additions & 2 deletions rule/range-val-in-closure.go
Original file line number Diff line number Diff line change
Expand Up @@ -87,15 +87,25 @@ func (w rangeValInClosure) Visit(node ast.Node) ast.Visitor {
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 {

var inspector func(n ast.Node) bool
inspector = func(n ast.Node) bool {
kv, ok := n.(*ast.KeyValueExpr)
if ok {
// do not check identifiers acting as key in key-value expressions (see issue #637)
ast.Inspect(kv.Value, inspector)
return false
}
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{
Expand All @@ -106,6 +116,7 @@ func (w rangeValInClosure) Visit(node ast.Node) ast.Visitor {
}
}
return true
})
}
ast.Inspect(lit.Body, inspector)
return w
}
16 changes: 14 additions & 2 deletions testdata/range-val-in-closure.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,14 +24,26 @@ func foo() {

for i, newg := range groups {
go func(newg int) {
newg.run(m.opts.Context,i) // MATCH /loop variable i captured by func literal/
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/
newg.run(m.opts.Context, i) // MATCH /loop variable i captured by func literal/
}()
}
}

func issue637() {
for key := range m {
myKey := key
go func() {
println(t{
key: myKey,
otherField: (10 + key), // MATCH /loop variable key captured by func literal/
})
}()
}
}

0 comments on commit d4fbc92

Please sign in to comment.