Skip to content

Commit

Permalink
SA4006: Fix for compound operators, increment/decrement
Browse files Browse the repository at this point in the history
In the case of compound operators such as +=, -=, etc we need to use the
left-hand side to get the value.

For IncDec we need a different codepath from AssignStmt altogether.

Fixes #1329
  • Loading branch information
arp242 committed May 31, 2024
1 parent 80d98d7 commit a6b8923
Show file tree
Hide file tree
Showing 2 changed files with 64 additions and 2 deletions.
26 changes: 24 additions & 2 deletions staticcheck/sa4006/sa4006.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package sa4006
import (
"fmt"
"go/ast"
"go/token"

"honnef.co/go/tools/analysis/code"
"honnef.co/go/tools/analysis/facts/generated"
Expand Down Expand Up @@ -31,7 +32,7 @@ var SCAnalyzer = lint.InitializeAnalyzer(&lint.Analyzer{

var Analyzer = SCAnalyzer.Analyzer

func run(pass *analysis.Pass) (interface{}, error) {
func run(pass *analysis.Pass) (any, error) {
for _, fn := range pass.ResultOf[buildir.Analyzer].(*buildir.IR).SrcFuncs {
if irutil.IsExample(fn) {
continue
Expand Down Expand Up @@ -99,6 +100,22 @@ func run(pass *analysis.Pass) (interface{}, error) {
}

ast.Inspect(node, func(node ast.Node) bool {
inc, ok := node.(*ast.IncDecStmt)
if ok {
val, _ := fn.ValueForExpr(inc.X)
if val == nil {
return true
}
if _, ok := val.(*ir.Const); ok {
// a zero-valued constant, for example in 'foo := []string(nil)'
return true
}
if !hasUse(val, nil) {
report.Report(pass, inc, fmt.Sprintf("this value of %s is never used", inc.X))
}
return true
}

assign, ok := node.(*ast.AssignStmt)
if !ok {
return true
Expand Down Expand Up @@ -137,7 +154,12 @@ func run(pass *analysis.Pass) (interface{}, error) {
}
val, _ := fn.ValueForExpr(rhs)
if val == nil {
continue
if assign.Tok != token.ASSIGN { // +=, *=, etc.
val, _ = fn.ValueForExpr(lhs)
}
if val == nil {
continue
}
}

if _, ok := val.(*ir.Const); ok {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -142,3 +142,43 @@ func fn10() {
}
fmt.Println(slice)
}

func issue1329() {
{
n := 1
n += 1 //@ diag(`this value of n is never used`)
}
{
n := 1
n ^= 1 //@ diag(`this value of n is never used`)
}
{
n := ""
n += "" //@ diag(`this value of n is never used`)
}
{
n := 1
n++ //@ diag(`this value of n is never used`)
}

{
n := 1
n += 1
fmt.Println(n)
}
{
n := 1
n ^= 1
fmt.Println(n)
}
{
n := ""
n += ""
fmt.Println(n)
}
{
n := 1
n++
fmt.Println(n)
}
}

0 comments on commit a6b8923

Please sign in to comment.