|
1 | 1 | 'use strict'; |
2 | 2 |
|
3 | 3 | const {types, operator} = require('putout'); |
| 4 | +const {remove} = operator; |
| 5 | + |
4 | 6 | const { |
5 | 7 | isExpressionStatement, |
6 | 8 | isFunctionDeclaration, |
7 | 9 | isBlockStatement, |
8 | 10 | } = types; |
9 | 11 |
|
10 | | -const {remove} = operator; |
| 12 | +const not = (fn) => (...a) => !fn(...a); |
11 | 13 |
|
12 | 14 | module.exports.report = () => `Unreachable code`; |
13 | 15 |
|
14 | | -module.exports.fix = ({siblings}) => { |
15 | | - for (const sibling of siblings) { |
16 | | - remove(sibling); |
17 | | - } |
18 | | -}; |
19 | | - |
20 | | -const processBlock = (push, path, leaf) => { |
21 | | - const siblings = path.getAllNextSiblings(); |
22 | | - |
23 | | - if (!siblings.length) |
24 | | - return; |
25 | | - |
26 | | - if (leaf) { |
27 | | - const [first] = siblings; |
28 | | - |
29 | | - if (!path.node.argument && (isBlockStatement(first) || isExpressionStatement(first))) |
30 | | - return false; |
31 | | - } |
32 | | - |
33 | | - for (const sibling of siblings) { |
34 | | - if (isFunctionDeclaration(sibling)) |
35 | | - continue; |
36 | | - |
37 | | - push({ |
38 | | - path: sibling, |
39 | | - siblings: [sibling], |
40 | | - }); |
41 | | - } |
| 16 | +module.exports.fix = (path) => { |
| 17 | + remove(path); |
42 | 18 | }; |
43 | 19 |
|
44 | 20 | module.exports.traverse = ({push}) => ({ |
45 | 21 | 'ReturnStatement|ThrowStatement'(path) { |
46 | | - let leaf = true; |
47 | | - |
48 | 22 | while (path.parentPath?.isBlockStatement()) { |
49 | | - processBlock(push, path, leaf); |
| 23 | + const siblings = path.getAllNextSiblings(); |
| 24 | + const {argument} = path.node; |
| 25 | + |
50 | 26 | path = path.parentPath; |
51 | | - leaf = false; |
| 27 | + |
| 28 | + if (checkFirstSibling({argument, siblings})) |
| 29 | + continue; |
| 30 | + |
| 31 | + processSiblings({ |
| 32 | + push, |
| 33 | + siblings, |
| 34 | + }); |
52 | 35 | } |
53 | 36 | }, |
54 | 37 | }); |
| 38 | + |
| 39 | +const processSiblings = ({push, siblings}) => { |
| 40 | + if (!siblings.length) |
| 41 | + return; |
| 42 | + |
| 43 | + siblings |
| 44 | + .filter(not(isFunctionDeclaration)) |
| 45 | + .map(push); |
| 46 | +}; |
| 47 | + |
| 48 | +function checkFirstSibling({argument, siblings}) { |
| 49 | + if (argument) |
| 50 | + return false; |
| 51 | + |
| 52 | + const [first] = siblings; |
| 53 | + |
| 54 | + if (isBlockStatement(first)) |
| 55 | + return true; |
| 56 | + |
| 57 | + return isExpressionStatement(first); |
| 58 | +} |
0 commit comments