123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411 |
- "use strict";
- const astUtils = require("./utils/ast-utils");
- const INDEX_OF_PATTERN = /^(?:i|lastI)ndexOf$/u;
- const ALLOWABLE_OPERATORS = ["~", "!!", "+", "- -", "-", "*"];
- function isDoubleLogicalNegating(node) {
- return (
- node.operator === "!" &&
- node.argument.type === "UnaryExpression" &&
- node.argument.operator === "!"
- );
- }
- function isBinaryNegatingOfIndexOf(node) {
- if (node.operator !== "~") {
- return false;
- }
- const callNode = astUtils.skipChainExpression(node.argument);
- return (
- callNode.type === "CallExpression" &&
- astUtils.isSpecificMemberAccess(callNode.callee, null, INDEX_OF_PATTERN)
- );
- }
- function isMultiplyByOne(node) {
- return node.operator === "*" && (
- node.left.type === "Literal" && node.left.value === 1 ||
- node.right.type === "Literal" && node.right.value === 1
- );
- }
- function isMultiplyByFractionOfOne(node, sourceCode) {
- return node.type === "BinaryExpression" &&
- node.operator === "*" &&
- (node.right.type === "Literal" && node.right.value === 1) &&
- node.parent.type === "BinaryExpression" &&
- node.parent.operator === "/" &&
- node.parent.left === node &&
- !astUtils.isParenthesised(sourceCode, node);
- }
- function isNumeric(node) {
- return (
- node.type === "Literal" && typeof node.value === "number" ||
- node.type === "CallExpression" && (
- node.callee.name === "Number" ||
- node.callee.name === "parseInt" ||
- node.callee.name === "parseFloat"
- )
- );
- }
- function getNonNumericOperand(node) {
- const left = node.left,
- right = node.right;
- if (right.type !== "BinaryExpression" && !isNumeric(right)) {
- return right;
- }
- if (left.type !== "BinaryExpression" && !isNumeric(left)) {
- return left;
- }
- return null;
- }
- function isStringType(node) {
- return astUtils.isStringLiteral(node) ||
- (
- node.type === "CallExpression" &&
- node.callee.type === "Identifier" &&
- node.callee.name === "String"
- );
- }
- function isEmptyString(node) {
- return astUtils.isStringLiteral(node) && (node.value === "" || (node.type === "TemplateLiteral" && node.quasis.length === 1 && node.quasis[0].value.cooked === ""));
- }
- function isConcatWithEmptyString(node) {
- return node.operator === "+" && (
- (isEmptyString(node.left) && !isStringType(node.right)) ||
- (isEmptyString(node.right) && !isStringType(node.left))
- );
- }
- function isAppendEmptyString(node) {
- return node.operator === "+=" && isEmptyString(node.right);
- }
- function getNonEmptyOperand(node) {
- return isEmptyString(node.left) ? node.right : node.left;
- }
- module.exports = {
- meta: {
- hasSuggestions: true,
- type: "suggestion",
- docs: {
- description: "Disallow shorthand type conversions",
- recommended: false,
- url: "https://eslint.org/docs/latest/rules/no-implicit-coercion"
- },
- fixable: "code",
- schema: [{
- type: "object",
- properties: {
- boolean: {
- type: "boolean"
- },
- number: {
- type: "boolean"
- },
- string: {
- type: "boolean"
- },
- disallowTemplateShorthand: {
- type: "boolean"
- },
- allow: {
- type: "array",
- items: {
- enum: ALLOWABLE_OPERATORS
- },
- uniqueItems: true
- }
- },
- additionalProperties: false
- }],
- defaultOptions: [{
- allow: [],
- boolean: true,
- disallowTemplateShorthand: false,
- number: true,
- string: true
- }],
- messages: {
- implicitCoercion: "Unexpected implicit coercion encountered. Use `{{recommendation}}` instead.",
- useRecommendation: "Use `{{recommendation}}` instead."
- }
- },
- create(context) {
- const [options] = context.options;
- const sourceCode = context.sourceCode;
-
- function report(node, recommendation, shouldSuggest, shouldFix) {
-
- function fix(fixer) {
- const tokenBefore = sourceCode.getTokenBefore(node);
- if (
- tokenBefore?.range[1] === node.range[0] &&
- !astUtils.canTokensBeAdjacent(tokenBefore, recommendation)
- ) {
- return fixer.replaceText(node, ` ${recommendation}`);
- }
- return fixer.replaceText(node, recommendation);
- }
- context.report({
- node,
- messageId: "implicitCoercion",
- data: { recommendation },
- fix(fixer) {
- if (!shouldFix) {
- return null;
- }
- return fix(fixer);
- },
- suggest: [
- {
- messageId: "useRecommendation",
- data: { recommendation },
- fix(fixer) {
- if (shouldFix || !shouldSuggest) {
- return null;
- }
- return fix(fixer);
- }
- }
- ]
- });
- }
- return {
- UnaryExpression(node) {
- let operatorAllowed;
-
- operatorAllowed = options.allow.includes("!!");
- if (!operatorAllowed && options.boolean && isDoubleLogicalNegating(node)) {
- const recommendation = `Boolean(${sourceCode.getText(node.argument.argument)})`;
- const variable = astUtils.getVariableByName(sourceCode.getScope(node), "Boolean");
- const booleanExists = variable?.identifiers.length === 0;
- report(node, recommendation, true, booleanExists);
- }
-
- operatorAllowed = options.allow.includes("~");
- if (!operatorAllowed && options.boolean && isBinaryNegatingOfIndexOf(node)) {
-
- const comparison = node.argument.type === "ChainExpression" ? ">= 0" : "!== -1";
- const recommendation = `${sourceCode.getText(node.argument)} ${comparison}`;
- report(node, recommendation, false, false);
- }
-
- operatorAllowed = options.allow.includes("+");
- if (!operatorAllowed && options.number && node.operator === "+" && !isNumeric(node.argument)) {
- const recommendation = `Number(${sourceCode.getText(node.argument)})`;
- report(node, recommendation, true, false);
- }
-
- operatorAllowed = options.allow.includes("- -");
- if (!operatorAllowed && options.number && node.operator === "-" && node.argument.type === "UnaryExpression" && node.argument.operator === "-" && !isNumeric(node.argument.argument)) {
- const recommendation = `Number(${sourceCode.getText(node.argument.argument)})`;
- report(node, recommendation, true, false);
- }
- },
-
- "BinaryExpression:exit"(node) {
- let operatorAllowed;
-
- operatorAllowed = options.allow.includes("*");
- const nonNumericOperand = !operatorAllowed && options.number && isMultiplyByOne(node) && !isMultiplyByFractionOfOne(node, sourceCode) &&
- getNonNumericOperand(node);
- if (nonNumericOperand) {
- const recommendation = `Number(${sourceCode.getText(nonNumericOperand)})`;
- report(node, recommendation, true, false);
- }
-
- operatorAllowed = options.allow.includes("-");
- if (!operatorAllowed && options.number && node.operator === "-" && node.right.type === "Literal" && node.right.value === 0 && !isNumeric(node.left)) {
- const recommendation = `Number(${sourceCode.getText(node.left)})`;
- report(node, recommendation, true, false);
- }
-
- operatorAllowed = options.allow.includes("+");
- if (!operatorAllowed && options.string && isConcatWithEmptyString(node)) {
- const recommendation = `String(${sourceCode.getText(getNonEmptyOperand(node))})`;
- report(node, recommendation, true, false);
- }
- },
- AssignmentExpression(node) {
-
- const operatorAllowed = options.allow.includes("+");
- if (!operatorAllowed && options.string && isAppendEmptyString(node)) {
- const code = sourceCode.getText(getNonEmptyOperand(node));
- const recommendation = `${code} = String(${code})`;
- report(node, recommendation, true, false);
- }
- },
- TemplateLiteral(node) {
- if (!options.disallowTemplateShorthand) {
- return;
- }
-
- if (node.parent.type === "TaggedTemplateExpression") {
- return;
- }
-
- if (node.expressions.length !== 1) {
- return;
- }
-
- if (node.quasis[0].value.cooked !== "") {
- return;
- }
-
- if (node.quasis[1].value.cooked !== "") {
- return;
- }
-
- if (isStringType(node.expressions[0])) {
- return;
- }
- const code = sourceCode.getText(node.expressions[0]);
- const recommendation = `String(${code})`;
- report(node, recommendation, true, false);
- }
- };
- }
- };
|