eslint-plugin-unicorn
Version:
More than 300 powerful ESLint rules
256 lines (220 loc) • 8.44 kB
JavaScript
import {isCommentToken} from '@eslint-community/eslint-utils';
import {getStaticStringValue, isNullLiteral} from './ast/index.js';
import {
getLogicalExpressionChildText,
getOutermostTypeScriptExpression,
getParenthesizedRange,
isBooleanContext,
isTypeScriptExpressionWrapper,
unwrapTypeScriptExpression,
wouldRemoveComments,
} from './utils/index.js';
const MESSAGE_ID = 'prefer-simple-condition-first';
const MESSAGE_ID_UNSAFE = 'prefer-simple-condition-first/unsafe';
const messages = {
[MESSAGE_ID]: 'Prefer this simple condition first in the `{{operator}}` expression.',
[MESSAGE_ID_UNSAFE]: 'Consider moving this simple condition first after verifying short-circuit behavior.',
};
function isTypeofIdentifier(node) {
node = unwrapTypeScriptExpression(node);
return node.type === 'UnaryExpression'
&& node.operator === 'typeof'
&& unwrapTypeScriptExpression(node.argument).type === 'Identifier';
}
function isIdentifierOrTypeofIdentifier(node) {
node = unwrapTypeScriptExpression(node);
return node.type === 'Identifier' || isTypeofIdentifier(node);
}
/**
Check if a node can be an operand in a simple strict comparison.
*/
function isSimpleOperand(node) {
node = unwrapTypeScriptExpression(node);
if (isIdentifierOrTypeofIdentifier(node) || node.type === 'Literal' || getStaticStringValue(node) !== undefined) {
return true;
}
if (
node.type !== 'UnaryExpression'
|| (node.operator !== '-' && node.operator !== '+')
) {
return false;
}
// Signed number literals and negative BigInt literals: `-1`, `+0`, `-1n`
const argument = unwrapTypeScriptExpression(node.argument);
return argument.type === 'Literal'
&& (
typeof argument.value === 'number'
|| (node.operator === '-' && typeof argument.value === 'bigint')
);
}
function isSimple(node) {
node = unwrapTypeScriptExpression(node);
if (node.type === 'Identifier') {
return true;
}
if (
node.type === 'UnaryExpression'
&& node.operator === '!'
) {
return isSimple(node.argument);
}
if (node.type === 'BinaryExpression') {
const left = unwrapTypeScriptExpression(node.left);
const right = unwrapTypeScriptExpression(node.right);
if (node.operator === '==' || node.operator === '!=') {
return (left.type === 'Identifier' && isNullLiteral(right))
|| (isNullLiteral(left) && right.type === 'Identifier')
|| (isTypeofIdentifier(left) && (getStaticStringValue(right) !== undefined || isTypeofIdentifier(right)))
|| (getStaticStringValue(left) !== undefined && isTypeofIdentifier(right));
}
return isSimpleOperand(left) && isSimpleOperand(right)
&& (node.operator === '===' || node.operator === '!==')
&& (isIdentifierOrTypeofIdentifier(left) || isIdentifierOrTypeofIdentifier(right));
}
return false;
}
function getLogicalOperands(node, operator, operands = []) {
const unwrappedNode = unwrapTypeScriptExpression(node);
if (unwrappedNode.type !== 'LogicalExpression' || unwrappedNode.operator !== operator) {
operands.push(node);
return operands;
}
getLogicalOperands(unwrappedNode.left, operator, operands);
getLogicalOperands(unwrappedNode.right, operator, operands);
return operands;
}
function isTypeofGuardForIdentifier(node, identifierName, logicalOperator) {
node = unwrapTypeScriptExpression(node);
const guardOperators = logicalOperator === '&&' ? ['!==', '!='] : ['===', '=='];
if (node.type !== 'BinaryExpression' || !guardOperators.includes(node.operator)) {
return false;
}
const left = unwrapTypeScriptExpression(node.left);
const right = unwrapTypeScriptExpression(node.right);
const typeofExpression = isTypeofIdentifier(left) ? left : right;
const undefinedLiteral = typeofExpression === left ? right : left;
return isTypeofIdentifier(typeofExpression)
&& getStaticStringValue(undefinedLiteral) === 'undefined'
&& unwrapTypeScriptExpression(typeofExpression.argument).name === identifierName;
}
function hasEarlierTypeofGuard(operands, index, logicalOperator) {
const identifier = unwrapTypeScriptExpression(operands[index]);
return identifier.type === 'Identifier'
&& operands.slice(0, index).some(operand => isTypeofGuardForIdentifier(operand, identifier.name, logicalOperator));
}
function isSafeConditionalExpression(node) {
const unwrappedNode = unwrapTypeScriptExpression(node);
return unwrappedNode.type === 'ConditionalExpression'
&& [unwrappedNode.test, unwrappedNode.consequent, unwrappedNode.alternate].every(child =>
isSimple(child) || isSimpleOperand(child) || isSafeConditionalExpression(child),
);
}
function isSafeToMove(node) {
return isSimple(node) || isSafeConditionalExpression(node);
}
function hasSameOperatorLogicalParent(node) {
const {parent} = getOutermostTypeScriptExpression(node);
return parent?.type === 'LogicalExpression' && parent.operator === node.operator;
}
function hasTypeScriptWrappedLogicalExpression(node, operator) {
if (isTypeScriptExpressionWrapper(node)) {
const unwrappedNode = unwrapTypeScriptExpression(node);
return unwrappedNode.type === 'LogicalExpression' && unwrappedNode.operator === operator;
}
return node.type === 'LogicalExpression'
&& node.operator === operator
&& (hasTypeScriptWrappedLogicalExpression(node.left, operator) || hasTypeScriptWrappedLogicalExpression(node.right, operator));
}
function hasCommentsThatPreventFix(node, operands, context) {
const {sourceCode} = context;
if (wouldRemoveComments(context, node, operands.map(operand => getParenthesizedRange(operand, context)))) {
return true;
}
const [firstOperand] = operands;
const lastOperand = operands.at(-1);
const [start] = getParenthesizedRange(firstOperand, context);
const [, end] = getParenthesizedRange(lastOperand, context);
const range = {range: [start, end]};
return isCommentToken(sourceCode.getTokenBefore(range, {includeComments: true}))
|| isCommentToken(sourceCode.getTokenAfter(range, {includeComments: true}));
}
/**
@param {import('eslint').Rule.RuleContext} context
*/
const create = context => {
const {sourceCode} = context;
context.on('LogicalExpression', node => {
if (node.operator !== '&&' && node.operator !== '||') {
return;
}
if (hasSameOperatorLogicalParent(node)) {
return;
}
// The rule only reorders operands, so TypeScript wrappers around a boolean context keep their type
if (!isBooleanContext(getOutermostTypeScriptExpression(node), context)) {
return;
}
const operands = getLogicalOperands(node, node.operator);
const classifiedOperands = operands.map(operand => ({operand, isSimple: isSimple(operand)}));
const firstComplexOperandIndex = classifiedOperands.findIndex(({isSimple}) => !isSimple);
const firstMisplacedSimpleOperandIndex = classifiedOperands.findIndex(
({isSimple}, index) => isSimple
&& index > firstComplexOperandIndex
&& !hasEarlierTypeofGuard(operands, index, node.operator),
);
if (
firstComplexOperandIndex === -1
|| firstMisplacedSimpleOperandIndex === -1
) {
return;
}
const reorderedOperands = [
...classifiedOperands.filter(({isSimple}) => isSimple),
...classifiedOperands.filter(({isSimple}) => !isSimple),
].map(({operand}) => operand);
const lastSimpleOperandIndex = classifiedOperands.findLastIndex(({isSimple}) => isSimple);
const canSafelyReorder = classifiedOperands.every(
({operand, isSimple}, index) => isSimple || index > lastSimpleOperandIndex || isSafeToMove(operand),
);
const canFix = canSafelyReorder
&& !hasTypeScriptWrappedLogicalExpression(node, node.operator)
&& !hasCommentsThatPreventFix(node, operands, context);
const fix = canFix
? fixer => fixer.replaceTextRange(
sourceCode.getRange(node),
reorderedOperands
.map((operand, index) => getLogicalExpressionChildText(operand, context, {
operator: node.operator,
property: index === 0 ? 'left' : 'right',
}))
.join(` ${node.operator} `),
)
: undefined;
return {
node,
loc: sourceCode.getLoc(operands[firstMisplacedSimpleOperandIndex]),
messageId: canSafelyReorder ? MESSAGE_ID : MESSAGE_ID_UNSAFE,
data: {operator: node.operator},
...(fix && {fix}),
};
});
};
/**
@type {import('eslint').Rule.RuleModule}
*/
const config = {
create,
meta: {
type: 'suggestion',
docs: {
description: 'Prefer simple conditions first in logical expressions.',
recommended: true,
},
fixable: 'code',
messages,
languages: [
'js/js',
],
},
};
export default config;