@maniascript/mslint
Version:
ManiaScript linter
39 lines (38 loc) • 1.52 kB
JavaScript
import {} from '../linter/rule.js';
import { ConditionalStatement, UnaryExpression, BinaryExpression, UnaryOperator, BinaryOperator } from '@maniascript/parser';
export const noNegatedCondition = {
meta: {
id: 'no-negated-condition',
description: 'Forbid negated conditions',
recommended: true
},
create(context) {
function hasOnlyElse(node) {
return (node.branches.length === 2 &&
node.branches[0].test !== undefined &&
node.branches[1].test === undefined);
}
function isNegatedUnaryExpression(node) {
return (node instanceof UnaryExpression &&
node.operator === UnaryOperator['!']);
}
function isNegatedBinaryExpression(node) {
return (node instanceof BinaryExpression &&
node.operator === BinaryOperator['!=']);
}
function isNegatedIf(node) {
const ifBranchTest = node.branches[0].test;
return (ifBranchTest !== undefined && (isNegatedUnaryExpression(ifBranchTest) ||
isNegatedBinaryExpression(ifBranchTest)));
}
return {
'ConditionalStatement:enter': (node) => {
if (node instanceof ConditionalStatement &&
hasOnlyElse(node) &&
isNegatedIf(node)) {
context.report(node.branches[0].test ?? node, 'Forbidden negated condition');
}
}
};
}
};