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.
 
 
 
 
 
 

66 lines
1.4 KiB

  1. package rule
  2. import (
  3. "go/ast"
  4. "github.com/mgechev/revive/lint"
  5. )
  6. // EmptyBlockRule lints given else constructs.
  7. type EmptyBlockRule struct{}
  8. // Apply applies the rule to given file.
  9. func (r *EmptyBlockRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failure {
  10. var failures []lint.Failure
  11. onFailure := func(failure lint.Failure) {
  12. failures = append(failures, failure)
  13. }
  14. w := lintEmptyBlock{make(map[*ast.BlockStmt]bool, 0), onFailure}
  15. ast.Walk(w, file.AST)
  16. return failures
  17. }
  18. // Name returns the rule name.
  19. func (r *EmptyBlockRule) Name() string {
  20. return "empty-block"
  21. }
  22. type lintEmptyBlock struct {
  23. ignore map[*ast.BlockStmt]bool
  24. onFailure func(lint.Failure)
  25. }
  26. func (w lintEmptyBlock) Visit(node ast.Node) ast.Visitor {
  27. switch n := node.(type) {
  28. case *ast.FuncDecl:
  29. w.ignore[n.Body] = true
  30. return w
  31. case *ast.FuncLit:
  32. w.ignore[n.Body] = true
  33. return w
  34. case *ast.RangeStmt:
  35. if len(n.Body.List) == 0 {
  36. w.onFailure(lint.Failure{
  37. Confidence: 0.9,
  38. Node: n,
  39. Category: "logic",
  40. Failure: "this block is empty, you can remove it",
  41. })
  42. return nil // skip visiting the range subtree (it will produce a duplicated failure)
  43. }
  44. case *ast.BlockStmt:
  45. if !w.ignore[n] && len(n.List) == 0 {
  46. w.onFailure(lint.Failure{
  47. Confidence: 1,
  48. Node: n,
  49. Category: "logic",
  50. Failure: "this block is empty, you can remove it",
  51. })
  52. }
  53. }
  54. return w
  55. }