no-loss-of-precision.js 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  1. /**
  2. * @fileoverview Rule to flag numbers that will lose significant figure precision at runtime
  3. * @author Jacob Moore
  4. */
  5. "use strict";
  6. //------------------------------------------------------------------------------
  7. // Helpers
  8. //------------------------------------------------------------------------------
  9. /** Class representing a number in scientific notation. */
  10. class ScientificNotation {
  11. /** @type {string} The digits of the coefficient. A decimal point is implied after the first digit. */
  12. coefficient;
  13. /** @type {number} The order of magnitude. */
  14. magnitude;
  15. constructor(coefficient, magnitude) {
  16. this.coefficient = coefficient;
  17. this.magnitude = magnitude;
  18. }
  19. /* c8 ignore start -- debug only */
  20. toString() {
  21. return `${this.coefficient[0]}${this.coefficient.length > 1 ? `.${this.coefficient.slice(1)}` : ""}e${this.magnitude}`;
  22. }
  23. /* c8 ignore stop */
  24. }
  25. /**
  26. * Returns whether the node is number literal
  27. * @param {Node} node the node literal being evaluated
  28. * @returns {boolean} true if the node is a number literal
  29. */
  30. function isNumber(node) {
  31. return typeof node.value === "number";
  32. }
  33. /**
  34. * Gets the source code of the given number literal. Removes `_` numeric separators from the result.
  35. * @param {Node} node the number `Literal` node
  36. * @returns {string} raw source code of the literal, without numeric separators
  37. */
  38. function getRaw(node) {
  39. return node.raw.replace(/_/gu, "");
  40. }
  41. /**
  42. * Checks whether the number is base ten
  43. * @param {ASTNode} node the node being evaluated
  44. * @returns {boolean} true if the node is in base ten
  45. */
  46. function isBaseTen(node) {
  47. const prefixes = ["0x", "0X", "0b", "0B", "0o", "0O"];
  48. return (
  49. prefixes.every(prefix => !node.raw.startsWith(prefix)) &&
  50. !/^0[0-7]+$/u.test(node.raw)
  51. );
  52. }
  53. /**
  54. * Checks that the user-intended non-base ten number equals the actual number after is has been converted to the Number type
  55. * @param {Node} node the node being evaluated
  56. * @returns {boolean} true if they do not match
  57. */
  58. function notBaseTenLosesPrecision(node) {
  59. const rawString = getRaw(node).toUpperCase();
  60. let base;
  61. if (rawString.startsWith("0B")) {
  62. base = 2;
  63. } else if (rawString.startsWith("0X")) {
  64. base = 16;
  65. } else {
  66. base = 8;
  67. }
  68. return !rawString.endsWith(node.value.toString(base).toUpperCase());
  69. }
  70. /**
  71. * Returns the number stripped of leading zeros
  72. * @param {string} numberAsString the string representation of the number
  73. * @returns {string} the stripped string
  74. */
  75. function removeLeadingZeros(numberAsString) {
  76. for (let i = 0; i < numberAsString.length; i++) {
  77. if (numberAsString[i] !== "0") {
  78. return numberAsString.slice(i);
  79. }
  80. }
  81. return numberAsString;
  82. }
  83. /**
  84. * Returns the number stripped of trailing zeros
  85. * @param {string} numberAsString the string representation of the number
  86. * @returns {string} the stripped string
  87. */
  88. function removeTrailingZeros(numberAsString) {
  89. for (let i = numberAsString.length - 1; i >= 0; i--) {
  90. if (numberAsString[i] !== "0") {
  91. return numberAsString.slice(0, i + 1);
  92. }
  93. }
  94. return numberAsString;
  95. }
  96. /**
  97. * Converts an integer to an object containing the integer's coefficient and order of magnitude
  98. * @param {string} stringInteger the string representation of the integer being converted
  99. * @returns {ScientificNotation} the object containing the integer's coefficient and order of magnitude
  100. */
  101. function normalizeInteger(stringInteger) {
  102. const trimmedInteger = removeLeadingZeros(stringInteger);
  103. const significantDigits = removeTrailingZeros(trimmedInteger);
  104. return new ScientificNotation(significantDigits, trimmedInteger.length - 1);
  105. }
  106. /**
  107. * Converts a float to an object containing the float's coefficient and order of magnitude
  108. * @param {string} stringFloat the string representation of the float being converted
  109. * @returns {ScientificNotation} the object containing the float's coefficient and order of magnitude
  110. */
  111. function normalizeFloat(stringFloat) {
  112. const trimmedFloat = removeLeadingZeros(stringFloat);
  113. const indexOfDecimalPoint = trimmedFloat.indexOf(".");
  114. switch (indexOfDecimalPoint) {
  115. case 0: {
  116. const significantDigits = removeLeadingZeros(trimmedFloat.slice(1));
  117. return new ScientificNotation(
  118. significantDigits,
  119. significantDigits.length - trimmedFloat.length,
  120. );
  121. }
  122. case -1:
  123. return new ScientificNotation(
  124. trimmedFloat,
  125. trimmedFloat.length - 1,
  126. );
  127. default:
  128. return new ScientificNotation(
  129. trimmedFloat.replace(".", ""),
  130. indexOfDecimalPoint - 1,
  131. );
  132. }
  133. }
  134. /**
  135. * Converts a base ten number to proper scientific notation
  136. * @param {string} stringNumber the string representation of the base ten number to be converted
  137. * @param {boolean} parseAsFloat if true, the coefficient will be always parsed as a float, regardless of whether a decimal point is present
  138. * @returns {ScientificNotation} the object containing the number's coefficient and order of magnitude
  139. */
  140. function convertNumberToScientificNotation(stringNumber, parseAsFloat) {
  141. const splitNumber = stringNumber.split("e");
  142. const originalCoefficient = splitNumber[0];
  143. const normalizedNumber =
  144. parseAsFloat || stringNumber.includes(".")
  145. ? normalizeFloat(originalCoefficient)
  146. : normalizeInteger(originalCoefficient);
  147. if (splitNumber.length > 1) {
  148. normalizedNumber.magnitude += parseInt(splitNumber[1], 10);
  149. }
  150. return normalizedNumber;
  151. }
  152. /**
  153. * Checks that the user-intended base ten number equals the actual number after is has been converted to the Number type
  154. * @param {Node} node the node being evaluated
  155. * @returns {boolean} true if they do not match
  156. */
  157. function baseTenLosesPrecision(node) {
  158. const rawNumber = getRaw(node).toLowerCase();
  159. const normalizedRawNumber = convertNumberToScientificNotation(
  160. rawNumber,
  161. false,
  162. );
  163. const requestedPrecision = normalizedRawNumber.coefficient.length;
  164. if (requestedPrecision > 100) {
  165. return true;
  166. }
  167. const storedNumber = node.value.toPrecision(requestedPrecision);
  168. const normalizedStoredNumber = convertNumberToScientificNotation(
  169. storedNumber,
  170. true,
  171. );
  172. return (
  173. normalizedRawNumber.magnitude !== normalizedStoredNumber.magnitude ||
  174. normalizedRawNumber.coefficient !== normalizedStoredNumber.coefficient
  175. );
  176. }
  177. /**
  178. * Checks that the user-intended number equals the actual number after is has been converted to the Number type
  179. * @param {Node} node the node being evaluated
  180. * @returns {boolean} true if they do not match
  181. */
  182. function losesPrecision(node) {
  183. return isBaseTen(node)
  184. ? baseTenLosesPrecision(node)
  185. : notBaseTenLosesPrecision(node);
  186. }
  187. //------------------------------------------------------------------------------
  188. // Rule Definition
  189. //------------------------------------------------------------------------------
  190. /** @type {import('../types').Rule.RuleModule} */
  191. module.exports = {
  192. meta: {
  193. type: "problem",
  194. dialects: ["typescript", "javascript"],
  195. language: "javascript",
  196. docs: {
  197. description: "Disallow literal numbers that lose precision",
  198. recommended: true,
  199. url: "https://eslint.org/docs/latest/rules/no-loss-of-precision",
  200. },
  201. schema: [],
  202. messages: {
  203. noLossOfPrecision:
  204. "This number literal will lose precision at runtime.",
  205. },
  206. },
  207. create(context) {
  208. return {
  209. Literal(node) {
  210. if (node.value && isNumber(node) && losesPrecision(node)) {
  211. context.report({
  212. messageId: "noLossOfPrecision",
  213. node,
  214. });
  215. }
  216. },
  217. };
  218. },
  219. };