File tree 3 files changed +18
-2
lines changed
gopls/internal/analysis/modernize
3 files changed +18
-2
lines changed Original file line number Diff line number Diff line change @@ -8,10 +8,12 @@ import (
8
8
"fmt"
9
9
"go/ast"
10
10
"go/token"
11
+ "go/types"
11
12
12
13
"golang.org/x/tools/go/analysis"
13
14
"golang.org/x/tools/go/analysis/passes/inspect"
14
15
"golang.org/x/tools/go/ast/inspector"
16
+ "golang.org/x/tools/go/types/typeutil"
15
17
"golang.org/x/tools/internal/analysisinternal"
16
18
"golang.org/x/tools/internal/astutil/cursor"
17
19
"golang.org/x/tools/internal/astutil/edge"
@@ -98,6 +100,14 @@ func rangeint(pass *analysis.Pass) {
98
100
})
99
101
}
100
102
103
+ // If limit is len(slice),
104
+ // simplify "range len(slice)" to "range slice".
105
+ if call , ok := limit .(* ast.CallExpr ); ok &&
106
+ typeutil .Callee (info , call ) == builtinLen &&
107
+ is [* types.Slice ](info .TypeOf (call .Args [0 ]).Underlying ()) {
108
+ limit = call .Args [0 ]
109
+ }
110
+
101
111
pass .Report (analysis.Diagnostic {
102
112
Pos : init .Pos (),
103
113
End : inc .End (),
Original file line number Diff line number Diff line change 1
1
package rangeint
2
2
3
- func _ (i int , s struct { i int }) {
3
+ func _ (i int , s struct { i int }, slice [] int ) {
4
4
for i := 0 ; i < 10 ; i ++ { // want "for loop can be modernized using range over int"
5
5
println (i )
6
6
}
@@ -9,6 +9,9 @@ func _(i int, s struct{ i int }) {
9
9
for i := 0 ; i < 10 ; i ++ { // want "for loop can be modernized using range over int"
10
10
// i unused within loop
11
11
}
12
+ for i := 0 ; i < len (slice ); i ++ { // want "for loop can be modernized using range over int"
13
+ println (slice [i ])
14
+ }
12
15
13
16
// nope
14
17
for i := 0 ; i < 10 ; { // nope: missing increment
Original file line number Diff line number Diff line change 1
1
package rangeint
2
2
3
- func _(i int, s struct{ i int }) {
3
+ func _(i int, s struct{ i int }, slice []int ) {
4
4
for i := range 10 { // want "for loop can be modernized using range over int"
5
5
println(i)
6
6
}
@@ -9,6 +9,9 @@ func _(i int, s struct{ i int }) {
9
9
for range 10 { // want "for loop can be modernized using range over int"
10
10
// i unused within loop
11
11
}
12
+ for i := range slice { // want "for loop can be modernized using range over int"
13
+ println(slice[i])
14
+ }
12
15
13
16
// nope
14
17
for i := 0; i < 10; { // nope: missing increment
You can’t perform that action at this time.
0 commit comments