no-fallthrough.js 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  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 (
  35. fallthroughCommentPattern.test(comment) &&
  36. !directivesPattern.test(comment.trim())
  37. );
  38. }
  39. /**
  40. * Checks whether or not a given case has a fallthrough comment.
  41. * @param {ASTNode} caseWhichFallsThrough SwitchCase node which falls through.
  42. * @param {ASTNode} subsequentCase The case after caseWhichFallsThrough.
  43. * @param {RuleContext} context A rule context which stores comments.
  44. * @param {RegExp} fallthroughCommentPattern A pattern to match comment to.
  45. * @returns {null | object} the comment if the case has a valid fallthrough comment, otherwise null
  46. */
  47. function getFallthroughComment(
  48. caseWhichFallsThrough,
  49. subsequentCase,
  50. context,
  51. fallthroughCommentPattern,
  52. ) {
  53. const sourceCode = context.sourceCode;
  54. if (
  55. caseWhichFallsThrough.consequent.length === 1 &&
  56. caseWhichFallsThrough.consequent[0].type === "BlockStatement"
  57. ) {
  58. const trailingCloseBrace = sourceCode.getLastToken(
  59. caseWhichFallsThrough.consequent[0],
  60. );
  61. const commentInBlock = sourceCode
  62. .getCommentsBefore(trailingCloseBrace)
  63. .pop();
  64. if (
  65. commentInBlock &&
  66. isFallThroughComment(
  67. commentInBlock.value,
  68. fallthroughCommentPattern,
  69. )
  70. ) {
  71. return commentInBlock;
  72. }
  73. }
  74. const comment = sourceCode.getCommentsBefore(subsequentCase).pop();
  75. if (
  76. comment &&
  77. isFallThroughComment(comment.value, fallthroughCommentPattern)
  78. ) {
  79. return comment;
  80. }
  81. return null;
  82. }
  83. /**
  84. * Checks whether a node and a token are separated by blank lines
  85. * @param {ASTNode} node The node to check
  86. * @param {Token} token The token to compare against
  87. * @returns {boolean} `true` if there are blank lines between node and token
  88. */
  89. function hasBlankLinesBetween(node, token) {
  90. return token.loc.start.line > node.loc.end.line + 1;
  91. }
  92. //------------------------------------------------------------------------------
  93. // Rule Definition
  94. //------------------------------------------------------------------------------
  95. /** @type {import('../types').Rule.RuleModule} */
  96. module.exports = {
  97. meta: {
  98. type: "problem",
  99. defaultOptions: [
  100. {
  101. allowEmptyCase: false,
  102. reportUnusedFallthroughComment: false,
  103. },
  104. ],
  105. docs: {
  106. description: "Disallow fallthrough of `case` statements",
  107. recommended: true,
  108. url: "https://eslint.org/docs/latest/rules/no-fallthrough",
  109. },
  110. schema: [
  111. {
  112. type: "object",
  113. properties: {
  114. commentPattern: {
  115. type: "string",
  116. },
  117. allowEmptyCase: {
  118. type: "boolean",
  119. },
  120. reportUnusedFallthroughComment: {
  121. type: "boolean",
  122. },
  123. },
  124. additionalProperties: false,
  125. },
  126. ],
  127. messages: {
  128. unusedFallthroughComment:
  129. "Found a comment that would permit fallthrough, but case cannot fall through.",
  130. case: "Expected a 'break' statement before 'case'.",
  131. default: "Expected a 'break' statement before 'default'.",
  132. },
  133. },
  134. create(context) {
  135. const codePathSegments = [];
  136. let currentCodePathSegments = new Set();
  137. const sourceCode = context.sourceCode;
  138. const [
  139. { allowEmptyCase, commentPattern, reportUnusedFallthroughComment },
  140. ] = context.options;
  141. const fallthroughCommentPattern = commentPattern
  142. ? new RegExp(commentPattern, "u")
  143. : DEFAULT_FALLTHROUGH_COMMENT;
  144. /*
  145. * We need to use leading comments of the next SwitchCase node because
  146. * trailing comments is wrong if semicolons are omitted.
  147. */
  148. let previousCase = null;
  149. return {
  150. onCodePathStart() {
  151. codePathSegments.push(currentCodePathSegments);
  152. currentCodePathSegments = new Set();
  153. },
  154. onCodePathEnd() {
  155. currentCodePathSegments = codePathSegments.pop();
  156. },
  157. onUnreachableCodePathSegmentStart(segment) {
  158. currentCodePathSegments.add(segment);
  159. },
  160. onUnreachableCodePathSegmentEnd(segment) {
  161. currentCodePathSegments.delete(segment);
  162. },
  163. onCodePathSegmentStart(segment) {
  164. currentCodePathSegments.add(segment);
  165. },
  166. onCodePathSegmentEnd(segment) {
  167. currentCodePathSegments.delete(segment);
  168. },
  169. SwitchCase(node) {
  170. /*
  171. * Checks whether or not there is a fallthrough comment.
  172. * And reports the previous fallthrough node if that does not exist.
  173. */
  174. if (previousCase && previousCase.node.parent === node.parent) {
  175. const previousCaseFallthroughComment =
  176. getFallthroughComment(
  177. previousCase.node,
  178. node,
  179. context,
  180. fallthroughCommentPattern,
  181. );
  182. if (
  183. previousCase.isFallthrough &&
  184. !previousCaseFallthroughComment
  185. ) {
  186. context.report({
  187. messageId: node.test ? "case" : "default",
  188. node,
  189. });
  190. } else if (
  191. reportUnusedFallthroughComment &&
  192. !previousCase.isSwitchExitReachable &&
  193. previousCaseFallthroughComment
  194. ) {
  195. context.report({
  196. messageId: "unusedFallthroughComment",
  197. node: previousCaseFallthroughComment,
  198. });
  199. }
  200. }
  201. previousCase = null;
  202. },
  203. "SwitchCase:exit"(node) {
  204. const nextToken = sourceCode.getTokenAfter(node);
  205. /*
  206. * `reachable` meant fall through because statements preceded by
  207. * `break`, `return`, or `throw` are unreachable.
  208. * And allows empty cases and the last case.
  209. */
  210. const isSwitchExitReachable = isAnySegmentReachable(
  211. currentCodePathSegments,
  212. );
  213. const isFallthrough =
  214. isSwitchExitReachable &&
  215. (node.consequent.length > 0 ||
  216. (!allowEmptyCase &&
  217. hasBlankLinesBetween(node, nextToken))) &&
  218. node.parent.cases.at(-1) !== node;
  219. previousCase = {
  220. node,
  221. isSwitchExitReachable,
  222. isFallthrough,
  223. };
  224. },
  225. };
  226. },
  227. };