1
0
mirror of https://github.com/mgechev/revive.git synced 2025-03-21 21:17:06 +02:00
revive/rule/ranges.go

59 lines
1.2 KiB
Go
Raw Normal View History

2018-01-21 18:04:41 -08:00
package rule
2017-11-26 20:14:25 -08:00
import (
"fmt"
"go/ast"
2018-01-21 18:04:41 -08:00
"github.com/mgechev/revive/linter"
2017-11-26 20:14:25 -08:00
)
// LintRangesRule lints given else constructs.
type LintRangesRule struct{}
// Apply applies the rule to given file.
2018-01-21 18:04:41 -08:00
func (r *LintRangesRule) Apply(file *linter.File, arguments linter.Arguments) []linter.Failure {
var failures []linter.Failure
2017-11-26 20:14:25 -08:00
2018-01-21 18:04:41 -08:00
onFailure := func(failure linter.Failure) {
2017-11-26 20:14:25 -08:00
failures = append(failures, failure)
}
2018-01-21 18:41:38 -08:00
w := &lintRanges{file, onFailure}
2018-01-21 18:48:51 -08:00
ast.Walk(w, file.AST)
2017-11-26 20:14:25 -08:00
return failures
}
// Name returns the rule name.
func (r *LintRangesRule) Name() string {
return "no-else-return"
}
type lintRanges struct {
2018-01-21 18:41:38 -08:00
file *linter.File
2018-01-21 18:04:41 -08:00
onFailure func(linter.Failure)
2017-11-26 20:14:25 -08:00
}
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 !isIdent(rs.Value, "_") {
// for ?, y = range m { ... }
return w
}
2018-01-21 18:04:41 -08:00
w.onFailure(linter.Failure{
2018-01-21 18:41:38 -08:00
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),
2017-11-26 20:14:25 -08:00
Confidence: 1,
Node: rs.Value,
})
// TODO: replacement?
return w
}