123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120 |
- "use strict";
- module.exports = {
- meta: {
- type: "suggestion",
- docs: {
- description: "disallow unnecessary nested blocks",
- category: "Best Practices",
- recommended: false,
- url: "https://eslint.org/docs/rules/no-lone-blocks"
- },
- schema: []
- },
- create(context) {
-
- const loneBlocks = [];
- let ruleDef;
-
- function report(node) {
- const message = node.parent.type === "BlockStatement" ? "Nested block is redundant." : "Block is redundant.";
- context.report({ node, message });
- }
-
- function isLoneBlock(node) {
- return node.parent.type === "BlockStatement" ||
- node.parent.type === "Program" ||
-
- node.parent.type === "SwitchCase" && !(node.parent.consequent[0] === node && node.parent.consequent.length === 1);
- }
-
- function markLoneBlock() {
- if (loneBlocks.length === 0) {
- return;
- }
- const block = context.getAncestors().pop();
- if (loneBlocks[loneBlocks.length - 1] === block) {
- loneBlocks.pop();
- }
- }
-
- ruleDef = {
- BlockStatement(node) {
- if (isLoneBlock(node)) {
- report(node);
- }
- }
- };
-
- if (context.parserOptions.ecmaVersion >= 6) {
- ruleDef = {
- BlockStatement(node) {
- if (isLoneBlock(node)) {
- loneBlocks.push(node);
- }
- },
- "BlockStatement:exit"(node) {
- if (loneBlocks.length > 0 && loneBlocks[loneBlocks.length - 1] === node) {
- loneBlocks.pop();
- report(node);
- } else if (
- node.parent.type === "BlockStatement" &&
- node.parent.body.length === 1
- ) {
- report(node);
- }
- }
- };
- ruleDef.VariableDeclaration = function(node) {
- if (node.kind === "let" || node.kind === "const") {
- markLoneBlock();
- }
- };
- ruleDef.FunctionDeclaration = function() {
- if (context.getScope().isStrict) {
- markLoneBlock();
- }
- };
- ruleDef.ClassDeclaration = markLoneBlock;
- }
- return ruleDef;
- }
- };
|