Skip to content

Commit

Permalink
internal/analysis/modernize: minmax: reject IfStmt with Init
Browse files Browse the repository at this point in the history
Updates golang/go#71111

Change-Id: I86cdf1731e6057c4c972b91c46e8d3216a18382d
Reviewed-on: https://go-review.googlesource.com/c/tools/+/640037
Auto-Submit: Alan Donovan <adonovan@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Robert Findley <rfindley@google.com>
Commit-Queue: Alan Donovan <adonovan@google.com>
  • Loading branch information
adonovan authored and gopherbot committed Jan 3, 2025
1 parent 29d66ee commit 43ba465
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 4 deletions.
9 changes: 5 additions & 4 deletions gopls/internal/analysis/modernize/minmax.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)),
}},
}},
})
Expand Down Expand Up @@ -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)),
}},
}},
})
Expand All @@ -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) {

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}

0 comments on commit 43ba465

Please sign in to comment.