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

simple: reverse "len(x) > 0" as "len(x) == 0" #1423

Merged
merged 1 commit into from
Jul 9, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
13 changes: 10 additions & 3 deletions simple/lint.go
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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
}