no-empty.js 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. /**
  2. * @fileoverview Rule to flag use of an empty block statement
  3. * @author Nicholas C. Zakas
  4. */
  5. "use strict";
  6. //------------------------------------------------------------------------------
  7. // Requirements
  8. //------------------------------------------------------------------------------
  9. const astUtils = require("./utils/ast-utils");
  10. //------------------------------------------------------------------------------
  11. // Rule Definition
  12. //------------------------------------------------------------------------------
  13. /** @type {import('../shared/types').Rule} */
  14. module.exports = {
  15. meta: {
  16. hasSuggestions: true,
  17. type: "suggestion",
  18. docs: {
  19. description: "Disallow empty block statements",
  20. recommended: true,
  21. url: "https://eslint.org/docs/rules/no-empty"
  22. },
  23. schema: [
  24. {
  25. type: "object",
  26. properties: {
  27. allowEmptyCatch: {
  28. type: "boolean",
  29. default: false
  30. }
  31. },
  32. additionalProperties: false
  33. }
  34. ],
  35. messages: {
  36. unexpected: "Empty {{type}} statement.",
  37. suggestComment: "Add comment inside empty {{type}} statement."
  38. }
  39. },
  40. create(context) {
  41. const options = context.options[0] || {},
  42. allowEmptyCatch = options.allowEmptyCatch || false;
  43. const sourceCode = context.getSourceCode();
  44. return {
  45. BlockStatement(node) {
  46. // if the body is not empty, we can just return immediately
  47. if (node.body.length !== 0) {
  48. return;
  49. }
  50. // a function is generally allowed to be empty
  51. if (astUtils.isFunction(node.parent)) {
  52. return;
  53. }
  54. if (allowEmptyCatch && node.parent.type === "CatchClause") {
  55. return;
  56. }
  57. // any other block is only allowed to be empty, if it contains a comment
  58. if (sourceCode.getCommentsInside(node).length > 0) {
  59. return;
  60. }
  61. context.report({
  62. node,
  63. messageId: "unexpected",
  64. data: { type: "block" },
  65. suggest: [
  66. {
  67. messageId: "suggestComment",
  68. data: { type: "block" },
  69. fix(fixer) {
  70. const range = [node.range[0] + 1, node.range[1] - 1];
  71. return fixer.replaceTextRange(range, " /* empty */ ");
  72. }
  73. }
  74. ]
  75. });
  76. },
  77. SwitchStatement(node) {
  78. if (typeof node.cases === "undefined" || node.cases.length === 0) {
  79. context.report({ node, messageId: "unexpected", data: { type: "switch" } });
  80. }
  81. }
  82. };
  83. }
  84. };