github.com/songshiyun/revive@v1.1.5-0.20220323112655-f8433a19b3c5/rule/argument-limit.go (about)

     1  package rule
     2  
     3  import (
     4  	"fmt"
     5  	"go/ast"
     6  
     7  	"github.com/songshiyun/revive/lint"
     8  )
     9  
    10  // ArgumentsLimitRule lints given else constructs.
    11  type ArgumentsLimitRule struct {
    12  	total int
    13  }
    14  
    15  // Apply applies the rule to given file.
    16  func (r *ArgumentsLimitRule) Apply(file *lint.File, arguments lint.Arguments) []lint.Failure {
    17  	if r.total == 0 {
    18  		checkNumberOfArguments(1, arguments, r.Name())
    19  
    20  		total, ok := arguments[0].(int64) // Alt. non panicking version
    21  		if !ok {
    22  			panic(`invalid value passed as argument number to the "argument-limit" rule`)
    23  		}
    24  		r.total = int(total)
    25  	}
    26  
    27  	var failures []lint.Failure
    28  
    29  	walker := lintArgsNum{
    30  		total: r.total,
    31  		onFailure: func(failure lint.Failure) {
    32  			failures = append(failures, failure)
    33  		},
    34  	}
    35  
    36  	ast.Walk(walker, file.AST)
    37  
    38  	return failures
    39  }
    40  
    41  // Name returns the rule name.
    42  func (r *ArgumentsLimitRule) Name() string {
    43  	return "argument-limit"
    44  }
    45  
    46  type lintArgsNum struct {
    47  	total     int
    48  	onFailure func(lint.Failure)
    49  }
    50  
    51  func (w lintArgsNum) Visit(n ast.Node) ast.Visitor {
    52  	node, ok := n.(*ast.FuncDecl)
    53  	if ok {
    54  		num := 0
    55  		for _, l := range node.Type.Params.List {
    56  			for range l.Names {
    57  				num++
    58  			}
    59  		}
    60  		if num > w.total {
    61  			w.onFailure(lint.Failure{
    62  				Confidence: 1,
    63  				Failure:    fmt.Sprintf("maximum number of arguments per function exceeded; max %d but got %d", w.total, num),
    64  				Node:       node.Type,
    65  			})
    66  			return w
    67  		}
    68  	}
    69  	return w
    70  }