Skip to content

Commit

Permalink
simple: reverse "len(x) > 0" as "len(x) == 0"
Browse files Browse the repository at this point in the history
Rather than "len(x) <= 0", which is technically correct,
but not actually what most Go programmers would write,
since funcs like len or cap can never return negative integers.

Do the same for cap and copy, which never return negative ints either.

Fixes #1422.
  • Loading branch information
mvdan authored and dominikh committed Jul 9, 2023
1 parent ddee6bb commit bc75918
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 3 deletions.
13 changes: 10 additions & 3 deletions simple/lint.go
Expand Up @@ -546,7 +546,7 @@ func CheckIfReturn(pass *analysis.Pass) (interface{}, error) {
cond := m1.State["cond"].(ast.Expr)
origCond := cond
if ret1.Name == "false" {
cond = negate(cond)
cond = negate(pass, cond)
}
report.Report(pass, n1,
fmt.Sprintf("should use 'return %s' instead of 'if %s { return %s }; return %s'",
Expand All @@ -558,7 +558,7 @@ func CheckIfReturn(pass *analysis.Pass) (interface{}, error) {
return nil, nil
}

func negate(expr ast.Expr) ast.Expr {
func negate(pass *analysis.Pass, expr ast.Expr) ast.Expr {
switch expr := expr.(type) {
case *ast.BinaryExpr:
out := *expr
Expand All @@ -568,7 +568,14 @@ func negate(expr ast.Expr) ast.Expr {
case token.LSS:
out.Op = token.GEQ
case token.GTR:
out.Op = token.LEQ
// Some builtins never return negative ints; "len(x) <= 0" should be "len(x) == 0".
if call, ok := expr.X.(*ast.CallExpr); ok &&
code.IsCallToAny(pass, call, "len", "cap", "copy") &&
code.IsIntegerLiteral(pass, expr.Y, constant.MakeInt64(0)) {
out.Op = token.EQL
} else {
out.Op = token.LEQ
}
case token.NEQ:
out.Op = token.EQL
case token.LEQ:
Expand Down
7 changes: 7 additions & 0 deletions simple/testdata/src/example.com/CheckIfReturn/if-return.go
Expand Up @@ -153,3 +153,10 @@ func fn21(x bool) bool {
}
return false
}

func fn22(x string) bool {
if len(x) > 0 { //@ diag(`should use 'return len(x) == 0'`)
return false
}
return true
}

0 comments on commit bc75918

Please sign in to comment.