no-fallthrough.js 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152
  1. /**
  2. * @fileoverview Rule to flag fall-through cases in switch statements.
  3. * @author Matt DuVall <http://mattduvall.com/>
  4. */
  5. "use strict";
  6. //------------------------------------------------------------------------------
  7. // Helpers
  8. //------------------------------------------------------------------------------
  9. const DEFAULT_FALLTHROUGH_COMMENT = /falls?\s?through/iu;
  10. /**
  11. * Checks whether or not a given case has a fallthrough comment.
  12. * @param {ASTNode} caseWhichFallsThrough SwitchCase node which falls through.
  13. * @param {ASTNode} subsequentCase The case after caseWhichFallsThrough.
  14. * @param {RuleContext} context A rule context which stores comments.
  15. * @param {RegExp} fallthroughCommentPattern A pattern to match comment to.
  16. * @returns {boolean} `true` if the case has a valid fallthrough comment.
  17. */
  18. function hasFallthroughComment(caseWhichFallsThrough, subsequentCase, context, fallthroughCommentPattern) {
  19. const sourceCode = context.getSourceCode();
  20. if (caseWhichFallsThrough.consequent.length === 1 && caseWhichFallsThrough.consequent[0].type === "BlockStatement") {
  21. const trailingCloseBrace = sourceCode.getLastToken(caseWhichFallsThrough.consequent[0]);
  22. const commentInBlock = sourceCode.getCommentsBefore(trailingCloseBrace).pop();
  23. if (commentInBlock && fallthroughCommentPattern.test(commentInBlock.value)) {
  24. return true;
  25. }
  26. }
  27. const comment = sourceCode.getCommentsBefore(subsequentCase).pop();
  28. return Boolean(comment && fallthroughCommentPattern.test(comment.value));
  29. }
  30. /**
  31. * Checks whether or not a given code path segment is reachable.
  32. * @param {CodePathSegment} segment A CodePathSegment to check.
  33. * @returns {boolean} `true` if the segment is reachable.
  34. */
  35. function isReachable(segment) {
  36. return segment.reachable;
  37. }
  38. /**
  39. * Checks whether a node and a token are separated by blank lines
  40. * @param {ASTNode} node The node to check
  41. * @param {Token} token The token to compare against
  42. * @returns {boolean} `true` if there are blank lines between node and token
  43. */
  44. function hasBlankLinesBetween(node, token) {
  45. return token.loc.start.line > node.loc.end.line + 1;
  46. }
  47. //------------------------------------------------------------------------------
  48. // Rule Definition
  49. //------------------------------------------------------------------------------
  50. /** @type {import('../shared/types').Rule} */
  51. module.exports = {
  52. meta: {
  53. type: "problem",
  54. docs: {
  55. description: "Disallow fallthrough of `case` statements",
  56. recommended: true,
  57. url: "https://eslint.org/docs/rules/no-fallthrough"
  58. },
  59. schema: [
  60. {
  61. type: "object",
  62. properties: {
  63. commentPattern: {
  64. type: "string",
  65. default: ""
  66. },
  67. allowEmptyCase: {
  68. type: "boolean",
  69. default: false
  70. }
  71. },
  72. additionalProperties: false
  73. }
  74. ],
  75. messages: {
  76. case: "Expected a 'break' statement before 'case'.",
  77. default: "Expected a 'break' statement before 'default'."
  78. }
  79. },
  80. create(context) {
  81. const options = context.options[0] || {};
  82. let currentCodePath = null;
  83. const sourceCode = context.getSourceCode();
  84. const allowEmptyCase = options.allowEmptyCase || false;
  85. /*
  86. * We need to use leading comments of the next SwitchCase node because
  87. * trailing comments is wrong if semicolons are omitted.
  88. */
  89. let fallthroughCase = null;
  90. let fallthroughCommentPattern = null;
  91. if (options.commentPattern) {
  92. fallthroughCommentPattern = new RegExp(options.commentPattern, "u");
  93. } else {
  94. fallthroughCommentPattern = DEFAULT_FALLTHROUGH_COMMENT;
  95. }
  96. return {
  97. onCodePathStart(codePath) {
  98. currentCodePath = codePath;
  99. },
  100. onCodePathEnd() {
  101. currentCodePath = currentCodePath.upper;
  102. },
  103. SwitchCase(node) {
  104. /*
  105. * Checks whether or not there is a fallthrough comment.
  106. * And reports the previous fallthrough node if that does not exist.
  107. */
  108. if (fallthroughCase && (!hasFallthroughComment(fallthroughCase, node, context, fallthroughCommentPattern))) {
  109. context.report({
  110. messageId: node.test ? "case" : "default",
  111. node
  112. });
  113. }
  114. fallthroughCase = null;
  115. },
  116. "SwitchCase:exit"(node) {
  117. const nextToken = sourceCode.getTokenAfter(node);
  118. /*
  119. * `reachable` meant fall through because statements preceded by
  120. * `break`, `return`, or `throw` are unreachable.
  121. * And allows empty cases and the last case.
  122. */
  123. if (currentCodePath.currentSegments.some(isReachable) &&
  124. (node.consequent.length > 0 || (!allowEmptyCase && hasBlankLinesBetween(node, nextToken))) &&
  125. node.parent.cases[node.parent.cases.length - 1] !== node) {
  126. fallthroughCase = node;
  127. }
  128. }
  129. };
  130. }
  131. };