]>
git.proxmox.com Git - pve-eslint.git/blob - eslint/lib/rules/no-lone-blocks.js
2 * @fileoverview Rule to flag blocks with no reason to exist
3 * @author Brandon Mills
8 //------------------------------------------------------------------------------
10 //------------------------------------------------------------------------------
12 /** @type {import('../shared/types').Rule} */
18 description
: "Disallow unnecessary nested blocks",
20 url
: "https://eslint.org/docs/latest/rules/no-lone-blocks"
26 redundantBlock
: "Block is redundant.",
27 redundantNestedBlock
: "Nested block is redundant."
33 // A stack of lone blocks to be checked for block-level bindings
34 const loneBlocks
= [];
36 const sourceCode
= context
.sourceCode
;
39 * Reports a node as invalid.
40 * @param {ASTNode} node The node to be reported.
43 function report(node
) {
44 const messageId
= node
.parent
.type
=== "BlockStatement" || node
.parent
.type
=== "StaticBlock"
45 ? "redundantNestedBlock"
55 * Checks for any occurrence of a BlockStatement in a place where lists of statements can appear
56 * @param {ASTNode} node The node to check
57 * @returns {boolean} True if the node is a lone block.
59 function isLoneBlock(node
) {
60 return node
.parent
.type
=== "BlockStatement" ||
61 node
.parent
.type
=== "StaticBlock" ||
62 node
.parent
.type
=== "Program" ||
64 // Don't report blocks in switch cases if the block is the only statement of the case.
65 node
.parent
.type
=== "SwitchCase" && !(node
.parent
.consequent
[0] === node
&& node
.parent
.consequent
.length
=== 1);
69 * Checks the enclosing block of the current node for block-level bindings,
70 * and "marks it" as valid if any.
71 * @param {ASTNode} node The current node to check.
74 function markLoneBlock(node
) {
75 if (loneBlocks
.length
=== 0) {
79 const block
= node
.parent
;
81 if (loneBlocks
[loneBlocks
.length
- 1] === block
) {
86 // Default rule definition: report all lone blocks
88 BlockStatement(node
) {
89 if (isLoneBlock(node
)) {
95 // ES6: report blocks without block-level bindings, or that's only child of another block
96 if (context
.languageOptions
.ecmaVersion
>= 2015) {
98 BlockStatement(node
) {
99 if (isLoneBlock(node
)) {
100 loneBlocks
.push(node
);
103 "BlockStatement:exit"(node
) {
104 if (loneBlocks
.length
> 0 && loneBlocks
[loneBlocks
.length
- 1] === node
) {
109 node
.parent
.type
=== "BlockStatement" ||
110 node
.parent
.type
=== "StaticBlock"
112 node
.parent
.body
.length
=== 1
119 ruleDef
.VariableDeclaration = function(node
) {
120 if (node
.kind
=== "let" || node
.kind
=== "const") {
125 ruleDef
.FunctionDeclaration = function(node
) {
126 if (sourceCode
.getScope(node
).isStrict
) {
131 ruleDef
.ClassDeclaration
= markLoneBlock
;