123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136 |
- "use strict";
- module.exports = {
- meta: {
- type: "suggestion",
- docs: {
- description: "Disallow unnecessary nested blocks",
- recommended: false,
- url: "https://eslint.org/docs/latest/rules/no-lone-blocks"
- },
- schema: [],
- messages: {
- redundantBlock: "Block is redundant.",
- redundantNestedBlock: "Nested block is redundant."
- }
- },
- create(context) {
-
- const loneBlocks = [];
- let ruleDef;
- const sourceCode = context.sourceCode;
-
- function report(node) {
- const messageId = node.parent.type === "BlockStatement" || node.parent.type === "StaticBlock"
- ? "redundantNestedBlock"
- : "redundantBlock";
- context.report({
- node,
- messageId
- });
- }
-
- function isLoneBlock(node) {
- return node.parent.type === "BlockStatement" ||
- node.parent.type === "StaticBlock" ||
- node.parent.type === "Program" ||
-
- node.parent.type === "SwitchCase" && !(node.parent.consequent[0] === node && node.parent.consequent.length === 1);
- }
-
- function markLoneBlock(node) {
- if (loneBlocks.length === 0) {
- return;
- }
- const block = node.parent;
- if (loneBlocks.at(-1) === block) {
- loneBlocks.pop();
- }
- }
-
- ruleDef = {
- BlockStatement(node) {
- if (isLoneBlock(node)) {
- report(node);
- }
- }
- };
-
- if (context.languageOptions.ecmaVersion >= 2015) {
- ruleDef = {
- BlockStatement(node) {
- if (isLoneBlock(node)) {
- loneBlocks.push(node);
- }
- },
- "BlockStatement:exit"(node) {
- if (loneBlocks.length > 0 && loneBlocks.at(-1) === node) {
- loneBlocks.pop();
- report(node);
- } else if (
- (
- node.parent.type === "BlockStatement" ||
- node.parent.type === "StaticBlock"
- ) &&
- node.parent.body.length === 1
- ) {
- report(node);
- }
- }
- };
- ruleDef.VariableDeclaration = function(node) {
- if (node.kind !== "var") {
- markLoneBlock(node);
- }
- };
- ruleDef.FunctionDeclaration = function(node) {
- if (sourceCode.getScope(node).isStrict) {
- markLoneBlock(node);
- }
- };
- ruleDef.ClassDeclaration = markLoneBlock;
- }
- return ruleDef;
- }
- };
|