Skip to content

Commit

Permalink
range-val-address: improve detection (#514)
Browse files Browse the repository at this point in the history
range-val-address: improve detection
  • Loading branch information
bernhardreisenberger committed May 3, 2021
1 parent e84dbc6 commit 3bac05c
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 3 deletions.
17 changes: 15 additions & 2 deletions rule/range-val-address.go
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ func (bw rangeBodyVisitor) Visit(node ast.Node) ast.Visitor {

for _, exp := range asgmt.Rhs {
switch e := exp.(type) {
case *ast.UnaryExpr: // e.g. ...&value
case *ast.UnaryExpr: // e.g. ...&value, ...&value.id
if bw.isAccessingRangeValueAddress(e) {
bw.onFailure(bw.newFailure(e))
}
Expand All @@ -100,8 +100,21 @@ func (bw rangeBodyVisitor) isAccessingRangeValueAddress(exp ast.Expr) bool {
return false
}

if u.Op != token.AND {
return false
}

v, ok := u.X.(*ast.Ident)
return ok && u.Op == token.AND && v.Obj == bw.valueID
if !ok {
var s *ast.SelectorExpr
s, ok = u.X.(*ast.SelectorExpr)
if !ok {
return false
}
v, ok = s.X.(*ast.Ident)
}

return ok && v.Obj == bw.valueID
}

func (bw rangeBodyVisitor) newFailure(node ast.Node) lint.Failure {
Expand Down
3 changes: 2 additions & 1 deletion rule/string-format.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,11 +30,12 @@ func (r *StringFormatRule) Apply(file *lint.File, arguments lint.Arguments) []li
return failures
}

// Name returns the rule name.
func (r *StringFormatRule) Name() string {
return "string-format"
}

// Public wrapper around w.parseArguments used for testing, returns the error message provided to panic, or nil if no error was encountered
// ParseArgumentsTest is a public wrapper around w.parseArguments used for testing. Returns the error message provided to panic, or nil if no error was encountered
func (r *StringFormatRule) ParseArgumentsTest(arguments lint.Arguments) *string {
w := lintStringFormatRule{}
c := make(chan interface{})
Expand Down
12 changes: 12 additions & 0 deletions testdata/range-val-address.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,3 +45,15 @@ func rangeValAddress5() {
m[&value] = value // MATCH /suspicious assignment of 'value'. range-loop variables always have the same address/
}
}

func rangeValAddress6() {
type v struct {
id string
}
m := []*string{}

mySlice := []v{{id: "A"}, {id: "B"}, {id: "C"}}
for _, value := range mySlice {
m = append(m, &value.id) // MATCH /suspicious assignment of 'value'. range-loop variables always have the same address/
}
}

0 comments on commit 3bac05c

Please sign in to comment.