Skip to content

fix(parser): improve radix literal rounding - #18420

Merged
nicolo-ribaudo merged 5 commits into
babel:mainfrom
JLHwung:fix-parser-radix-literal-rounding
Oct 29, 2026
Merged

nicolo-ribaudo merged 5 commits into
babel:mainfrom
JLHwung:fix-parser-radix-literal-rounding

Conversation

@JLHwung

@JLHwung JLHwung commented Oct 26, 2026

Copy link
Copy Markdown
Contributor
Q                       A
Fixed Issues? Babel parser incorrectly double-round literal digit when the number is larger than Number.MAX_SAFE_INTEGER.
Patch: Bug Fix? Yes
Major: Breaking Change?
Minor: New Feature?
Tests Added + Pass? Yes
Documentation PR Link
Any Dependency Changes?
Need backport? Yes
License MIT

In this PR we fix an issue reported by Claude Fable: readInt double round the number when the running total exceeds Number.MAX_SAFE_INTEGER due to the accumulation step. To fix that we have to reparse the value with parseInt.

`readInt` accumulates the literal digit by digit in a double, so once the
running total exceeds `Number.MAX_SAFE_INTEGER` every further step is
rounded again. `0x1000000000000081` ends up as 2^60 instead of 2^60+256,
whereas NumericValue (#sec-numericvalue) requires 𝔽(MV), i.e. a single
roundTiesToEven conversion of the exact mathematical value.

When the accumulated value is not exactly representable, recompute it with
`parseInt`, which the spec requires to be exact for radixes 2, 8 and 16.

Assisted-by: Claude Fable 5.1 <[email protected]>
With errorRecovery, readInt reads an invalid digit (2-9 in binary, 8-9 in
octal) as 0 and continues, but parseInt stops at it: `0b2` followed by 60
ones became NaN, and a trailing invalid digit truncated the literal.
Replace invalid digits with 0 before calling parseInt so large literals
recover the same way small ones do.

Also fix the `val` null check flagged by tsc, and share the
separator-stripped digits between the BigInt and Number paths.

Assisted-by: Claude Opus 5.5 <[email protected]>
@JLHwung JLHwung added PR: Bug Fix 🐛 A type of pull request used for our changelog categories pkg: parser labels Oct 26, 2026
@babel-bot

babel-bot commented Oct 26, 2026 •

Copy link
Copy Markdown
Collaborator

Build successful! You can test your changes in the REPL here: https://babeljs.io/repl/build/62654

@pkg-pr-new

pkg-pr-new Bot commented Oct 26, 2026 •

Copy link
Copy Markdown

Open in StackBlitz

commit: 8c77d45

@JLHwung
JLHwung requested a review from liuxingbaoyu October 27, 2026 20:35
@liuxingbaoyu

Copy link
Copy Markdown
Member

AI helped me perform a performance check and attempt some optimizations, please take a look.
Feel free to commit directly. :)

Node.js 26.1.0, full parsing including AST construction, median of 12 rounds.
Times are in milliseconds. Negative percentages indicate reduced execution time.

Workload Before PR Original PR New Implementation PR vs. Before New vs. Before
Decimal integers ×10,000 9.214 9.301 6.969 +0.9% −24.4%
Fractions / exponents ×10,000 10.864 10.719 7.776 −1.3% −28.4%
Large decimal integers ×5,000 4.330 4.351 3.821 +0.5% −11.8%
Small radix integers ×10,000 5.798 6.353 4.888 +9.6% −15.7%
Large binary integers ×5,000 4.842 6.423 4.752 +32.6% −1.9%
Large octal integers ×5,000 5.255 9.931 5.532 +89.0% +5.3%
Large hexadecimal integers ×5,000 3.417 4.535 3.781 +32.7% +10.7%
Mixed BigInt literals ×5,000 4.428 4.419 3.683 −0.2% −16.8%
Decimal literals with separators ×10,000 8.449 8.292 7.849 −1.9% −7.1%
Mixed numeric literals ×10,000 8.092 8.200 6.637 +1.3% −18.0%
41 TypeScript source files 65.304 65.322 66.289 0.0% +1.5%
10 JavaScript test files 1.141 1.174 1.130 +2.9% −1.0%
diff --git a/packages/babel-parser/src/tokenizer/index.ts b/packages/babel-parser/src/tokenizer/index.ts
index 304657b26e..565c51d376 100644
--- a/packages/babel-parser/src/tokenizer/index.ts
+++ b/packages/babel-parser/src/tokenizer/index.ts
@@ -1181,13 +1181,42 @@ export default abstract class Tokenizer extends CommentsParser {
     return n;
   }
 
+  readLiteralInt(radix: number): number | null {
+    let pos = this.state.pos;
+    let val = 0;
+    let code: number;
+    for (;;) {
+      code = this.input.charCodeAt(pos);
+      let digit: number;
+      if (code >= charCodes.digit0 && code <= charCodes.digit9) {
+        digit = code - charCodes.digit0;
+      } else {
+        digit = (code | 0x20) - charCodes.lowercaseA;
+        if (digit < 0 || digit > 5) break;
+        digit += 10;
+      }
+      if (digit >= radix) break;
+      val = val * radix + digit;
+      ++pos;
+    }
+    if (
+      code === charCodes.underscore ||
+      (code >= charCodes.digit0 && code <= charCodes.digit9)
+    ) {
+      return this.readInt(radix);
+    }
+    if (pos === this.state.pos) return null;
+    this.state.pos = pos;
+    return val;
+  }
+
   readRadixNumber(radix: number): void {
     const start = this.state.pos;
     const startLoc = this.state.curPosition();
-    let isBigInt = false;
 
     this.state.pos += 2; // 0x
-    const val = this.readInt(radix);
+    let val = this.readLiteralInt(radix);
+    const end = this.state.pos;
     if (val == null) {
       this.raise(
         Errors.InvalidDigit,
@@ -1198,21 +1227,28 @@ export default abstract class Tokenizer extends CommentsParser {
         },
       );
     }
-    const next = this.input.charCodeAt(this.state.pos);
-
-    if (next === charCodes.lowercaseN) {
-      ++this.state.pos;
-      isBigInt = true;
-    }
+    const isBigInt =
+      this.input.charCodeAt(this.state.pos) === charCodes.lowercaseN;
+    if (isBigInt) ++this.state.pos;
 
     if (isIdentifierStart(this.codePointAtPos(this.state.pos))) {
       throw this.raise(Errors.NumberIdentifier, this.state.curPosition());
     }
 
-    if (isBigInt) {
-      const str = this.input.slice(start, this.state.pos).replace(/[_n]/g, "");
-      this.finishToken(tt.bigint, str);
-      return;
+    if (isBigInt || (val !== null && val > Number.MAX_SAFE_INTEGER)) {
+      const str = this.input.slice(start, end).replaceAll("_", "");
+      if (isBigInt) {
+        this.finishToken(tt.bigint, str);
+        return;
+      }
+
+      // Reparse the original digits to round once instead of at each step.
+      // Preserve readInt's invalid-digit recovery before conversion.
+      val = Number(
+        radix !== 16 && this.optionFlags & OptionFlags.ErrorRecovery
+          ? str.replace(radix === 2 ? /[2-9]/g : /[89]/g, "0")
+          : str,
+      );
     }
 
     this.finishToken(tt.num, val);
@@ -1224,12 +1260,9 @@ export default abstract class Tokenizer extends CommentsParser {
     const start = this.state.pos;
     const startLoc = this.state.curPosition();
     let isFloat = false;
-    let isBigInt = false;
     let isOctal = false;
 
-    if (!startsWithDot && this.readInt(10) === null) {
-      this.raise(Errors.InvalidNumber, this.state.curPosition());
-    }
+    const integerValue = startsWithDot ? 0 : this.readLiteralInt(10)!;
     const hasLeadingZero =
       this.state.pos - start >= 2 &&
       this.input.charCodeAt(start) === charCodes.digit0;
@@ -1248,13 +1281,13 @@ export default abstract class Tokenizer extends CommentsParser {
           );
         }
       }
-      isOctal = hasLeadingZero && !/[89]/.test(integer);
+      isOctal = !/[89]/.test(integer);
     }
 
     let next = this.input.charCodeAt(this.state.pos);
     if (next === charCodes.dot && !isOctal) {
       ++this.state.pos;
-      this.readInt(10);
+      this.readLiteralInt(10);
       isFloat = true;
       next = this.input.charCodeAt(this.state.pos);
     }
@@ -1267,30 +1300,41 @@ export default abstract class Tokenizer extends CommentsParser {
       if (next === charCodes.plusSign || next === charCodes.dash) {
         ++this.state.pos;
       }
-      if (this.readInt(10) === null) {
+      if (this.readLiteralInt(10) === null) {
         this.raise(Errors.InvalidOrMissingExponent, startLoc);
       }
       isFloat = true;
       next = this.input.charCodeAt(this.state.pos);
     }
 
-    // remove "_" for numeric literal separator. It should not include "n" for bigint literal
-    const str = this.input.slice(start, this.state.pos).replaceAll("_", "");
+    const end = this.state.pos;
+    const isBigInt = next === charCodes.lowercaseN;
 
-    if (next === charCodes.lowercaseN) {
+    if (isBigInt) {
       // disallow floats, legacy octal syntax and non octal decimals
       // new style octal ("0o") is handled in this.readRadixNumber
       if (isFloat || hasLeadingZero) {
         this.raise(Errors.InvalidBigIntLiteral, startLoc);
       }
       ++this.state.pos;
-      isBigInt = true;
     }
 
     if (isIdentifierStart(this.codePointAtPos(this.state.pos))) {
       throw this.raise(Errors.NumberIdentifier, this.state.curPosition());
     }
 
+    if (
+      !isFloat &&
+      !isBigInt &&
+      !hasLeadingZero &&
+      integerValue <= Number.MAX_SAFE_INTEGER
+    ) {
+      this.finishToken(tt.num, integerValue);
+      return;
+    }
+
+    // Exclude the bigint suffix and remove numeric separators before conversion.
+    const str = this.input.slice(start, end).replaceAll("_", "");
     if (isBigInt) {
       this.finishToken(tt.bigint, str);
       return;

liuxingbaoyu and others added 2 commits October 28, 2026 10:14
Add `readLiteralInt`, which scans plain digits without the separator and
error handling of `readInt`, and falls back to `readInt` when it meets a
`_` or an out-of-range digit. Decimal integers up to 2^53 - 1 now reuse
the accumulated value instead of re-parsing the source text, and large
radix literals are converted with `Number()` so they are rounded once.

From babel#18420 (comment)
`readNumber` is only called at a digit or at a `.` followed by a digit,
so reading the integer part never fails, and the check raising
`InvalidNumber` was removed with the `readLiteralInt` fast path.

Assisted-by: Claude Opus 5.5
@JLHwung

JLHwung commented Oct 28, 2026

Copy link
Copy Markdown
Contributor Author

Thank you, the attached diff looks good to me and I have pushed to this branch, plus a cleanup.

@nicolo-ribaudo
nicolo-ribaudo merged commit 0553104 into babel:main Oct 29, 2026
57 of 58 checks passed
@nicolo-ribaudo
nicolo-ribaudo deleted the fix-parser-radix-literal-rounding branch October 29, 2026 14:36
@babel-bot

Copy link
Copy Markdown
Collaborator

Backported to 7.x in #18445.

brandhaug added a commit to brandhaug/b2b-saas-starter that referenced this pull request Nov 2, 2026
## pnpm-workspace.yaml (default)

## Dependency Updates

| Package | From | To | Type |
| --- | --- | --- | --- |
| `@babel/core` | 8.0.9 | 8.0.10 | patch |
| `@inlang/plugin-message-format` | 4.5.5 | 4.5.6 | patch |
| `@tanstack/devtools-vite` | 0.8.5 | 0.8.6 | patch |
| `ai` | 7.0.156 | 7.0.157 | patch |
| `cn` | 0.5.0 | 0.5.1 | patch |
| `seroval` | 1.7.4 | 1.7.5 | patch |

## Release Notes

<details>
<summary><b>@<!---->babel/core</b> (8.0.9 → 8.0.10)</summary>

## v8.0.10 (2026-10-29)

Thanks @<!---->dagemawinegash, @<!---->nyan-left,
@<!---->saiyam-jain-dev, and @<!---->yulman2207 for your first PRs!

#### 🐛 Bug Fix
* `babel-parser`
* [#18420](babel/babel#18420) fix(parser):
improve radix literal rounding
([@<!---->JLHwung](https://github.com/JLHwung))
* [#18372](babel/babel#18372) fix(parser): allow
parenthesized assignment target in arrow initializer
([@<!---->JLHwung](https://github.com/JLHwung))
* [#18410](babel/babel#18410) fix(parser): do
not record strict mode errors during lookahead
([@<!---->JLHwung](https://github.com/JLHwung))
* [#18433](babel/babel#18433) fix(parser):
invalid expectOnePlugin usage
([@<!---->JLHwung](https://github.com/JLHwung))
* [#18409](babel/babel#18409) fix(parser):
handle ASI after let followed by a reserved word on the next line
([@<!---->JLHwung](https://github.com/JLHwung))
* [#18406](babel/babel#18406) fix(parser):
parser should not crash for `import defer {}`
([@<!---->JLHwung](https://github.com/JLHwung))
* [#18407](babel/babel#18407) fix(parser):
record start location in `startNodeAt`
([@<!---->JLHwung](https://github.com/JLHwung))
* `babel-plugin-transform-block-scoping`
* [#18371](babel/babel#18371) fix: closures in
for-loop test and update capture wrong binding
([@<!---->joellemd](https://github.com/joellemd))
* `babel-generator`
* [#18418](babel/babel#18418) fix(generator):
keep aliases of string-literal module specifiers
([@<!---->JLHwung](https://github.com/JLHwung))
* [#18427](babel/babel#18427) Fix missing
parentheses around TypeScript assertion targets
([@<!---->dagemawinegash](https://github.com/dagemawinegash))
* [#18324](babel/babel#18324) fix: invalid
`minified: true` output for new expression
([@<!---->JLHwung](https://github.com/JLHwung))
  * [#18437](https://github.

…[full notes](https://github.com/babel/babel/releases/tag/v8.0.10)

</details>

<details>
<summary><b>@<!---->tanstack/devtools-vite</b> (0.8.5 → 0.8.6)</summary>

### Patch Changes

- [#539](TanStack/devtools#539)
[`ed8b314`](TanStack/devtools@ed8b314)
- Source injection no longer stops after the dev server parses a regex
literal. Before this fix, a regex literal cached `value` as a child key
of `Literal` nodes. Every later file with a string literal then threw
during the walk and got zero `data-tsd-source` attributes.

- [#540](TanStack/devtools#540)
[`012421f`](TanStack/devtools@012421f)
- Stop the console pipe feedback loop with Vite 8
`server.forwardConsole`. The server side of the pipe no longer sends
browser logs that Vite printed in the terminal back to the browser.

- [#548](TanStack/devtools#548)
[`40f32e4`](TanStack/devtools@40f32e4)
- Run source injection before the transforms of other plugins (unless
they also use `order: 'pre'`), also when `devtools()` is not first in
the plugins array. Before this fix, a framework plugin that changed the
code of only one environment shifted the line numbers, so
`data-tsd-source` differed between SSR and client and caused hydration
warnings.

- [#541](TanStack/devtools#541)
[`df1464c`](TanStack/devtools@df1464c)
- Fix "Go to Source" for files outside the current working directory,
for example a package in a monorepo or Vite run from another directory.
The editor got a path with the working directory added twice. Also
answer a missing or malformed `source` with `400` instead of leaving the
request pending.

- [#542](TanStack/devtools#542)
[`9c58288`](TanStack/devtools@9c58288)
- Remove the `intent` bin from the published packages. It took over
`node_modules/.bin/i

…[full
notes](https://github.com/TanStack/devtools/releases/tag/%40tanstack/devtools-vite%400.8.6)

</details>

<details>
<summary><b>cn</b> (0.5.0 → 0.5.1)</summary>

### Patch Changes

- [#165](shadcn-ui/cn#165)
[`5e65675`](shadcn-ui/cn@5e65675)
Thanks [@<!---->shadcn](https://github.com/shadcn)! - Group the legacy
`bg-gradient-to-*` utilities as `bg-color`, the same as tailwind-merge.
`cn("bg-background", "bg-gradient-to-r")` now returns
`bg-gradient-to-r`, and `bg-gradient-to-r` no longer replaces
`bg-linear-to-r` or an arbitrary `bg-[...]` image.

</details>

<details>
<summary><b>seroval</b> (1.7.4 → 1.7.5)</summary>

### Patch Changes

- d85ec3f: Keep two round-trip cases intact. An object whose own
`constructor` key holds a falsy value, such as `{ constructor: undefined
}`, now keeps `Object.prototype` instead of coming back with a null
prototype. A null-prototype object with an own `__proto__` key, or any
object serialized with `Feature.ObjectAssign` disabled, no longer turns
equal-looking values such as two `new Set()` into one shared object in
`serialize`, `crossSerialize` and `compileJSON` output.

</details>

---
*This PR was auto-generated by
[catalog-update-action](https://github.com/brandhaug/catalog-update-action).*

Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pkg: parser PR: Bug Fix 🐛 A type of pull request used for our changelog categories

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants