@@ -98,19 +98,23 @@ func minmax(pass *analysis.Pass) {
98
98
} else if prev , ok := curIfStmt .PrevSibling (); ok && is [* ast.AssignStmt ](prev .Node ()) {
99
99
fassign := prev .Node ().(* ast.AssignStmt )
100
100
101
- // Have: lhs2 = rhs2; if a < b { lhs = rhs }
101
+ // Have: lhs0 = rhs0; if a < b { lhs = rhs }
102
+ //
102
103
// For pattern 2, check that
103
- // - lhs = lhs2
104
- // - {rhs,rhs2} = {a,b}, but allow lhs2 to
105
- // stand for rhs2.
106
- // TODO(adonovan): accept "var lhs2 = rhs2" form too.
107
- lhs2 := fassign .Lhs [0 ]
108
- rhs2 := fassign .Rhs [0 ]
109
-
110
- if equalSyntax (lhs , lhs2 ) {
111
- if equalSyntax (rhs , a ) && (equalSyntax (rhs2 , b ) || equalSyntax (lhs2 , b )) {
104
+ // - lhs = lhs0
105
+ // - {a,b} = {rhs,rhs0} or {rhs,lhs0}
106
+ // The replacement must use rhs0 not lhs0 though.
107
+ // For example, we accept this variant:
108
+ // lhs = x; if lhs < y { lhs = y } => lhs = min(x, y), not min(lhs, y)
109
+ //
110
+ // TODO(adonovan): accept "var lhs0 = rhs0" form too.
111
+ lhs0 := fassign .Lhs [0 ]
112
+ rhs0 := fassign .Rhs [0 ]
113
+
114
+ if equalSyntax (lhs , lhs0 ) {
115
+ if equalSyntax (rhs , a ) && (equalSyntax (rhs0 , b ) || equalSyntax (lhs0 , b )) {
112
116
sign = + sign
113
- } else if (equalSyntax (rhs2 , a ) || equalSyntax (lhs2 , a )) && equalSyntax (rhs , b ) {
117
+ } else if (equalSyntax (rhs0 , a ) || equalSyntax (lhs0 , a )) && equalSyntax (rhs , b ) {
114
118
sign = - sign
115
119
} else {
116
120
return
@@ -121,6 +125,15 @@ func minmax(pass *analysis.Pass) {
121
125
return // min/max function is shadowed
122
126
}
123
127
128
+ // Permit lhs0 to stand for rhs0 in the matching,
129
+ // but don't actually reduce to lhs0 = min(lhs0, rhs)
130
+ // since the "=" could be a ":=". Use min(rhs0, rhs).
131
+ if equalSyntax (lhs0 , a ) {
132
+ a = rhs0
133
+ } else if equalSyntax (lhs0 , b ) {
134
+ b = rhs0
135
+ }
136
+
124
137
// pattern 2
125
138
pass .Report (analysis.Diagnostic {
126
139
// Highlight the condition a < b.
@@ -131,8 +144,8 @@ func minmax(pass *analysis.Pass) {
131
144
SuggestedFixes : []analysis.SuggestedFix {{
132
145
Message : fmt .Sprintf ("Replace if/else with %s" , sym ),
133
146
TextEdits : []analysis.TextEdit {{
134
- // Replace rhs2 and IfStmt with min(a, b)
135
- Pos : rhs2 .Pos (),
147
+ // Replace rhs0 and IfStmt with min(a, b)
148
+ Pos : rhs0 .Pos (),
136
149
End : ifStmt .End (),
137
150
NewText : fmt .Appendf (nil , "%s(%s, %s)" ,
138
151
sym ,
0 commit comments