Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

SA4006: Fix for compound operators, increment/decrement #1555

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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)
}
}
Loading