]>
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/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
= [];
38 * Reports a node as invalid.
39 * @param {ASTNode} node The node to be reported.
42 function report(node
) {
43 const messageId
= node
.parent
.type
=== "BlockStatement" || node
.parent
.type
=== "StaticBlock"
44 ? "redundantNestedBlock"
54 * Checks for any occurrence of a BlockStatement in a place where lists of statements can appear
55 * @param {ASTNode} node The node to check
56 * @returns {boolean} True if the node is a lone block.
58 function isLoneBlock(node
) {
59 return node
.parent
.type
=== "BlockStatement" ||
60 node
.parent
.type
=== "StaticBlock" ||
61 node
.parent
.type
=== "Program" ||
63 // Don't report blocks in switch cases if the block is the only statement of the case.
64 node
.parent
.type
=== "SwitchCase" && !(node
.parent
.consequent
[0] === node
&& node
.parent
.consequent
.length
=== 1);
68 * Checks the enclosing block of the current node for block-level bindings,
69 * and "marks it" as valid if any.
72 function markLoneBlock() {
73 if (loneBlocks
.length
=== 0) {
77 const block
= context
.getAncestors().pop();
79 if (loneBlocks
[loneBlocks
.length
- 1] === block
) {
84 // Default rule definition: report all lone blocks
86 BlockStatement(node
) {
87 if (isLoneBlock(node
)) {
93 // ES6: report blocks without block-level bindings, or that's only child of another block
94 if (context
.languageOptions
.ecmaVersion
>= 2015) {
96 BlockStatement(node
) {
97 if (isLoneBlock(node
)) {
98 loneBlocks
.push(node
);
101 "BlockStatement:exit"(node
) {
102 if (loneBlocks
.length
> 0 && loneBlocks
[loneBlocks
.length
- 1] === node
) {
107 node
.parent
.type
=== "BlockStatement" ||
108 node
.parent
.type
=== "StaticBlock"
110 node
.parent
.body
.length
=== 1
117 ruleDef
.VariableDeclaration = function(node
) {
118 if (node
.kind
=== "let" || node
.kind
=== "const") {
123 ruleDef
.FunctionDeclaration = function() {
124 if (context
.getScope().isStrict
) {
129 ruleDef
.ClassDeclaration
= markLoneBlock
;