UNPKG

eslint-plugin-unicorn

Version:
436 lines (373 loc) • 12.9 kB
import {findVariable, isCommentToken} from '@eslint-community/eslint-utils'; import reservedIdentifiers from 'reserved-identifiers'; import {removeStatement} from './fix/index.js'; import {isDirectEvalCall} from './ast/index.js'; import { containsNode, getIndentUnit, getLineIndent, getParenthesizedRange, getParenthesizedText, getReferencesInside, getVisitorChildNodes, hasMultilineToken, reindentText, } from './utils/index.js'; const MESSAGE_ID = 'prefer-smaller-scope'; const messages = { [MESSAGE_ID]: 'Move `{{name}}` into the block where it is used.', }; const reserved = reservedIdentifiers(); const scopeBoundaryTypes = new Set([ 'ArrowFunctionExpression', 'ClassDeclaration', 'ClassExpression', 'FunctionDeclaration', 'FunctionExpression', 'StaticBlock', 'WithStatement', ]); const isDeclarationCandidate = node => Boolean(node.parent) && (node.parent.type === 'Program' || node.parent.type === 'BlockStatement') && (node.kind === 'let' || node.kind === 'const') && !node.declare && node.declarations.length === 1 && node.declarations[0].id.type === 'Identifier'; const isExported = (declaration, name) => (declaration.parent.type === 'Program' || declaration.parent.type === 'SvelteScriptElement') && declaration.parent.body.some(statement => statement.type === 'ExportNamedDeclaration' && !statement.source && statement.specifiers.some(specifier => specifier.local.name === name), ); function isDescendantWithoutScopeBoundary(node, ancestor) { let current = node.parent; while (current && current !== ancestor) { if (scopeBoundaryTypes.has(current.type)) { return false; } current = current.parent; } return current === ancestor; } function hasDynamicScope(node, visitorKeys) { if (node.type === 'WithStatement' || isDirectEvalCall(node)) { return true; } return getVisitorChildNodes(node, visitorKeys).some(child => hasDynamicScope(child, visitorKeys)); } function getAssignment(writeReference) { const {identifier} = writeReference; const assignmentExpression = identifier.parent; if ( assignmentExpression.type !== 'AssignmentExpression' || assignmentExpression.operator !== '=' || assignmentExpression.left !== identifier || assignmentExpression.parent.type !== 'ExpressionStatement' ) { return; } const assignmentStatement = assignmentExpression.parent; const block = assignmentStatement.parent; if (block.type !== 'BlockStatement') { return; } return { assignmentExpression, assignmentStatement, block, }; } function hasCommentNextTo(sourceCode, node, direction) { const token = direction === 'before' ? sourceCode.getTokenBefore(node, {includeComments: true}) : sourceCode.getTokenAfter(node, {includeComments: true}); return Boolean(token && isCommentToken(token)); } function isParenthesizedAssignmentExpression(sourceCode, assignmentExpression) { const tokenBefore = sourceCode.getTokenBefore(assignmentExpression); const tokenAfter = sourceCode.getTokenAfter(assignmentExpression); return tokenBefore?.value === '(' && tokenAfter?.value === ')'; } const hasCommentsThatBlockUninitializedDeclarationFix = (sourceCode, declaration, assignmentStatement) => sourceCode.getCommentsInside(declaration).length > 0 || sourceCode.getCommentsInside(assignmentStatement).length > 0 || hasCommentNextTo(sourceCode, declaration, 'before') || hasCommentNextTo(sourceCode, declaration, 'after') || hasCommentNextTo(sourceCode, assignmentStatement, 'before') || hasCommentNextTo(sourceCode, assignmentStatement, 'after'); const hasCommentsThatBlockDeclarationMove = (sourceCode, declaration, firstStatement) => sourceCode.getCommentsInside(declaration).length > 0 || hasCommentNextTo(sourceCode, declaration, 'before') || hasCommentNextTo(sourceCode, declaration, 'after') || hasCommentNextTo(sourceCode, firstStatement, 'before'); function getUninitializedDeclarationFix({ sourceCode, declaration, assignmentExpression, assignmentStatement, name, }) { return function * (fixer) { yield removeStatement(declaration, {sourceCode}, fixer); const declarationText = `const ${name} = `; // The parentheses are not part of the node range, they have to be kept explicitly const {right} = assignmentExpression; if (isParenthesizedAssignmentExpression(sourceCode, assignmentExpression)) { yield fixer.replaceText(assignmentStatement, `${declarationText}${getParenthesizedText(right, {sourceCode})};`); return; } const [assignmentStart] = sourceCode.getRange(assignmentExpression); const [rightStart] = getParenthesizedRange(right, {sourceCode}); yield fixer.replaceTextRange([assignmentStart, rightStart], declarationText); }; } function getInitializedDeclarationProblem(declaration, sourceCode, references) { const [declarator] = declaration.declarations; const {init} = declarator; if ( !(init.type === 'Literal' && !init.regex) && !(init.type === 'TemplateLiteral' && init.expressions.length === 0) ) { return; } const statements = declaration.parent.body; const nextStatement = statements[statements.indexOf(declaration) + 1]; if (nextStatement?.type !== 'IfStatement') { return; } if (references.length === 0) { return; } const block = [nextStatement.consequent, nextStatement.alternate].find(branch => branch?.type === 'BlockStatement' && references.every(reference => isDescendantWithoutScopeBoundary(reference.identifier, branch)), ); if (!block || hasDynamicScope(declaration.parent, sourceCode.visitorKeys)) { return; } const problem = { node: declarator.id, messageId: MESSAGE_ID, data: {name: declarator.id.name}, }; const [firstStatement] = block.body; if ( !declarator.id.typeAnnotation && !hasCommentsThatBlockDeclarationMove(sourceCode, declaration, firstStatement) ) { problem.fix = function * (fixer) { const openingBrace = sourceCode.getFirstToken(block); const [, openingBraceEnd] = sourceCode.getRange(openingBrace); const [firstStatementStart] = sourceCode.getRange(firstStatement); const separator = sourceCode.text.slice(openingBraceEnd, firstStatementStart) || ' '; const declarationText = sourceCode.getText(declaration); const semicolon = declarationText.endsWith(';') ? '' : ';'; const [declarationStart] = sourceCode.getRange(declaration); const [nextStatementStart] = sourceCode.getRange(nextStatement); yield fixer.removeRange([declarationStart, nextStatementStart]); yield fixer.insertTextBefore(firstStatement, `${declarationText}${semicolon}${separator}`); }; } return problem; } function getProblem(node, sourceCode) { if (!isDeclarationCandidate(node)) { return; } const [declarator] = node.declarations; const [variable] = sourceCode.getDeclaredVariables(declarator); if ( variable.eslintUsed || isExported(node, declarator.id.name) ) { return; } const references = variable.references.filter(reference => !reference.init); if (declarator.init) { return getInitializedDeclarationProblem(node, sourceCode, references); } if (node.kind !== 'let') { return; } const writeReferences = references.filter(reference => reference.isWrite()); if ( writeReferences.length !== 1 || references.every(reference => !reference.isRead()) ) { return; } const assignment = getAssignment(writeReferences[0]); if (!assignment) { return; } const { assignmentExpression, assignmentStatement, block, } = assignment; const [, declarationEnd] = sourceCode.getRange(node); const [assignmentStatementStart, assignmentStatementEnd] = sourceCode.getRange(assignmentStatement); if ( !isDescendantWithoutScopeBoundary(block, node.parent) || hasDynamicScope(node.parent, sourceCode.visitorKeys) ) { return; } if (assignmentStatementStart < declarationEnd) { return; } if (references.some(reference => !isDescendantWithoutScopeBoundary(reference.identifier, block))) { return; } if (references.some(reference => reference.isRead() && sourceCode.getRange(reference.identifier)[0] < assignmentStatementEnd)) { return; } const problem = { node: declarator.id, messageId: MESSAGE_ID, data: {name: declarator.id.name}, }; if ( !declarator.id.typeAnnotation && !( isParenthesizedAssignmentExpression(sourceCode, assignmentExpression) && assignmentExpression.right.type === 'SequenceExpression' ) && !hasCommentsThatBlockUninitializedDeclarationFix(sourceCode, node, assignmentStatement) ) { problem.fix = getUninitializedDeclarationFix({ sourceCode, declaration: node, assignmentExpression, assignmentStatement, name: declarator.id.name, }); } return problem; } const isInside = (node, ancestor, sourceCode) => { const [start, end] = sourceCode.getRange(node); const [ancestorStart, ancestorEnd] = sourceCode.getRange(ancestor); return start >= ancestorStart && end <= ancestorEnd; }; function getTypeAliasBlock(declaration, references, sourceCode) { if (references.length === 0) { return; } let ancestor = references[0].identifier.parent; while (ancestor && ancestor !== declaration.parent) { if ( ancestor.type === 'BlockStatement' && references.every(reference => isInside(reference.identifier, ancestor, sourceCode)) ) { return ancestor; } ancestor = ancestor.parent; } } function getTypeAliasProblem(declaration, context) { const {sourceCode} = context; if ( !['Program', 'BlockStatement', 'SvelteScriptElement'].includes(declaration.parent.type) || declaration.declare || declaration.typeParameters?.params.some(parameter => parameter.in || parameter.out) || isExported(declaration, declaration.id.name) ) { return; } const [variable] = sourceCode.getDeclaredVariables(declaration); if (variable.eslintUsed) { return; } const references = variable.references.filter(reference => reference.isTypeReference && !isInside(reference.identifier, declaration, sourceCode)); const block = getTypeAliasBlock(declaration, references, sourceCode); if (!block) { return; } const problem = { node: declaration.id, messageId: MESSAGE_ID, data: {name: declaration.id.name}, }; const firstStatement = block.body.find(statement => !statement.directive); const destinationScope = sourceCode.getScope(block); const hasUnsafeDependency = getReferencesInside(declaration, context).some(({identifier, resolved, isValueReference}) => isValueReference || ( !(resolved && isInside(resolved.scope.block, declaration, sourceCode)) && findVariable(destinationScope, identifier.name) !== resolved ), ); if ( variable.isValueVariable || hasUnsafeDependency || variable.references.some(reference => isInside(reference.identifier, declaration, sourceCode)) || findVariable(destinationScope, declaration.id.name) !== variable || containsNode(declaration, context, node => node.type === 'TSTypeQuery' || node.type === 'TSThisType' || (node.type === 'Identifier' && reserved.has(node.name)), ) || hasMultilineToken(declaration, context) || hasCommentsThatBlockDeclarationMove(sourceCode, declaration, firstStatement) ) { return problem; } problem.fix = function * (fixer) { const previousToken = sourceCode.getTokenBefore(firstStatement); const [, previousTokenEnd] = sourceCode.getRange(previousToken); const [firstStatementStart] = sourceCode.getRange(firstStatement); const separator = sourceCode.text.slice(previousTokenEnd, firstStatementStart) || ' '; const targetIndent = sourceCode.getLoc(previousToken).end.line === sourceCode.getLoc(firstStatement).start.line ? getLineIndent(block, context) + getIndentUnit(context) : getLineIndent(firstStatement, context); const declarationText = reindentText(sourceCode.getText(declaration), getLineIndent(declaration, context), targetIndent); const semicolon = declarationText.endsWith(';') ? '' : ';'; yield removeStatement(declaration, context, fixer); yield fixer.insertTextBefore(firstStatement, `${declarationText}${semicolon}${separator}`); }; return problem; } /** @param {import('eslint').Rule.RuleContext} context */ const create = context => { const {sourceCode} = context; const {checkTypeAliases} = context.options[0]; context.on('VariableDeclaration', node => getProblem(node, sourceCode)); if (checkTypeAliases) { context.on('TSTypeAliasDeclaration', node => getTypeAliasProblem(node, context)); } }; /** @type {import('eslint').Rule.RuleModule} */ const config = { create, meta: { type: 'suggestion', docs: { description: 'Prefer declaring variables and type aliases in the smallest possible scope.', recommended: true, }, fixable: 'code', schema: [{ type: 'object', properties: { checkTypeAliases: { type: 'boolean', description: 'Check TypeScript type aliases.', }, }, additionalProperties: false, }], defaultOptions: [{checkTypeAliases: true}], messages, languages: [ 'js/js', ], }, }; export default config;