Skip to content

Commit c3b541f

Browse files
authoredDec 4, 2024
refactor (rule/arguments-limits): replace AST walker by iteration over declarations (#1159)
1 parent 275b018 commit c3b541f

File tree

2 files changed

+29
-39
lines changed

2 files changed

+29
-39
lines changed
 

‎rule/argument_limit.go

+20-37
Original file line numberDiff line numberDiff line change
@@ -35,50 +35,33 @@ func (r *ArgumentsLimitRule) Apply(file *lint.File, arguments lint.Arguments) []
3535
r.configureOnce.Do(func() { r.configure(arguments) })
3636

3737
var failures []lint.Failure
38-
onFailure := func(failure lint.Failure) {
39-
failures = append(failures, failure)
40-
}
41-
42-
walker := lintArgsNum{
43-
max: r.max,
44-
onFailure: onFailure,
45-
}
46-
47-
ast.Walk(walker, file.AST)
48-
49-
return failures
50-
}
51-
52-
// Name returns the rule name.
53-
func (*ArgumentsLimitRule) Name() string {
54-
return "argument-limit"
55-
}
5638

57-
type lintArgsNum struct {
58-
max int
59-
onFailure func(lint.Failure)
60-
}
39+
for _, decl := range file.AST.Decls {
40+
funcDecl, ok := decl.(*ast.FuncDecl)
41+
if !ok {
42+
continue
43+
}
6144

62-
func (w lintArgsNum) Visit(n ast.Node) ast.Visitor {
63-
node, ok := n.(*ast.FuncDecl)
64-
if !ok {
65-
return w
66-
}
45+
numParams := 0
46+
for _, l := range funcDecl.Type.Params.List {
47+
numParams += len(l.Names)
48+
}
6749

68-
num := 0
69-
for _, l := range node.Type.Params.List {
70-
for range l.Names {
71-
num++
50+
if numParams <= r.max {
51+
continue
7252
}
73-
}
7453

75-
if num > w.max {
76-
w.onFailure(lint.Failure{
54+
failures = append(failures, lint.Failure{
7755
Confidence: 1,
78-
Failure: fmt.Sprintf("maximum number of arguments per function exceeded; max %d but got %d", w.max, num),
79-
Node: node.Type,
56+
Failure: fmt.Sprintf("maximum number of arguments per function exceeded; max %d but got %d", r.max, numParams),
57+
Node: funcDecl.Type,
8058
})
8159
}
8260

83-
return nil // skip visiting the body of the function
61+
return failures
62+
}
63+
64+
// Name returns the rule name.
65+
func (*ArgumentsLimitRule) Name() string {
66+
return "argument-limit"
8467
}

‎test/argument_limit_test.go

+9-2
Original file line numberDiff line numberDiff line change
@@ -7,12 +7,19 @@ import (
77
"github.com/mgechev/revive/rule"
88
)
99

10-
func TestArgumentLimitDefault(t *testing.T) {
10+
func TestArgumentsLimitDefault(t *testing.T) {
1111
testRule(t, "argument_limit_default", &rule.ArgumentsLimitRule{}, &lint.RuleConfig{})
1212
}
1313

14-
func TestArgumentLimit(t *testing.T) {
14+
func TestArgumentsLimit(t *testing.T) {
1515
testRule(t, "argument_limit", &rule.ArgumentsLimitRule{}, &lint.RuleConfig{
1616
Arguments: []any{int64(3)},
1717
})
1818
}
19+
20+
func BenchmarkArgumentsLimit(b *testing.B) {
21+
var t *testing.T
22+
for i := 0; i <= b.N; i++ {
23+
testRule(t, "argument_limit_default", &rule.ArgumentsLimitRule{}, &lint.RuleConfig{})
24+
}
25+
}

0 commit comments

Comments
 (0)
Please sign in to comment.