diff --git a/gopls/internal/analysis/modernize/minmax.go b/gopls/internal/analysis/modernize/minmax.go index 676090073f2..06330657876 100644 --- a/gopls/internal/analysis/modernize/minmax.go +++ b/gopls/internal/analysis/modernize/minmax.go @@ -84,11 +84,11 @@ func minmax(pass *analysis.Pass) { // Replace IfStmt with lhs = min(a, b). Pos: ifStmt.Pos(), End: ifStmt.End(), - NewText: []byte(fmt.Sprintf("%s = %s(%s, %s)", + NewText: fmt.Appendf(nil, "%s = %s(%s, %s)", formatNode(pass.Fset, lhs), sym, formatNode(pass.Fset, a), - formatNode(pass.Fset, b))), + formatNode(pass.Fset, b)), }}, }}, }) @@ -133,10 +133,10 @@ func minmax(pass *analysis.Pass) { // Replace rhs2 and IfStmt with min(a, b) Pos: rhs2.Pos(), End: ifStmt.End(), - NewText: []byte(fmt.Sprintf("%s(%s, %s)", + NewText: fmt.Appendf(nil, "%s(%s, %s)", sym, formatNode(pass.Fset, a), - formatNode(pass.Fset, b))), + formatNode(pass.Fset, b)), }}, }}, }) @@ -151,6 +151,7 @@ func minmax(pass *analysis.Pass) { ifStmt := curIfStmt.Node().(*ast.IfStmt) if compare, ok := ifStmt.Cond.(*ast.BinaryExpr); ok && + ifStmt.Init == nil && isInequality(compare.Op) != 0 && isAssignBlock(ifStmt.Body) { diff --git a/gopls/internal/analysis/modernize/testdata/src/minmax/minmax.go b/gopls/internal/analysis/modernize/testdata/src/minmax/minmax.go index d2efeb71589..393b3729e07 100644 --- a/gopls/internal/analysis/modernize/testdata/src/minmax/minmax.go +++ b/gopls/internal/analysis/modernize/testdata/src/minmax/minmax.go @@ -63,3 +63,11 @@ func shadowed() int { } return time } + +func nopeIfStmtHasInitStmt() { + x := 1 + if y := 2; y < x { // silent: IfStmt has an Init stmt + x = y + } + print(x) +} diff --git a/gopls/internal/analysis/modernize/testdata/src/minmax/minmax.go.golden b/gopls/internal/analysis/modernize/testdata/src/minmax/minmax.go.golden index c29d42d69a0..aacf84dd1c4 100644 --- a/gopls/internal/analysis/modernize/testdata/src/minmax/minmax.go.golden +++ b/gopls/internal/analysis/modernize/testdata/src/minmax/minmax.go.golden @@ -43,3 +43,11 @@ func shadowed() int { } return time } + +func nopeIfStmtHasInitStmt() { + x := 1 + if y := 2; y < x { // silent: IfStmt has an Init stmt + x = y + } + print(x) +}