Skip to content

Commit

Permalink
tools/syz-linter: suggest use of min/max functions
Browse files Browse the repository at this point in the history
They are shorter, more readable, and don't require temp vars.
  • Loading branch information
dvyukov committed Jan 17, 2025
1 parent 5d04aae commit bb91bdd
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 0 deletions.
42 changes: 42 additions & 0 deletions tools/syz-linter/linter.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,10 @@
package main

import (
"bytes"
"fmt"
"go/ast"
"go/printer"
"go/token"
"go/types"
"regexp"
Expand Down Expand Up @@ -71,6 +73,8 @@ func run(p *analysis.Pass) (interface{}, error) {
pass.checkLogErrorFormat(n)
case *ast.GenDecl:
pass.checkVarDecl(n)
case *ast.IfStmt:
pass.checkIfStmt(n)
}
return true
})
Expand Down Expand Up @@ -340,3 +344,41 @@ func (pass *Pass) checkVarDecl(n *ast.GenDecl) {
"Use either \"var x type\" or \"x := val\" or \"x := type(val)\"")
}
}

func (pass *Pass) checkIfStmt(n *ast.IfStmt) {
cond, ok := n.Cond.(*ast.BinaryExpr)
if !ok || len(n.Body.List) != 1 {
return
}
assign, ok := n.Body.List[0].(*ast.AssignStmt)
if !ok || assign.Tok != token.ASSIGN || len(assign.Lhs) != 1 {
return
}
isMin := true
switch cond.Op {
case token.GTR, token.GEQ:
case token.LSS, token.LEQ:
isMin = false
default:
return
}
x := pass.nodeString(cond.X)
y := pass.nodeString(cond.Y)
lhs := pass.nodeString(assign.Lhs[0])
rhs := pass.nodeString(assign.Rhs[0])
switch {
case x == lhs && y == rhs:
case x == rhs && y == lhs:
isMin = !isMin
default:
return
}
fn := map[bool]string{true: "min", false: "max"}[isMin]
pass.report(n, "Use %v function instead", fn)
}

func (pass *Pass) nodeString(n ast.Node) string {
w := new(bytes.Buffer)
printer.Fprint(w, pass.Fset, n)
return w.String()
}
13 changes: 13 additions & 0 deletions tools/syz-linter/testdata/src/lintertest/lintertest.go
Original file line number Diff line number Diff line change
Expand Up @@ -123,3 +123,16 @@ func varDecls() {
var d int = 0 // want "Don't use both var, type and value in variable declarations"
_, _, _, _ = a, b, c, d
}

func minmax() {
x, y := 0, 0
if x < y + 1 { // want "Use max function instead"
x = y + 1
}
if x >= y { // want "Use max function instead"
y = x
}
if x > 10 { // want "Use min function instead"
x = 10
}
}

0 comments on commit bb91bdd

Please sign in to comment.