You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

function-result-limit.go 1.6KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. package rule
  2. import (
  3. "fmt"
  4. "go/ast"
  5. "github.com/mgechev/revive/lint"
  6. )
  7. // FunctionResultsLimitRule lints given else constructs.
  8. type FunctionResultsLimitRule struct{}
  9. // Apply applies the rule to given file.
  10. func (r *FunctionResultsLimitRule) Apply(file *lint.File, arguments lint.Arguments) []lint.Failure {
  11. if len(arguments) != 1 {
  12. panic(`invalid configuration for "function-result-limit"`)
  13. }
  14. max, ok := arguments[0].(int64) // Alt. non panicking version
  15. if !ok {
  16. panic(fmt.Sprintf(`invalid value passed as return results number to the "function-result-limit" rule; need int64 but got %T`, arguments[0]))
  17. }
  18. if max < 0 {
  19. panic(`the value passed as return results number to the "function-result-limit" rule cannot be negative`)
  20. }
  21. var failures []lint.Failure
  22. walker := lintFunctionResultsNum{
  23. max: int(max),
  24. onFailure: func(failure lint.Failure) {
  25. failures = append(failures, failure)
  26. },
  27. }
  28. ast.Walk(walker, file.AST)
  29. return failures
  30. }
  31. // Name returns the rule name.
  32. func (r *FunctionResultsLimitRule) Name() string {
  33. return "function-result-limit"
  34. }
  35. type lintFunctionResultsNum struct {
  36. max int
  37. onFailure func(lint.Failure)
  38. }
  39. func (w lintFunctionResultsNum) Visit(n ast.Node) ast.Visitor {
  40. node, ok := n.(*ast.FuncDecl)
  41. if ok {
  42. num := 0
  43. if node.Type.Results != nil {
  44. num = node.Type.Results.NumFields()
  45. }
  46. if num > w.max {
  47. w.onFailure(lint.Failure{
  48. Confidence: 1,
  49. Failure: fmt.Sprintf("maximum number of return results per function exceeded; max %d but got %d", w.max, num),
  50. Node: node.Type,
  51. })
  52. return w
  53. }
  54. }
  55. return w
  56. }