1
0
mirror of https://github.com/mgechev/revive.git synced 2025-11-23 22:04:49 +02:00
Files
revive/rule/range.go
chavacava 92f28cb5e1 refactor: moves code related to AST from rule.utils into astutils package (#1380)
Modifications summary:

* Moves AST-related functions from rule/utils.go to astutils/ast_utils.go (+ modifies function calls)
* Renames some of these AST-related functions
* Avoids instantiating a printer config at each call to astutils.GoFmt
* Uses astutils.IsIdent and astutils.IsPkgDotName when possible
2025-05-26 13:18:38 +02:00

84 lines
1.7 KiB
Go

package rule
import (
"fmt"
"go/ast"
"strings"
"github.com/mgechev/revive/internal/astutils"
"github.com/mgechev/revive/lint"
)
// RangeRule prevents redundant variables when iterating over a collection.
type RangeRule struct{}
// Apply applies the rule to given file.
func (*RangeRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failure {
var failures []lint.Failure
onFailure := func(failure lint.Failure) {
failures = append(failures, failure)
}
w := &lintRanges{file, onFailure}
ast.Walk(w, file.AST)
return failures
}
// Name returns the rule name.
func (*RangeRule) Name() string {
return "range"
}
type lintRanges struct {
file *lint.File
onFailure func(lint.Failure)
}
func (w *lintRanges) Visit(node ast.Node) ast.Visitor {
rs, ok := node.(*ast.RangeStmt)
if !ok {
return w
}
if rs.Value == nil {
// for x = range m { ... }
return w // single var form
}
if !astutils.IsIdent(rs.Value, "_") {
// for ?, y = range m { ... }
return w
}
newRS := *rs // shallow copy
newRS.Value = nil
w.onFailure(lint.Failure{
Failure: fmt.Sprintf("should omit 2nd value from range; this loop is equivalent to `for %s %s range ...`", w.file.Render(rs.Key), rs.Tok),
Confidence: 1,
Node: rs.Value,
ReplacementLine: firstLineOf(w.file, &newRS, rs),
})
return w
}
func firstLineOf(f *lint.File, node, match ast.Node) string {
line := f.Render(node)
if i := strings.Index(line, "\n"); i >= 0 {
line = line[:i]
}
return indentOf(f, match) + line
}
func indentOf(f *lint.File, node ast.Node) string {
line := srcLine(f.Content(), f.ToPosition(node.Pos()))
for i, r := range line {
switch r {
case ' ', '\t':
default:
return line[:i]
}
}
return line // unusual or empty line
}