import {types, operator} from 'putout'; const { replaceWith, remove, createTypeChecker, } = operator; const isEmptyBlock = createTypeChecker([ ['-: node.innerComments -> +'], ['-: node.body.length', '>', 0], ['-: parentPath -> ArrowFunctionExpression'], ['-: parentPath -> FunctionExpression'], ['-: parentPath -> FunctionDeclaration'], ['-: parentPath -> ObjectMethod'], ['-: parentPath -> ClassMethod'], ['-: parentPath -> CatchClause'], ['+: -> +'], ]); const { isIfStatement, isTryStatement, unaryExpression, isProgram, } = types; export const report = () => 'Avoid useless empty blocks'; export const fix = (path) => { const alternatePath = path.get('alternate'); const testPath = path.get('test'); const {alternate} = path.node; if (!path.isIfStatement()) return remove(path); if (!alternate) { if (!testPath.isBinaryExpression() && !testPath.isLiteral()) return replaceWith(path, testPath); return remove(path); } if (alternatePath.isBlock() && !alternate.body.length) { path.node.alternate = null; return; } if (alternatePath.isIfStatement()) return replaceWith(path, alternatePath); path.node.consequent = path.node.alternate; path.node.alternate = null; const {operator} = testPath.node; if (operator && operator !== '=' && /[!<=>]/.test(testPath.node.operator)) { testPath.node.operator = reverse(testPath.node.operator); return; } replaceWith(testPath, unaryExpression('!', testPath.node)); }; export const traverse = ({push}) => ({ BlockStatement(path) { if (!isEmptyBlock(path)) return; const {node, parentPath} = path; const parentNode = parentPath.node; if (isTryStatement(parentNode)) return push(parentPath); if (blockIsIndependentBody(node, parentNode)) return push(path); if (blockIsConsequent(node, parentNode)) return push(parentPath); if (blockIsAlternate(node, parentNode)) return push(parentPath); if (isProgram(parentPath)) return push(path); push(parentPath); }, }); function blockIsIndependentBody(node, parentNode) { const {body} = parentNode; if (!body) return false; return body[0] === node; } function blockIsConsequent(node, parentNode) { if (!isIfStatement(parentNode)) return; return parentNode.consequent === node; } function blockIsAlternate(node, parentNode) { const {alternate} = parentNode; if (!isIfStatement(parentNode)) return; return alternate === node; } function reverse(a) { if (a === '>') return '<='; if (a === '<') return '>='; if (a === '<=') return '>'; if (a === '>=') return '<'; if (a === '!') return ''; if (a === '!=') return '=='; if (a === '!==') return '==='; return `!${a}`.replace('=', ''); }