Ohm-Management - Projektarbeit B-ME
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

no-implicit-coercion.js 10.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  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("../util/ast-utils");
  7. //------------------------------------------------------------------------------
  8. // Helpers
  9. //------------------------------------------------------------------------------
  10. const INDEX_OF_PATTERN = /^(?:i|lastI)ndexOf$/;
  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 ? Boolean(options.boolean) : true,
  20. number: "number" in options ? Boolean(options.number) : true,
  21. string: "string" in options ? Boolean(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. },
  150. number: {
  151. type: "boolean"
  152. },
  153. string: {
  154. type: "boolean"
  155. },
  156. allow: {
  157. type: "array",
  158. items: {
  159. enum: ALLOWABLE_OPERATORS
  160. },
  161. uniqueItems: true
  162. }
  163. },
  164. additionalProperties: false
  165. }]
  166. },
  167. create(context) {
  168. const options = parseOptions(context.options[0] || {});
  169. const sourceCode = context.getSourceCode();
  170. /**
  171. * Reports an error and autofixes the node
  172. * @param {ASTNode} node - An ast node to report the error on.
  173. * @param {string} recommendation - The recommended code for the issue
  174. * @param {bool} shouldFix - Whether this report should fix the node
  175. * @returns {void}
  176. */
  177. function report(node, recommendation, shouldFix) {
  178. context.report({
  179. node,
  180. message: "use `{{recommendation}}` instead.",
  181. data: {
  182. recommendation
  183. },
  184. fix(fixer) {
  185. if (!shouldFix) {
  186. return null;
  187. }
  188. const tokenBefore = sourceCode.getTokenBefore(node);
  189. if (
  190. tokenBefore &&
  191. tokenBefore.range[1] === node.range[0] &&
  192. !astUtils.canTokensBeAdjacent(tokenBefore, recommendation)
  193. ) {
  194. return fixer.replaceText(node, ` ${recommendation}`);
  195. }
  196. return fixer.replaceText(node, recommendation);
  197. }
  198. });
  199. }
  200. return {
  201. UnaryExpression(node) {
  202. let operatorAllowed;
  203. // !!foo
  204. operatorAllowed = options.allow.indexOf("!!") >= 0;
  205. if (!operatorAllowed && options.boolean && isDoubleLogicalNegating(node)) {
  206. const recommendation = `Boolean(${sourceCode.getText(node.argument.argument)})`;
  207. report(node, recommendation, true);
  208. }
  209. // ~foo.indexOf(bar)
  210. operatorAllowed = options.allow.indexOf("~") >= 0;
  211. if (!operatorAllowed && options.boolean && isBinaryNegatingOfIndexOf(node)) {
  212. const recommendation = `${sourceCode.getText(node.argument)} !== -1`;
  213. report(node, recommendation, false);
  214. }
  215. // +foo
  216. operatorAllowed = options.allow.indexOf("+") >= 0;
  217. if (!operatorAllowed && options.number && node.operator === "+" && !isNumeric(node.argument)) {
  218. const recommendation = `Number(${sourceCode.getText(node.argument)})`;
  219. report(node, recommendation, true);
  220. }
  221. },
  222. // Use `:exit` to prevent double reporting
  223. "BinaryExpression:exit"(node) {
  224. let operatorAllowed;
  225. // 1 * foo
  226. operatorAllowed = options.allow.indexOf("*") >= 0;
  227. const nonNumericOperand = !operatorAllowed && options.number && isMultiplyByOne(node) && getNonNumericOperand(node);
  228. if (nonNumericOperand) {
  229. const recommendation = `Number(${sourceCode.getText(nonNumericOperand)})`;
  230. report(node, recommendation, true);
  231. }
  232. // "" + foo
  233. operatorAllowed = options.allow.indexOf("+") >= 0;
  234. if (!operatorAllowed && options.string && isConcatWithEmptyString(node)) {
  235. const recommendation = `String(${sourceCode.getText(getNonEmptyOperand(node))})`;
  236. report(node, recommendation, true);
  237. }
  238. },
  239. AssignmentExpression(node) {
  240. // foo += ""
  241. const operatorAllowed = options.allow.indexOf("+") >= 0;
  242. if (!operatorAllowed && options.string && isAppendEmptyString(node)) {
  243. const code = sourceCode.getText(getNonEmptyOperand(node));
  244. const recommendation = `${code} = String(${code})`;
  245. report(node, recommendation, true);
  246. }
  247. }
  248. };
  249. }
  250. };