no-implicit-coercion.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  1. /**
  2. * @fileoverview A rule to disallow the type conversions with shorter notations.
  3. * @author Toru Nagashima
  4. */
  5. "use strict";
  6. const astUtils = require("./utils/ast-utils");
  7. //------------------------------------------------------------------------------
  8. // Helpers
  9. //------------------------------------------------------------------------------
  10. const INDEX_OF_PATTERN = /^(?:i|lastI)ndexOf$/u;
  11. const ALLOWABLE_OPERATORS = ["~", "!!", "+", "*"];
  12. /**
  13. * Parses and normalizes an option object.
  14. * @param {Object} options An option object to parse.
  15. * @returns {Object} The parsed and normalized option object.
  16. */
  17. function parseOptions(options) {
  18. return {
  19. boolean: "boolean" in options ? options.boolean : true,
  20. number: "number" in options ? options.number : true,
  21. string: "string" in options ? options.string : true,
  22. allow: options.allow || []
  23. };
  24. }
  25. /**
  26. * Checks whether or not a node is a double logical nigating.
  27. * @param {ASTNode} node An UnaryExpression node to check.
  28. * @returns {boolean} Whether or not the node is a double logical nigating.
  29. */
  30. function isDoubleLogicalNegating(node) {
  31. return (
  32. node.operator === "!" &&
  33. node.argument.type === "UnaryExpression" &&
  34. node.argument.operator === "!"
  35. );
  36. }
  37. /**
  38. * Checks whether or not a node is a binary negating of `.indexOf()` method calling.
  39. * @param {ASTNode} node An UnaryExpression node to check.
  40. * @returns {boolean} Whether or not the node is a binary negating of `.indexOf()` method calling.
  41. */
  42. function isBinaryNegatingOfIndexOf(node) {
  43. return (
  44. node.operator === "~" &&
  45. node.argument.type === "CallExpression" &&
  46. node.argument.callee.type === "MemberExpression" &&
  47. node.argument.callee.property.type === "Identifier" &&
  48. INDEX_OF_PATTERN.test(node.argument.callee.property.name)
  49. );
  50. }
  51. /**
  52. * Checks whether or not a node is a multiplying by one.
  53. * @param {BinaryExpression} node A BinaryExpression node to check.
  54. * @returns {boolean} Whether or not the node is a multiplying by one.
  55. */
  56. function isMultiplyByOne(node) {
  57. return node.operator === "*" && (
  58. node.left.type === "Literal" && node.left.value === 1 ||
  59. node.right.type === "Literal" && node.right.value === 1
  60. );
  61. }
  62. /**
  63. * Checks whether the result of a node is numeric or not
  64. * @param {ASTNode} node The node to test
  65. * @returns {boolean} true if the node is a number literal or a `Number()`, `parseInt` or `parseFloat` call
  66. */
  67. function isNumeric(node) {
  68. return (
  69. node.type === "Literal" && typeof node.value === "number" ||
  70. node.type === "CallExpression" && (
  71. node.callee.name === "Number" ||
  72. node.callee.name === "parseInt" ||
  73. node.callee.name === "parseFloat"
  74. )
  75. );
  76. }
  77. /**
  78. * Returns the first non-numeric operand in a BinaryExpression. Designed to be
  79. * used from bottom to up since it walks up the BinaryExpression trees using
  80. * node.parent to find the result.
  81. * @param {BinaryExpression} node The BinaryExpression node to be walked up on
  82. * @returns {ASTNode|null} The first non-numeric item in the BinaryExpression tree or null
  83. */
  84. function getNonNumericOperand(node) {
  85. const left = node.left,
  86. right = node.right;
  87. if (right.type !== "BinaryExpression" && !isNumeric(right)) {
  88. return right;
  89. }
  90. if (left.type !== "BinaryExpression" && !isNumeric(left)) {
  91. return left;
  92. }
  93. return null;
  94. }
  95. /**
  96. * Checks whether a node is an empty string literal or not.
  97. * @param {ASTNode} node The node to check.
  98. * @returns {boolean} Whether or not the passed in node is an
  99. * empty string literal or not.
  100. */
  101. function isEmptyString(node) {
  102. return astUtils.isStringLiteral(node) && (node.value === "" || (node.type === "TemplateLiteral" && node.quasis.length === 1 && node.quasis[0].value.cooked === ""));
  103. }
  104. /**
  105. * Checks whether or not a node is a concatenating with an empty string.
  106. * @param {ASTNode} node A BinaryExpression node to check.
  107. * @returns {boolean} Whether or not the node is a concatenating with an empty string.
  108. */
  109. function isConcatWithEmptyString(node) {
  110. return node.operator === "+" && (
  111. (isEmptyString(node.left) && !astUtils.isStringLiteral(node.right)) ||
  112. (isEmptyString(node.right) && !astUtils.isStringLiteral(node.left))
  113. );
  114. }
  115. /**
  116. * Checks whether or not a node is appended with an empty string.
  117. * @param {ASTNode} node An AssignmentExpression node to check.
  118. * @returns {boolean} Whether or not the node is appended with an empty string.
  119. */
  120. function isAppendEmptyString(node) {
  121. return node.operator === "+=" && isEmptyString(node.right);
  122. }
  123. /**
  124. * Returns the operand that is not an empty string from a flagged BinaryExpression.
  125. * @param {ASTNode} node The flagged BinaryExpression node to check.
  126. * @returns {ASTNode} The operand that is not an empty string from a flagged BinaryExpression.
  127. */
  128. function getNonEmptyOperand(node) {
  129. return isEmptyString(node.left) ? node.right : node.left;
  130. }
  131. //------------------------------------------------------------------------------
  132. // Rule Definition
  133. //------------------------------------------------------------------------------
  134. module.exports = {
  135. meta: {
  136. type: "suggestion",
  137. docs: {
  138. description: "disallow shorthand type conversions",
  139. category: "Best Practices",
  140. recommended: false,
  141. url: "https://eslint.org/docs/rules/no-implicit-coercion"
  142. },
  143. fixable: "code",
  144. schema: [{
  145. type: "object",
  146. properties: {
  147. boolean: {
  148. type: "boolean",
  149. default: true
  150. },
  151. number: {
  152. type: "boolean",
  153. default: true
  154. },
  155. string: {
  156. type: "boolean",
  157. default: true
  158. },
  159. allow: {
  160. type: "array",
  161. items: {
  162. enum: ALLOWABLE_OPERATORS
  163. },
  164. uniqueItems: true
  165. }
  166. },
  167. additionalProperties: false
  168. }]
  169. },
  170. create(context) {
  171. const options = parseOptions(context.options[0] || {});
  172. const sourceCode = context.getSourceCode();
  173. /**
  174. * Reports an error and autofixes the node
  175. * @param {ASTNode} node An ast node to report the error on.
  176. * @param {string} recommendation The recommended code for the issue
  177. * @param {bool} shouldFix Whether this report should fix the node
  178. * @returns {void}
  179. */
  180. function report(node, recommendation, shouldFix) {
  181. context.report({
  182. node,
  183. message: "use `{{recommendation}}` instead.",
  184. data: {
  185. recommendation
  186. },
  187. fix(fixer) {
  188. if (!shouldFix) {
  189. return null;
  190. }
  191. const tokenBefore = sourceCode.getTokenBefore(node);
  192. if (
  193. tokenBefore &&
  194. tokenBefore.range[1] === node.range[0] &&
  195. !astUtils.canTokensBeAdjacent(tokenBefore, recommendation)
  196. ) {
  197. return fixer.replaceText(node, ` ${recommendation}`);
  198. }
  199. return fixer.replaceText(node, recommendation);
  200. }
  201. });
  202. }
  203. return {
  204. UnaryExpression(node) {
  205. let operatorAllowed;
  206. // !!foo
  207. operatorAllowed = options.allow.indexOf("!!") >= 0;
  208. if (!operatorAllowed && options.boolean && isDoubleLogicalNegating(node)) {
  209. const recommendation = `Boolean(${sourceCode.getText(node.argument.argument)})`;
  210. report(node, recommendation, true);
  211. }
  212. // ~foo.indexOf(bar)
  213. operatorAllowed = options.allow.indexOf("~") >= 0;
  214. if (!operatorAllowed && options.boolean && isBinaryNegatingOfIndexOf(node)) {
  215. const recommendation = `${sourceCode.getText(node.argument)} !== -1`;
  216. report(node, recommendation, false);
  217. }
  218. // +foo
  219. operatorAllowed = options.allow.indexOf("+") >= 0;
  220. if (!operatorAllowed && options.number && node.operator === "+" && !isNumeric(node.argument)) {
  221. const recommendation = `Number(${sourceCode.getText(node.argument)})`;
  222. report(node, recommendation, true);
  223. }
  224. },
  225. // Use `:exit` to prevent double reporting
  226. "BinaryExpression:exit"(node) {
  227. let operatorAllowed;
  228. // 1 * foo
  229. operatorAllowed = options.allow.indexOf("*") >= 0;
  230. const nonNumericOperand = !operatorAllowed && options.number && isMultiplyByOne(node) && getNonNumericOperand(node);
  231. if (nonNumericOperand) {
  232. const recommendation = `Number(${sourceCode.getText(nonNumericOperand)})`;
  233. report(node, recommendation, true);
  234. }
  235. // "" + foo
  236. operatorAllowed = options.allow.indexOf("+") >= 0;
  237. if (!operatorAllowed && options.string && isConcatWithEmptyString(node)) {
  238. const recommendation = `String(${sourceCode.getText(getNonEmptyOperand(node))})`;
  239. report(node, recommendation, true);
  240. }
  241. },
  242. AssignmentExpression(node) {
  243. // foo += ""
  244. const operatorAllowed = options.allow.indexOf("+") >= 0;
  245. if (!operatorAllowed && options.string && isAppendEmptyString(node)) {
  246. const code = sourceCode.getText(getNonEmptyOperand(node));
  247. const recommendation = `${code} = String(${code})`;
  248. report(node, recommendation, true);
  249. }
  250. }
  251. };
  252. }
  253. };