Skip to content

js_parser: skip computed keys in destructured parameters of TypeScript function types - #38890

Closed
robobun wants to merge 1 commit into
mainfrom
farm/d901bc5a/ts-skip-computed-binding-keys
Closed

robobun wants to merge 1 commit into
mainfrom
farm/d901bc5a/ts-skip-computed-binding-keys

Conversation

@robobun

@robobun robobun commented Aug 15, 2026

Copy link
Copy Markdown
Collaborator

Problem

  • A TypeScript function type, constructor type, or interface / type literal method signature whose parameter is destructured with a computed key does not parse:
    let f: ({ [k]: x }: T) => void          // error: Expected ")" but found ":"
    interface I { m({ [k]: x }: T): void }  // error: Unexpected [
    tsc parses both (no parse diagnostics) and erases them. The same pattern in a value position (({ [k]: x }: T) => x), in a declare function, an overload or an abstract method already works in bun, and so do { 1: x } / { 's': x } keys in these exact positions.
  • When the function type sits in an arrow's return type, the failure is silent and the output is wrong: in (b): ({ [k]: v }) => c => e bun gave up on the function type, read ({ [k]: v }) as a parenthesized type literal and c => e as the arrow body, printing (b) => (c) => e. tsc (and bun for the equivalent ({ a: v }) => c => e) print (b) => e.
  • Cause: skip_type_script_binding() in src/js_parser/parse/parse_skip_typescript.rs, the TOpenBrace arm. Its match over member keys handles identifiers, ...rest, string / numeric literals and keywords, but has no [ arm, so a computed key falls into unexpected(). This is the binding skipper used by skip_typescript_fn_args(), which is reached from skip_type_script_paren_or_fn_type (function, constructor and generic function types) and from the method / call / construct signature path in skip_type_script_object_type. The code is ported from esbuild's skipTypeScriptBinding, which has the same gap, so there is nothing upstream to port.

Fix

  • Add a TOpenBracket arm: consume [, skip the key with skip_type_script_type, expect ]. found_identifier stays false, so the existing code then requires : binding after it, which also handles nested patterns ({ [k]: { y } }, { [k]: [y] }).
  • Skipping the key as a type is how skip_type_script_object_type already handles { [k]: T } in type literals. It covers the forms a computed key takes in practice ([k], [a.b.c], [Symbol.iterator], ['k'], [1], [1n], [`${k}`], [keys[0]]), and the accepted set is now identical between the two positions ([k()] stays rejected in both).
  • The expression parser is deliberately not used for the key: this code runs inside try_skip_type_script_arrow_args_with_backtracking, which rewinds only the lexer, and the expression parser pushes scopes and allocates AST nodes that the rewind would leave behind. The type skipper has no such side effects and is already what runs for parameter types on this same path.
  • Parse results only change for inputs that previously failed the function type attempt. A parenthesized type that is not followed by => (({ [k]: a }), ({ [k: string]: a })) still backtracks to the type literal parse exactly as before, because the attempt still fails at the missing => (or, for an index signature, at the : inside the brackets). Inputs followed by => were either errors or the misparse described above, and now resolve the way tsc resolves them, which is also how bun already resolves the same inputs written with a plain key. Verified against tsc 6.0 for every row in the new test.
  • Parameter initializers in these positions (({ x = 1 }: T) => void) are unchanged: they fail before and after for every key form, and tsc reports them as an error (TS2371), so they are a separate question from this one.
  • Verified:
    • test/bundler/transpiler/transpiler.test.js, new test "computed keys in destructuring patterns of function types and method signatures": fails on bun 1.4.0 and on a debug build of main without the src/ change, passes with it.
    • bun bd test on the whole of transpiler.test.js (189 pass, 0 fail) and on esbuild/ts, esbuild/default, decorator-metadata, transpiler-stack-overflow, property (215 pass, 0 fail).
    • Deeply nested inputs through the new arm (300k levels of { [k]: and 20k levels of { [{ [) end in the existing "Maximum call stack size exceeded" error on the ASAN build; both recursion paths already carry a stack check.

Background

  • The TypeScript type skipper (parse_skip_typescript.rs) is the part of the parser that consumes type annotations without building anything for them, since types are erased from the output. It only has to accept what tsc accepts and leave the lexer positioned after the type. skip_type_script_binding is its copy of the destructuring grammar, needed because parameters inside a function type can be patterns (([a, b]: T) => void), and skip_type_script_type is the entry point for a type.
  • ( ... ) => R is ambiguous with a parenthesized type ( T ) until the => is seen. skip_type_script_paren_or_fn_type therefore first tries to skip the whole thing as function parameters plus => with backtracking: the lexer position is snapshotted, errors are muted, and on any failure the lexer is restored and the input is re-read as a parenthesized type. Anything run inside that attempt must have no effect outside the lexer, which is why the key is skipped rather than parsed.
  • A computed key in a destructuring pattern, { [expr]: binding }, takes the property named by the value of expr. In the grammar it is an arbitrary expression; in type-position patterns it is in practice an identifier, a member chain such as Symbol.iterator, or a literal, all of which the type skipper reads as a type reference or a literal type.
Before / after on a few inputs (debug build; tsc 6.0 agrees with every "after" line)
input                                                  before                                   after
let x: ({ [k]: a }: T) => void = Foo                   Expected ")" but found ":"               let x = Foo;
let x: new ({ [k]: a }: T) => void = Foo               Expected ")" but found ":"               let x = Foo;
interface I { m({ [k]: a }: T): void }                 Unexpected [                             (empty)
interface I { new ({ [k]: a }: T): I }                 Unexpected [                             (empty)
let x: ({ [a.b.c]: v, [`${k}`]: w }: T) => void = Foo  Expected ")" but found ":"               let x = Foo;
let x: ({ [k]: { a, [j]: [b, ...c] } }: T) => void     Expected ")" but found ":"               let x;
y = (b): ({ [k]: v }) => c => e                        y = (b) => (c) => e;   (wrong)           y = (b) => e;
y = (b): (({ [k]: v }) => c) => e                      Expected ";" but found ":"               y = (b) => e;
y = (b): ({ [k]: v }) => e                             y = (b) => e;          (tsc: error)      Expected ";" but found ":"
let x: ({ [k]: a }) = Foo                              let x = Foo;                             let x = Foo;   (unchanged)
let x: ({ [k: string]: a }) = Foo                      let x = Foo;                             let x = Foo;   (unchanged)
let x: ({ [k()]: a }: T) => void                       Expected "]" but found "("               Expected "]" but found "("   (unchanged)
let x: ({ [k]: a = 1 }: T) => void                     Unexpected =                             Unexpected =   (unchanged)

The { a: v } spellings of the y = (b): ... rows produce the "after" column on main today; the test asserts both spellings side by side.

… function types

skip_type_script_binding() had no arm for a computed key, so a function
type, constructor type or method signature whose parameter is destructured
with a computed key failed to parse:

    let f: ({ [k]: x }: T) => void       // Expected ")" but found ":"
    interface I { m({ [k]: x }: T): void }

The key is skipped with the type skipper, the same way computed keys in
type literals already are, and is then followed by the usual ": binding".
@coderabbitai

coderabbitai Bot commented Aug 15, 2026

Copy link
Copy Markdown
Contributor

Warning

Review limit reached

@robobun, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 34 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 655abe40-ade7-4a6c-9a0c-6dd93b2eb6ff

📥 Commits

Reviewing files that changed from the base of the PR and between 6324a58 and 044c753.

📒 Files selected for processing (2)
  • src/js_parser/parse/parse_skip_typescript.rs
  • test/bundler/transpiler/transpiler.test.js

Comment @coderabbitai help to get the list of available commands.

@robobun

robobun commented Aug 15, 2026

Copy link
Copy Markdown
Collaborator Author

Status: ready for review.

Reproduced on bun 1.4.0 and on a debug build of main with new Bun.Transpiler({ loader: "ts" }).transformSync("let f: ({ [k]: x }: T) => void") (Expected ")" but found ":") and "interface I { m({ [k]: x }: T): void }" (Unexpected [). tsc parses both.

The new test in test/bundler/transpiler/transpiler.test.js fails without the src/ change and passes with it; the rest of transpiler.test.js and the esbuild/ts, esbuild/default, decorator-metadata, transpiler-stack-overflow and property suites pass with it.

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM — small, well-scoped parser fix with thorough test coverage.

What was reviewed:

  • The new TOpenBracket arm mirrors how skip_type_script_object_type already skips computed keys as types; found_identifier stays false so the existing : binding requirement applies.
  • Backtracking safety: skip_type_script_type::<false> has no scope/AST side effects, and it is already called on this same backtracking path for parameter types, so nothing new is introduced.
  • Stack safety: both recursion entry points (skip_type_script_binding and skip_type_script_type) already carry is_safe_to_recurse checks.
  • Tests cover function/constructor/generic types, method/call/construct signatures, key forms, nesting, the parenthesized-type-literal backtrack, the ambiguous return-type case (with plain-key comparison), and error/unchanged cases.
Extended reasoning...

Overview

Adds a single T::TOpenBracket match arm to skip_type_script_binding()'s TOpenBrace handler in src/js_parser/parse/parse_skip_typescript.rs, so that computed keys ({ [expr]: binding }) in destructured parameters of TypeScript function types, constructor types, and interface/type-literal method signatures are skipped instead of hitting unexpected(). The key is consumed via skip_type_script_type(Level::Lowest), exactly as skip_type_script_object_type already does for computed keys in type literals. A comprehensive test block is added to test/bundler/transpiler/transpiler.test.js.

Security risks

None. This is TypeScript type-annotation skipping — types are erased from output. The change only widens the set of inputs that parse successfully (previously errors) and, in one narrow case, makes an input that silently misparsed now match tsc's parse. No untrusted-size arithmetic, no allocation, no new recursion path without a stack check.

Level of scrutiny

Medium — parser correctness matters, but the change is 5 lines of logic in a well-understood location with a clear precedent in the same file. The key correctness concerns for a change here are (1) backtracking safety and (2) stack-overflow safety, and both hold: skip_type_script_type::<false> is side-effect-free w.r.t. scopes/AST and is already invoked on this exact backtracking path (for parameter type annotations in skip_typescript_fn_args), and both recursive functions already guard with stack_check.is_safe_to_recurse(). The only behavioral change to previously-accepted input (y = (b): ({ [k]: v }) => e now errors) aligns with tsc and with bun's existing handling of the plain-key spelling — the test asserts both spellings side by side.

Other factors

  • Test coverage is unusually thorough: every entry point (let x:, type F =, return type, as cast, generic argument, interface method/call/construct signatures, type-literal method), every practical key form (identifier, member chain, string/number/bigint/template literal, indexed access), nesting, mixing with other member forms, optional/rest parameters, the two backtrack-to-type-literal cases (no =>, index signature), the ambiguous arrow-return-type case with the plain-key control, negative cases (missing binding after computed key), and value-position patterns as a no-regression check.
  • The PR description documents that the test fails on main without the src change and passes with it, that the surrounding suites pass, and that deep-nesting inputs hit the existing stack-overflow guard on the ASAN build.
  • No prior reviewer comments to address; no CODEOWNERS concerns for this file.

@github-actions

Copy link
Copy Markdown
Contributor

Closing this PR because it has been inactive for more than 90 days.

@github-actions github-actions Bot closed this Nov 14, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant