1 // Copyright 2020 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
5 // Package simplifyrange defines an Analyzer that simplifies range statements.
6 // https://golang.org/cmd/gofmt/#hdr-The_simplify_command
7 // https://github.com/golang/go/blob/master/src/cmd/gofmt/simplify.go
16 "golang.org/x/tools/go/analysis"
17 "golang.org/x/tools/go/analysis/passes/inspect"
18 "golang.org/x/tools/go/ast/inspector"
21 const Doc = `check for range statement simplifications
24 for x, _ = range v {...}
25 will be simplified to:
30 will be simplified to:
33 This is one of the simplifications that "gofmt -s" applies.`
35 var Analyzer = &analysis.Analyzer{
36 Name: "simplifyrange",
38 Requires: []*analysis.Analyzer{inspect.Analyzer},
42 func run(pass *analysis.Pass) (interface{}, error) {
43 inspect := pass.ResultOf[inspect.Analyzer].(*inspector.Inspector)
44 nodeFilter := []ast.Node{
45 (*ast.RangeStmt)(nil),
47 inspect.Preorder(nodeFilter, func(n ast.Node) {
48 var copy *ast.RangeStmt
49 if stmt, ok := n.(*ast.RangeStmt); ok {
56 end := newlineIndex(pass.Fset, copy)
58 // Range statements of the form: for i, _ := range x {}
60 if isBlank(copy.Value) {
64 // Range statements of the form: for _ := range x {}
65 if isBlank(copy.Key) && copy.Value == nil {
69 // Return early if neither if condition is met.
73 pass.Report(analysis.Diagnostic{
76 Message: "simplify range expression",
77 SuggestedFixes: suggestedFixes(pass.Fset, copy, end),
83 func suggestedFixes(fset *token.FileSet, rng *ast.RangeStmt, end token.Pos) []analysis.SuggestedFix {
85 printer.Fprint(&b, fset, rng)
87 index := bytes.Index(stmt, []byte("\n"))
88 // If there is a new line character, then don't replace the body.
92 return []analysis.SuggestedFix{{
93 Message: "Remove empty value",
94 TextEdits: []analysis.TextEdit{{
97 NewText: stmt[:index],
102 func newlineIndex(fset *token.FileSet, rng *ast.RangeStmt) token.Pos {
104 printer.Fprint(&b, fset, rng)
105 contents := b.Bytes()
106 index := bytes.Index(contents, []byte("\n"))
110 return rng.Pos() + token.Pos(index)
113 func isBlank(x ast.Expr) bool {
114 ident, ok := x.(*ast.Ident)
115 return ok && ident.Name == "_"