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.

empty-block.go 1.4KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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([]*ast.BlockStmt, 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 []*ast.BlockStmt
  24. onFailure func(lint.Failure)
  25. }
  26. func (w lintEmptyBlock) Visit(node ast.Node) ast.Visitor {
  27. fd, ok := node.(*ast.FuncDecl)
  28. if ok {
  29. w.ignore = append(w.ignore, fd.Body)
  30. return w
  31. }
  32. fl, ok := node.(*ast.FuncLit)
  33. if ok {
  34. w.ignore = append(w.ignore, fl.Body)
  35. return w
  36. }
  37. block, ok := node.(*ast.BlockStmt)
  38. if !ok {
  39. return w
  40. }
  41. if mustIgnore(block, w.ignore) {
  42. return w
  43. }
  44. if len(block.List) == 0 {
  45. w.onFailure(lint.Failure{
  46. Confidence: 1,
  47. Node: block,
  48. Category: "logic",
  49. Failure: "this block is empty, you can remove it",
  50. })
  51. }
  52. return w
  53. }
  54. func mustIgnore(block *ast.BlockStmt, blackList []*ast.BlockStmt) bool {
  55. for _, b := range blackList {
  56. if b == block {
  57. return true
  58. }
  59. }
  60. return false
  61. }