no-fallthrough.js 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221
  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. // Requirements
  8. //------------------------------------------------------------------------------
  9. const { directivesPattern } = require("../shared/directives");
  10. //------------------------------------------------------------------------------
  11. // Helpers
  12. //------------------------------------------------------------------------------
  13. const DEFAULT_FALLTHROUGH_COMMENT = /falls?\s?through/iu;
  14. /**
  15. * Checks all segments in a set and returns true if any are reachable.
  16. * @param {Set<CodePathSegment>} segments The segments to check.
  17. * @returns {boolean} True if any segment is reachable; false otherwise.
  18. */
  19. function isAnySegmentReachable(segments) {
  20. for (const segment of segments) {
  21. if (segment.reachable) {
  22. return true;
  23. }
  24. }
  25. return false;
  26. }
  27. /**
  28. * Checks whether or not a given comment string is really a fallthrough comment and not an ESLint directive.
  29. * @param {string} comment The comment string to check.
  30. * @param {RegExp} fallthroughCommentPattern The regular expression used for checking for fallthrough comments.
  31. * @returns {boolean} `true` if the comment string is truly a fallthrough comment.
  32. */
  33. function isFallThroughComment(comment, fallthroughCommentPattern) {
  34. return fallthroughCommentPattern.test(comment) && !directivesPattern.test(comment.trim());
  35. }
  36. /**
  37. * Checks whether or not a given case has a fallthrough comment.
  38. * @param {ASTNode} caseWhichFallsThrough SwitchCase node which falls through.
  39. * @param {ASTNode} subsequentCase The case after caseWhichFallsThrough.
  40. * @param {RuleContext} context A rule context which stores comments.
  41. * @param {RegExp} fallthroughCommentPattern A pattern to match comment to.
  42. * @returns {null | object} the comment if the case has a valid fallthrough comment, otherwise null
  43. */
  44. function getFallthroughComment(caseWhichFallsThrough, subsequentCase, context, fallthroughCommentPattern) {
  45. const sourceCode = context.sourceCode;
  46. if (caseWhichFallsThrough.consequent.length === 1 && caseWhichFallsThrough.consequent[0].type === "BlockStatement") {
  47. const trailingCloseBrace = sourceCode.getLastToken(caseWhichFallsThrough.consequent[0]);
  48. const commentInBlock = sourceCode.getCommentsBefore(trailingCloseBrace).pop();
  49. if (commentInBlock && isFallThroughComment(commentInBlock.value, fallthroughCommentPattern)) {
  50. return commentInBlock;
  51. }
  52. }
  53. const comment = sourceCode.getCommentsBefore(subsequentCase).pop();
  54. if (comment && isFallThroughComment(comment.value, fallthroughCommentPattern)) {
  55. return comment;
  56. }
  57. return null;
  58. }
  59. /**
  60. * Checks whether a node and a token are separated by blank lines
  61. * @param {ASTNode} node The node to check
  62. * @param {Token} token The token to compare against
  63. * @returns {boolean} `true` if there are blank lines between node and token
  64. */
  65. function hasBlankLinesBetween(node, token) {
  66. return token.loc.start.line > node.loc.end.line + 1;
  67. }
  68. //------------------------------------------------------------------------------
  69. // Rule Definition
  70. //------------------------------------------------------------------------------
  71. /** @type {import('../shared/types').Rule} */
  72. module.exports = {
  73. meta: {
  74. type: "problem",
  75. docs: {
  76. description: "Disallow fallthrough of `case` statements",
  77. recommended: true,
  78. url: "https://eslint.org/docs/latest/rules/no-fallthrough"
  79. },
  80. schema: [
  81. {
  82. type: "object",
  83. properties: {
  84. commentPattern: {
  85. type: "string",
  86. default: ""
  87. },
  88. allowEmptyCase: {
  89. type: "boolean",
  90. default: false
  91. },
  92. reportUnusedFallthroughComment: {
  93. type: "boolean",
  94. default: false
  95. }
  96. },
  97. additionalProperties: false
  98. }
  99. ],
  100. messages: {
  101. unusedFallthroughComment: "Found a comment that would permit fallthrough, but case cannot fall through.",
  102. case: "Expected a 'break' statement before 'case'.",
  103. default: "Expected a 'break' statement before 'default'."
  104. }
  105. },
  106. create(context) {
  107. const options = context.options[0] || {};
  108. const codePathSegments = [];
  109. let currentCodePathSegments = new Set();
  110. const sourceCode = context.sourceCode;
  111. const allowEmptyCase = options.allowEmptyCase || false;
  112. const reportUnusedFallthroughComment = options.reportUnusedFallthroughComment || false;
  113. /*
  114. * We need to use leading comments of the next SwitchCase node because
  115. * trailing comments is wrong if semicolons are omitted.
  116. */
  117. let previousCase = null;
  118. let fallthroughCommentPattern = null;
  119. if (options.commentPattern) {
  120. fallthroughCommentPattern = new RegExp(options.commentPattern, "u");
  121. } else {
  122. fallthroughCommentPattern = DEFAULT_FALLTHROUGH_COMMENT;
  123. }
  124. return {
  125. onCodePathStart() {
  126. codePathSegments.push(currentCodePathSegments);
  127. currentCodePathSegments = new Set();
  128. },
  129. onCodePathEnd() {
  130. currentCodePathSegments = codePathSegments.pop();
  131. },
  132. onUnreachableCodePathSegmentStart(segment) {
  133. currentCodePathSegments.add(segment);
  134. },
  135. onUnreachableCodePathSegmentEnd(segment) {
  136. currentCodePathSegments.delete(segment);
  137. },
  138. onCodePathSegmentStart(segment) {
  139. currentCodePathSegments.add(segment);
  140. },
  141. onCodePathSegmentEnd(segment) {
  142. currentCodePathSegments.delete(segment);
  143. },
  144. SwitchCase(node) {
  145. /*
  146. * Checks whether or not there is a fallthrough comment.
  147. * And reports the previous fallthrough node if that does not exist.
  148. */
  149. if (previousCase && previousCase.node.parent === node.parent) {
  150. const previousCaseFallthroughComment = getFallthroughComment(previousCase.node, node, context, fallthroughCommentPattern);
  151. if (previousCase.isFallthrough && !(previousCaseFallthroughComment)) {
  152. context.report({
  153. messageId: node.test ? "case" : "default",
  154. node
  155. });
  156. } else if (reportUnusedFallthroughComment && !previousCase.isSwitchExitReachable && previousCaseFallthroughComment) {
  157. context.report({
  158. messageId: "unusedFallthroughComment",
  159. node: previousCaseFallthroughComment
  160. });
  161. }
  162. }
  163. previousCase = null;
  164. },
  165. "SwitchCase:exit"(node) {
  166. const nextToken = sourceCode.getTokenAfter(node);
  167. /*
  168. * `reachable` meant fall through because statements preceded by
  169. * `break`, `return`, or `throw` are unreachable.
  170. * And allows empty cases and the last case.
  171. */
  172. const isSwitchExitReachable = isAnySegmentReachable(currentCodePathSegments);
  173. const isFallthrough = isSwitchExitReachable && (node.consequent.length > 0 || (!allowEmptyCase && hasBlankLinesBetween(node, nextToken))) &&
  174. node.parent.cases.at(-1) !== node;
  175. previousCase = {
  176. node,
  177. isSwitchExitReachable,
  178. isFallthrough
  179. };
  180. }
  181. };
  182. }
  183. };