prefer-numeric-literals.js 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148
  1. /**
  2. * @fileoverview Rule to disallow `parseInt()` in favor of binary, octal, and hexadecimal literals
  3. * @author Annie Zhang, Henry Zhu
  4. */
  5. "use strict";
  6. //------------------------------------------------------------------------------
  7. // Requirements
  8. //------------------------------------------------------------------------------
  9. const astUtils = require("./utils/ast-utils");
  10. //------------------------------------------------------------------------------
  11. // Helpers
  12. //------------------------------------------------------------------------------
  13. const radixMap = new Map([
  14. [2, { system: "binary", literalPrefix: "0b" }],
  15. [8, { system: "octal", literalPrefix: "0o" }],
  16. [16, { system: "hexadecimal", literalPrefix: "0x" }]
  17. ]);
  18. /**
  19. * Checks to see if a CallExpression's callee node is `parseInt` or
  20. * `Number.parseInt`.
  21. * @param {ASTNode} calleeNode The callee node to evaluate.
  22. * @returns {boolean} True if the callee is `parseInt` or `Number.parseInt`,
  23. * false otherwise.
  24. */
  25. function isParseInt(calleeNode) {
  26. return (
  27. astUtils.isSpecificId(calleeNode, "parseInt") ||
  28. astUtils.isSpecificMemberAccess(calleeNode, "Number", "parseInt")
  29. );
  30. }
  31. //------------------------------------------------------------------------------
  32. // Rule Definition
  33. //------------------------------------------------------------------------------
  34. /** @type {import('../shared/types').Rule} */
  35. module.exports = {
  36. meta: {
  37. type: "suggestion",
  38. docs: {
  39. description: "Disallow `parseInt()` and `Number.parseInt()` in favor of binary, octal, and hexadecimal literals",
  40. recommended: false,
  41. url: "https://eslint.org/docs/rules/prefer-numeric-literals"
  42. },
  43. schema: [],
  44. messages: {
  45. useLiteral: "Use {{system}} literals instead of {{functionName}}()."
  46. },
  47. fixable: "code"
  48. },
  49. create(context) {
  50. const sourceCode = context.getSourceCode();
  51. //----------------------------------------------------------------------
  52. // Public
  53. //----------------------------------------------------------------------
  54. return {
  55. "CallExpression[arguments.length=2]"(node) {
  56. const [strNode, radixNode] = node.arguments,
  57. str = astUtils.getStaticStringValue(strNode),
  58. radix = radixNode.value;
  59. if (
  60. str !== null &&
  61. astUtils.isStringLiteral(strNode) &&
  62. radixNode.type === "Literal" &&
  63. typeof radix === "number" &&
  64. radixMap.has(radix) &&
  65. isParseInt(node.callee)
  66. ) {
  67. const { system, literalPrefix } = radixMap.get(radix);
  68. context.report({
  69. node,
  70. messageId: "useLiteral",
  71. data: {
  72. system,
  73. functionName: sourceCode.getText(node.callee)
  74. },
  75. fix(fixer) {
  76. if (sourceCode.getCommentsInside(node).length) {
  77. return null;
  78. }
  79. const replacement = `${literalPrefix}${str}`;
  80. if (+replacement !== parseInt(str, radix)) {
  81. /*
  82. * If the newly-produced literal would be invalid, (e.g. 0b1234),
  83. * or it would yield an incorrect parseInt result for some other reason, don't make a fix.
  84. *
  85. * If `str` had numeric separators, `+replacement` will evaluate to `NaN` because unary `+`
  86. * per the specification doesn't support numeric separators. Thus, the above condition will be `true`
  87. * (`NaN !== anything` is always `true`) regardless of the `parseInt(str, radix)` value.
  88. * Consequently, no autofixes will be made. This is correct behavior because `parseInt` also
  89. * doesn't support numeric separators, but it does parse part of the string before the first `_`,
  90. * so the autofix would be invalid:
  91. *
  92. * parseInt("1_1", 2) // === 1
  93. * 0b1_1 // === 3
  94. */
  95. return null;
  96. }
  97. const tokenBefore = sourceCode.getTokenBefore(node),
  98. tokenAfter = sourceCode.getTokenAfter(node);
  99. let prefix = "",
  100. suffix = "";
  101. if (
  102. tokenBefore &&
  103. tokenBefore.range[1] === node.range[0] &&
  104. !astUtils.canTokensBeAdjacent(tokenBefore, replacement)
  105. ) {
  106. prefix = " ";
  107. }
  108. if (
  109. tokenAfter &&
  110. node.range[1] === tokenAfter.range[0] &&
  111. !astUtils.canTokensBeAdjacent(replacement, tokenAfter)
  112. ) {
  113. suffix = " ";
  114. }
  115. return fixer.replaceText(node, `${prefix}${replacement}${suffix}`);
  116. }
  117. });
  118. }
  119. }
  120. };
  121. }
  122. };