1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 | "use strict";
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 | const SENTINEL_NODE_TYPE_RETURN_THROW = /^(?:Program|(?:Function|Class)(?:Declaration|Expression)|ArrowFunctionExpression)$/u;
|
13 | const SENTINEL_NODE_TYPE_BREAK = /^(?:Program|(?:Function|Class)(?:Declaration|Expression)|ArrowFunctionExpression|DoWhileStatement|WhileStatement|ForOfStatement|ForInStatement|ForStatement|SwitchStatement)$/u;
|
14 | const SENTINEL_NODE_TYPE_CONTINUE = /^(?:Program|(?:Function|Class)(?:Declaration|Expression)|ArrowFunctionExpression|DoWhileStatement|WhileStatement|ForOfStatement|ForInStatement|ForStatement)$/u;
|
15 |
|
16 |
|
17 |
|
18 |
|
19 |
|
20 |
|
21 | module.exports = {
|
22 | meta: {
|
23 | type: "problem",
|
24 |
|
25 | docs: {
|
26 | description: "disallow control flow statements in `finally` blocks",
|
27 | category: "Possible Errors",
|
28 | recommended: true,
|
29 | url: "https://eslint.org/docs/rules/no-unsafe-finally"
|
30 | },
|
31 |
|
32 | schema: []
|
33 | },
|
34 | create(context) {
|
35 |
|
36 | |
37 |
|
38 |
|
39 |
|
40 |
|
41 |
|
42 | function isFinallyBlock(node) {
|
43 | return node.parent.type === "TryStatement" && node.parent.finalizer === node;
|
44 | }
|
45 |
|
46 | |
47 |
|
48 |
|
49 |
|
50 |
|
51 |
|
52 |
|
53 | function isInFinallyBlock(node, label) {
|
54 | let labelInside = false;
|
55 | let sentinelNodeType;
|
56 |
|
57 | if (node.type === "BreakStatement" && !node.label) {
|
58 | sentinelNodeType = SENTINEL_NODE_TYPE_BREAK;
|
59 | } else if (node.type === "ContinueStatement") {
|
60 | sentinelNodeType = SENTINEL_NODE_TYPE_CONTINUE;
|
61 | } else {
|
62 | sentinelNodeType = SENTINEL_NODE_TYPE_RETURN_THROW;
|
63 | }
|
64 |
|
65 | for (
|
66 | let currentNode = node;
|
67 | currentNode && !sentinelNodeType.test(currentNode.type);
|
68 | currentNode = currentNode.parent
|
69 | ) {
|
70 | if (currentNode.parent.label && label && (currentNode.parent.label.name === label.name)) {
|
71 | labelInside = true;
|
72 | }
|
73 | if (isFinallyBlock(currentNode)) {
|
74 | if (label && labelInside) {
|
75 | return false;
|
76 | }
|
77 | return true;
|
78 | }
|
79 | }
|
80 | return false;
|
81 | }
|
82 |
|
83 | |
84 |
|
85 |
|
86 |
|
87 |
|
88 |
|
89 | function check(node) {
|
90 | if (isInFinallyBlock(node, node.label)) {
|
91 | context.report({
|
92 | message: "Unsafe usage of {{nodeType}}.",
|
93 | data: {
|
94 | nodeType: node.type
|
95 | },
|
96 | node,
|
97 | line: node.loc.line,
|
98 | column: node.loc.column
|
99 | });
|
100 | }
|
101 | }
|
102 |
|
103 | return {
|
104 | ReturnStatement: check,
|
105 | ThrowStatement: check,
|
106 | BreakStatement: check,
|
107 | ContinueStatement: check
|
108 | };
|
109 | }
|
110 | };
|