1
0
mirror of https://github.com/mgechev/revive.git synced 2024-11-24 08:32:22 +02:00

range-val-address: improve detection (#647)

This commit is contained in:
Bernhard Reisenberger 2022-03-12 09:32:57 +01:00 committed by GitHub
parent 577441d60c
commit f335f9792d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 43 additions and 2 deletions

View File

@ -95,16 +95,34 @@ func (bw rangeBodyVisitor) Visit(node ast.Node) ast.Visitor {
case *ast.CallExpr:
if fun, ok := e.Fun.(*ast.Ident); ok && fun.Name == "append" { // e.g. ...append(arr, &value)
for _, v := range e.Args {
if bw.isAccessingRangeValueAddress(v) {
bw.onFailure(bw.newFailure(e))
if lit, ok := v.(*ast.CompositeLit); ok { // e.g. ...append(arr, v{id:&value})
bw.checkCompositeLit(lit)
continue
}
if bw.isAccessingRangeValueAddress(v) { // e.g. ...append(arr, &value)
bw.onFailure(bw.newFailure(v))
}
}
}
case *ast.CompositeLit: // e.g. ...v{id:&value}
bw.checkCompositeLit(e)
}
}
return bw
}
func (bw rangeBodyVisitor) checkCompositeLit(comp *ast.CompositeLit) {
for _, exp := range comp.Elts {
e, ok := exp.(*ast.KeyValueExpr)
if !ok {
continue
}
if bw.isAccessingRangeValueAddress(e.Value) {
bw.onFailure(bw.newFailure(e.Value))
}
}
}
func (bw rangeBodyVisitor) isAccessingRangeValueAddress(exp ast.Expr) bool {
u, ok := exp.(*ast.UnaryExpr)
if !ok {

View File

@ -138,3 +138,26 @@ func rangeValAddress13() {
m = append(m, &value.id)
}
}
func rangeValAddress14() {
type v struct {
id *string
}
m := []v{}
for _, value := range []string{"A", "B", "C"} {
a := v{id: &value} // MATCH /suspicious assignment of 'value'. range-loop variables always have the same address/
m = append(m, a)
}
}
func rangeValAddress15() {
type v struct {
id *string
}
m := []v{}
for _, value := range []string{"A", "B", "C"} {
m = append(m, v{id: &value}) // MATCH /suspicious assignment of 'value'. range-loop variables always have the same address/
}
}