prefer-numeric-literals.js 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157
  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('../types').Rule.RuleModule} */
  35. module.exports = {
  36. meta: {
  37. type: "suggestion",
  38. docs: {
  39. description:
  40. "Disallow `parseInt()` and `Number.parseInt()` in favor of binary, octal, and hexadecimal literals",
  41. recommended: false,
  42. frozen: true,
  43. url: "https://eslint.org/docs/latest/rules/prefer-numeric-literals",
  44. },
  45. schema: [],
  46. messages: {
  47. useLiteral:
  48. "Use {{system}} literals instead of {{functionName}}().",
  49. },
  50. fixable: "code",
  51. },
  52. create(context) {
  53. const sourceCode = context.sourceCode;
  54. //----------------------------------------------------------------------
  55. // Public
  56. //----------------------------------------------------------------------
  57. return {
  58. "CallExpression[arguments.length=2]"(node) {
  59. const [strNode, radixNode] = node.arguments,
  60. str = astUtils.getStaticStringValue(strNode),
  61. radix = radixNode.value;
  62. if (
  63. str !== null &&
  64. astUtils.isStringLiteral(strNode) &&
  65. radixNode.type === "Literal" &&
  66. typeof radix === "number" &&
  67. radixMap.has(radix) &&
  68. isParseInt(node.callee)
  69. ) {
  70. const { system, literalPrefix } = radixMap.get(radix);
  71. context.report({
  72. node,
  73. messageId: "useLiteral",
  74. data: {
  75. system,
  76. functionName: sourceCode.getText(node.callee),
  77. },
  78. fix(fixer) {
  79. if (sourceCode.getCommentsInside(node).length) {
  80. return null;
  81. }
  82. const replacement = `${literalPrefix}${str}`;
  83. if (+replacement !== parseInt(str, radix)) {
  84. /*
  85. * If the newly-produced literal would be invalid, (e.g. 0b1234),
  86. * or it would yield an incorrect parseInt result for some other reason, don't make a fix.
  87. *
  88. * If `str` had numeric separators, `+replacement` will evaluate to `NaN` because unary `+`
  89. * per the specification doesn't support numeric separators. Thus, the above condition will be `true`
  90. * (`NaN !== anything` is always `true`) regardless of the `parseInt(str, radix)` value.
  91. * Consequently, no autofixes will be made. This is correct behavior because `parseInt` also
  92. * doesn't support numeric separators, but it does parse part of the string before the first `_`,
  93. * so the autofix would be invalid:
  94. *
  95. * parseInt("1_1", 2) // === 1
  96. * 0b1_1 // === 3
  97. */
  98. return null;
  99. }
  100. const tokenBefore = sourceCode.getTokenBefore(node),
  101. tokenAfter = sourceCode.getTokenAfter(node);
  102. let prefix = "",
  103. suffix = "";
  104. if (
  105. tokenBefore &&
  106. tokenBefore.range[1] === node.range[0] &&
  107. !astUtils.canTokensBeAdjacent(
  108. tokenBefore,
  109. replacement,
  110. )
  111. ) {
  112. prefix = " ";
  113. }
  114. if (
  115. tokenAfter &&
  116. node.range[1] === tokenAfter.range[0] &&
  117. !astUtils.canTokensBeAdjacent(
  118. replacement,
  119. tokenAfter,
  120. )
  121. ) {
  122. suffix = " ";
  123. }
  124. return fixer.replaceText(
  125. node,
  126. `${prefix}${replacement}${suffix}`,
  127. );
  128. },
  129. });
  130. }
  131. },
  132. };
  133. },
  134. };