From 43ba4651fe4ce4a4e2ab9d6d60956db78c119d26 Mon Sep 17 00:00:00 2001 From: Alan Donovan Date: Fri, 3 Jan 2025 15:16:23 -0500 Subject: [PATCH] internal/analysis/modernize: minmax: reject IfStmt with Init Updates golang/go#71111 Change-Id: I86cdf1731e6057c4c972b91c46e8d3216a18382d Reviewed-on: https://go-review.googlesource.com/c/tools/+/640037 Auto-Submit: Alan Donovan LUCI-TryBot-Result: Go LUCI Reviewed-by: Robert Findley Commit-Queue: Alan Donovan --- gopls/internal/analysis/modernize/minmax.go | 9 +++++---- .../analysis/modernize/testdata/src/minmax/minmax.go | 8 ++++++++ .../modernize/testdata/src/minmax/minmax.go.golden | 8 ++++++++ 3 files changed, 21 insertions(+), 4 deletions(-) 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) +}