github-pages-deploy-action/node_modules/eslint/lib/rules/no-extra-boolean-cast.js

310 lines
11 KiB
JavaScript
Raw Normal View History

2020-03-07 11:45:40 +08:00
/**
* @fileoverview Rule to flag unnecessary double negation in Boolean contexts
* @author Brandon Mills
*/
"use strict";
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
2020-03-31 20:40:00 +08:00
const astUtils = require("./utils/ast-utils");
2020-05-15 05:33:08 +08:00
const eslintUtils = require("eslint-utils");
const precedence = astUtils.getPrecedence;
2020-03-07 11:45:40 +08:00
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
module.exports = {
meta: {
type: "suggestion",
docs: {
description: "disallow unnecessary boolean casts",
category: "Possible Errors",
recommended: true,
url: "https://eslint.org/docs/rules/no-extra-boolean-cast"
},
2020-05-15 05:33:08 +08:00
schema: [{
type: "object",
properties: {
enforceForLogicalOperands: {
type: "boolean",
default: false
}
},
additionalProperties: false
}],
2020-03-07 11:45:40 +08:00
fixable: "code",
messages: {
unexpectedCall: "Redundant Boolean call.",
unexpectedNegation: "Redundant double negation."
}
},
create(context) {
const sourceCode = context.getSourceCode();
// Node types which have a test which will coerce values to booleans.
const BOOLEAN_NODE_TYPES = [
"IfStatement",
"DoWhileStatement",
"WhileStatement",
"ConditionalExpression",
"ForStatement"
];
2020-05-15 05:33:08 +08:00
/**
* Check if a node is a Boolean function or constructor.
* @param {ASTNode} node the node
* @returns {boolean} If the node is Boolean function or constructor
*/
function isBooleanFunctionOrConstructorCall(node) {
// Boolean(<bool>) and new Boolean(<bool>)
return (node.type === "CallExpression" || node.type === "NewExpression") &&
node.callee.type === "Identifier" &&
node.callee.name === "Boolean";
}
/**
* Checks whether the node is a logical expression and that the option is enabled
* @param {ASTNode} node the node
* @returns {boolean} if the node is a logical expression and option is enabled
*/
function isLogicalContext(node) {
return node.type === "LogicalExpression" &&
(node.operator === "||" || node.operator === "&&") &&
(context.options.length && context.options[0].enforceForLogicalOperands === true);
}
2020-03-07 11:45:40 +08:00
/**
* Check if a node is in a context where its value would be coerced to a boolean at runtime.
2020-03-31 20:40:00 +08:00
* @param {ASTNode} node The node
2020-03-07 11:45:40 +08:00
* @returns {boolean} If it is in a boolean context
*/
2020-05-15 05:33:08 +08:00
function isInBooleanContext(node) {
2020-03-07 11:45:40 +08:00
return (
2020-05-15 05:33:08 +08:00
(isBooleanFunctionOrConstructorCall(node.parent) &&
node === node.parent.arguments[0]) ||
(BOOLEAN_NODE_TYPES.indexOf(node.parent.type) !== -1 &&
node === node.parent.test) ||
2020-03-07 11:45:40 +08:00
// !<bool>
2020-05-15 05:33:08 +08:00
(node.parent.type === "UnaryExpression" &&
node.parent.operator === "!")
2020-03-07 11:45:40 +08:00
);
}
2020-05-15 05:33:08 +08:00
/**
* Checks whether the node is a context that should report an error
* Acts recursively if it is in a logical context
* @param {ASTNode} node the node
* @returns {boolean} If the node is in one of the flagged contexts
*/
function isInFlaggedContext(node) {
return isInBooleanContext(node) ||
(isLogicalContext(node.parent) &&
// For nested logical statements
isInFlaggedContext(node.parent)
);
}
2020-03-31 20:40:00 +08:00
/**
* Check if a node has comments inside.
* @param {ASTNode} node The node to check.
* @returns {boolean} `true` if it has comments inside.
*/
function hasCommentsInside(node) {
return Boolean(sourceCode.getCommentsInside(node).length);
}
2020-03-07 11:45:40 +08:00
2020-05-15 05:33:08 +08:00
/**
* Checks if the given node is wrapped in grouping parentheses. Parentheses for constructs such as if() don't count.
* @param {ASTNode} node The node to check.
* @returns {boolean} `true` if the node is parenthesized.
* @private
*/
function isParenthesized(node) {
return eslintUtils.isParenthesized(1, node, sourceCode);
}
/**
* Determines whether the given node needs to be parenthesized when replacing the previous node.
* It assumes that `previousNode` is the node to be reported by this rule, so it has a limited list
* of possible parent node types. By the same assumption, the node's role in a particular parent is already known.
* For example, if the parent is `ConditionalExpression`, `previousNode` must be its `test` child.
* @param {ASTNode} previousNode Previous node.
* @param {ASTNode} node The node to check.
* @returns {boolean} `true` if the node needs to be parenthesized.
*/
function needsParens(previousNode, node) {
if (isParenthesized(previousNode)) {
// parentheses around the previous node will stay, so there is no need for an additional pair
return false;
}
// parent of the previous node will become parent of the replacement node
const parent = previousNode.parent;
switch (parent.type) {
case "CallExpression":
case "NewExpression":
return node.type === "SequenceExpression";
case "IfStatement":
case "DoWhileStatement":
case "WhileStatement":
case "ForStatement":
return false;
case "ConditionalExpression":
return precedence(node) <= precedence(parent);
case "UnaryExpression":
return precedence(node) < precedence(parent);
case "LogicalExpression":
2020-06-27 02:01:06 +08:00
if (astUtils.isMixedLogicalAndCoalesceExpressions(node, parent)) {
return true;
}
2020-05-15 05:33:08 +08:00
if (previousNode === parent.left) {
return precedence(node) < precedence(parent);
}
return precedence(node) <= precedence(parent);
/* istanbul ignore next */
default:
throw new Error(`Unexpected parent type: ${parent.type}`);
}
}
2020-03-07 11:45:40 +08:00
return {
UnaryExpression(node) {
2020-05-15 05:33:08 +08:00
const parent = node.parent;
2020-03-07 11:45:40 +08:00
// Exit early if it's guaranteed not to match
if (node.operator !== "!" ||
2020-05-15 05:33:08 +08:00
parent.type !== "UnaryExpression" ||
parent.operator !== "!") {
2020-03-07 11:45:40 +08:00
return;
}
2020-05-15 05:33:08 +08:00
if (isInFlaggedContext(parent)) {
2020-03-07 11:45:40 +08:00
context.report({
2020-03-31 20:40:00 +08:00
node: parent,
2020-03-07 11:45:40 +08:00
messageId: "unexpectedNegation",
2020-05-15 05:33:08 +08:00
fix(fixer) {
2020-03-31 20:40:00 +08:00
if (hasCommentsInside(parent)) {
return null;
}
2020-05-15 05:33:08 +08:00
if (needsParens(parent, node.argument)) {
return fixer.replaceText(parent, `(${sourceCode.getText(node.argument)})`);
}
2020-03-31 20:40:00 +08:00
let prefix = "";
const tokenBefore = sourceCode.getTokenBefore(parent);
const firstReplacementToken = sourceCode.getFirstToken(node.argument);
2020-05-15 05:33:08 +08:00
if (
tokenBefore &&
tokenBefore.range[1] === parent.range[0] &&
!astUtils.canTokensBeAdjacent(tokenBefore, firstReplacementToken)
) {
2020-03-31 20:40:00 +08:00
prefix = " ";
}
return fixer.replaceText(parent, prefix + sourceCode.getText(node.argument));
}
2020-03-07 11:45:40 +08:00
});
}
},
2020-05-15 05:33:08 +08:00
CallExpression(node) {
2020-03-07 11:45:40 +08:00
if (node.callee.type !== "Identifier" || node.callee.name !== "Boolean") {
return;
}
2020-05-15 05:33:08 +08:00
if (isInFlaggedContext(node)) {
2020-03-07 11:45:40 +08:00
context.report({
node,
messageId: "unexpectedCall",
2020-05-15 05:33:08 +08:00
fix(fixer) {
const parent = node.parent;
if (node.arguments.length === 0) {
2020-03-31 20:40:00 +08:00
if (parent.type === "UnaryExpression" && parent.operator === "!") {
2020-05-15 05:33:08 +08:00
/*
* !Boolean() -> true
*/
2020-03-31 20:40:00 +08:00
if (hasCommentsInside(parent)) {
return null;
}
const replacement = "true";
let prefix = "";
const tokenBefore = sourceCode.getTokenBefore(parent);
2020-05-15 05:33:08 +08:00
if (
tokenBefore &&
tokenBefore.range[1] === parent.range[0] &&
!astUtils.canTokensBeAdjacent(tokenBefore, replacement)
) {
2020-03-31 20:40:00 +08:00
prefix = " ";
}
return fixer.replaceText(parent, prefix + replacement);
}
2020-05-15 05:33:08 +08:00
/*
* Boolean() -> false
*/
2020-03-31 20:40:00 +08:00
if (hasCommentsInside(node)) {
return null;
}
2020-05-15 05:33:08 +08:00
2020-03-31 20:40:00 +08:00
return fixer.replaceText(node, "false");
2020-03-07 11:45:40 +08:00
}
2020-05-15 05:33:08 +08:00
if (node.arguments.length === 1) {
const argument = node.arguments[0];
2020-03-07 11:45:40 +08:00
2020-05-15 05:33:08 +08:00
if (argument.type === "SpreadElement" || hasCommentsInside(node)) {
return null;
}
/*
* Boolean(expression) -> expression
*/
2020-03-07 11:45:40 +08:00
2020-05-15 05:33:08 +08:00
if (needsParens(node, argument)) {
return fixer.replaceText(node, `(${sourceCode.getText(argument)})`);
}
return fixer.replaceText(node, sourceCode.getText(argument));
2020-03-07 11:45:40 +08:00
}
2020-05-15 05:33:08 +08:00
// two or more arguments
return null;
2020-03-07 11:45:40 +08:00
}
});
}
}
};
}
};