no-empty.js 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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. module.exports = {
  14. meta: {
  15. type: "suggestion",
  16. docs: {
  17. description: "disallow empty block statements",
  18. category: "Possible Errors",
  19. recommended: true,
  20. url: "https://eslint.org/docs/rules/no-empty"
  21. },
  22. schema: [
  23. {
  24. type: "object",
  25. properties: {
  26. allowEmptyCatch: {
  27. type: "boolean",
  28. default: false
  29. }
  30. },
  31. additionalProperties: false
  32. }
  33. ],
  34. messages: {
  35. unexpected: "Empty {{type}} statement."
  36. }
  37. },
  38. create(context) {
  39. const options = context.options[0] || {},
  40. allowEmptyCatch = options.allowEmptyCatch || false;
  41. const sourceCode = context.getSourceCode();
  42. return {
  43. BlockStatement(node) {
  44. // if the body is not empty, we can just return immediately
  45. if (node.body.length !== 0) {
  46. return;
  47. }
  48. // a function is generally allowed to be empty
  49. if (astUtils.isFunction(node.parent)) {
  50. return;
  51. }
  52. if (allowEmptyCatch && node.parent.type === "CatchClause") {
  53. return;
  54. }
  55. // any other block is only allowed to be empty, if it contains a comment
  56. if (sourceCode.getCommentsInside(node).length > 0) {
  57. return;
  58. }
  59. context.report({ node, messageId: "unexpected", data: { type: "block" } });
  60. },
  61. SwitchStatement(node) {
  62. if (typeof node.cases === "undefined" || node.cases.length === 0) {
  63. context.report({ node, messageId: "unexpected", data: { type: "switch" } });
  64. }
  65. }
  66. };
  67. }
  68. };