UNPKG

2.56 kBJavaScriptView Raw
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
8var FALLTHROUGH_COMMENT = /falls\sthrough/;
9
10//------------------------------------------------------------------------------
11// Rule Definition
12//------------------------------------------------------------------------------
13
14module.exports = function(context) {
15
16 var switches = [];
17
18 return {
19
20 "SwitchCase": function(node) {
21
22 var consequent = node.consequent,
23 switchData = switches[switches.length - 1],
24 i,
25 comments,
26 comment;
27
28 // checking on previous case
29 if (!switchData.lastCaseClosed) {
30
31 // a fall through comment will be a leading comment of the following case
32 comments = context.getComments(node).leading;
33 comment = comments[comments.length - 1];
34
35 // check for comment
36 if (!comment || !FALLTHROUGH_COMMENT.test(comment.value)) {
37 context.report(switchData.lastCase,
38 "Expected a \"break\" statement before \"{{code}}\".",
39 { code: node.test ? "case" : "default" });
40 }
41 }
42
43 // now dealing with the current case
44 switchData.lastCaseClosed = false;
45 switchData.lastCase = node;
46
47 // try to verify using statements - go backwards as a fast path for the search
48 if (consequent.length) {
49 for (i = consequent.length - 1; i >= 0; i--) {
50 if (/(?:Break|Return|Throw)Statement/.test(consequent[i].type)) {
51 switchData.lastCaseClosed = true;
52 break;
53 }
54 }
55 } else {
56 // the case statement has no statements, so it must logically fall through
57 switchData.lastCaseClosed = true;
58 }
59
60 /*
61 * Any warnings are triggered when the next SwitchCase occurs.
62 * There is no need to warn on the last SwitchCase, since it can't
63 * fall through to anything.
64 */
65 },
66
67 "SwitchStatement": function(node) {
68 switches.push({
69 node: node,
70 lastCaseClosed: true,
71 lastCase: null
72 });
73 },
74
75 "SwitchStatement:exit": function() {
76 switches.pop();
77 }
78 };
79
80};