1
0
mirror of https://github.com/mgechev/revive.git synced 2024-12-02 09:02:23 +02:00
revive/rule/argument-limit.go

66 lines
1.3 KiB
Go
Raw Normal View History

2018-01-22 04:04:41 +02:00
package rule
2017-11-20 04:23:01 +02:00
import (
"fmt"
"go/ast"
2018-01-25 01:44:03 +02:00
"github.com/mgechev/revive/lint"
2017-11-20 04:23:01 +02:00
)
// ArgumentsLimitRule lints given else constructs.
type ArgumentsLimitRule struct{}
// Apply applies the rule to given file.
2018-01-25 01:44:03 +02:00
func (r *ArgumentsLimitRule) Apply(file *lint.File, arguments lint.Arguments) []lint.Failure {
checkNumberOfArguments(1, arguments, r.Name())
2018-01-27 06:45:17 +02:00
total, ok := arguments[0].(int64) // Alt. non panicking version
if !ok {
panic(`invalid value passed as argument number to the "argument-list" rule`)
2017-11-20 04:23:01 +02:00
}
2018-01-25 01:44:03 +02:00
var failures []lint.Failure
2017-11-20 04:23:01 +02:00
walker := lintArgsNum{
2018-01-27 06:45:17 +02:00
total: int(total),
2018-01-25 01:44:03 +02:00
onFailure: func(failure lint.Failure) {
2017-11-20 04:23:01 +02:00
failures = append(failures, failure)
},
}
2018-01-22 04:48:51 +02:00
ast.Walk(walker, file.AST)
2017-11-20 04:23:01 +02:00
return failures
}
// Name returns the rule name.
func (r *ArgumentsLimitRule) Name() string {
return "argument-limit"
}
type lintArgsNum struct {
2018-01-27 06:45:17 +02:00
total int
2018-01-25 01:44:03 +02:00
onFailure func(lint.Failure)
2017-11-20 04:23:01 +02:00
}
func (w lintArgsNum) Visit(n ast.Node) ast.Visitor {
node, ok := n.(*ast.FuncDecl)
if ok {
2018-02-05 01:10:35 +02:00
num := 0
for _, l := range node.Type.Params.List {
for range l.Names {
num++
}
}
2017-11-20 04:23:01 +02:00
if num > w.total {
2018-01-25 01:44:03 +02:00
w.onFailure(lint.Failure{
2018-01-27 06:34:20 +02:00
Confidence: 1,
Failure: fmt.Sprintf("maximum number of arguments per function exceeded; max %d but got %d", w.total, num),
Node: node.Type,
2017-11-20 04:23:01 +02:00
})
2017-11-20 06:32:18 +02:00
return w
2017-11-20 04:23:01 +02:00
}
}
return w
}