Skip to content

js_parser: reject a modifier or an escape in front of a class static block - #44909

Open
robobun wants to merge 1 commit into
robobun/8c5073b9/reject-decorator-on-static-blockfrom
robobun/2f492a0a/static-block-first-token
Open

robobun wants to merge 1 commit into
robobun/8c5073b9/reject-decorator-on-static-blockfrom
robobun/2f492a0a/static-block-first-token

Conversation

@robobun

@robobun robobun commented Oct 10, 2026 •

Copy link
Copy Markdown
Collaborator

Stacked on #44883. The diff is against its branch.

Problem

  • After a modifier or an escape, static before { is a member name. Bun runs class A { async static {} }, static static {} and st\u0061tic {}. V8 and JSC throw SyntaxError: Unexpected token '{'.
  • TypeScript: public static {} runs the block and declare static {} deletes it.
  • Cause: the static block arm (src/js_parser/parse/parse_property.rs:671) tests only { and the name.

Fix

  • parse_class stores the start of each class member in PropertyOpts::member_start. The arm takes the block only if static ends six characters after it: first token, no escape.
  • Else one error: Expected "(" but found "{" after async, Modifiers cannot appear here in TypeScript, Expected ";" but found "{" otherwise. A decorator keeps the error of js_parser: reject a decorator on a class static block, keep decorators out of the body of declare global #44883.
  • Verified: test/bundler/transpiler/transpiler.test.js (28 tests fail on the base). bun check output is byte-identical.
  • Self-reviewed: 6 concerns raised, 5 addressed. Not taken: keep declare_range beside the new field (+2 instructions per object property).

Background

  • ClassStaticBlock is static { } with nothing before it. A modifier restarts the parse_property loop, so the arm cannot see it.
  • Considered a flag test in the arm (misses declare and 5 keywords) and a flag per modifier arm (6 writers).

Downsides

  • Stricter than esbuild, which rejects only async static {}. node 26, tsc, Babel, SWC and oxc reject them all. No user reported this. 0 uses in 19,470 TypeScript files.
  • TypeScript public⏎ static {} is an error too: the keyword is a modifier there until Follow tsc's same-line rule for TS class member and parameter modifiers #38706.
  • Release build: 0 instructions per JavaScript property or class member, +3 per TypeScript class member, 256 bytes less.
Notes

The decision this needs. For JavaScript every engine rejects these spellings, and esbuild rejects async static {}. esbuild accepts static static {}, st\u0061tic {} and a TypeScript modifier before static {. This PR rejects them. If that is too strict, the change shrinks to async static {}.

What each spelling reports. One error, then the parse stops. The block body is not parsed.

In the class body .js .ts
async static {}, static async static {} Expected "(" but found "{" same
static static {}, static⏎static {}, static static⏎{} Expected ";" but found "{" Modifiers cannot appear here
st\u0061tic {} Expected ";" but found "{" same
public / private / protected / readonly / override / declare / abstract static {}, and stacks of them not TypeScript Modifiers cannot appear here, at the first modifier
any of them after a decorator Decorators are not valid here (#44883) same

These stay valid, and test/bundler/transpiler/transpiler.test.js pins their output: static⏎{}, /* a */ static /* b */ {}, static static⏎static {}, async⏎static {}, static async⏎static {}, accessor⏎static {}, st\u0061tic⏎static {}, async static() {} static {}, and in TypeScript declare⏎static {}, abstract⏎static {}, static?: T; static {}, and a block after an index signature or an overload.

References.

  • ECMA-262: ClassStaticBlock : static { ClassStaticBlockBody } has no modifier, and a keyword terminal has no escape.
  • V8 (node 26.3.0) and JSC (indirect eval in Bun) throw for every JavaScript spelling above. JSC says Expected an opening '(' before a async method's parameter list or Expected a ';' following a class field.
  • node 26 type stripping, on .ts: Modifiers cannot appear here for 6 of the 7 TypeScript modifiers and for static static {} (another error for override), Expected '(', got '{' for async static {}.
  • tsc 6.0.2: TS1184 Modifiers cannot appear here. from the checker, TS1260 for the escape. Its emit keeps the block. ts.transpileModule reports nothing for the modifiers.
  • Babel: Static class blocks cannot have any modifier. SWC: TS1184. oxc: modifiers_cannot_appear_here.
  • esbuild 0.21.5 and main: rejects async static {} (Expected "(" but found "{"). It accepts static static {}, the escape and the 5 TypeScript keywords, and deletes the block after declare or abstract. It has no test for these.

How it relates to #44883. That PR tests opts.ts_decorators in the arm. A decorator is also a token before static, so the position test covers it. This PR replaces the decorator test with the position test and moves the Decorators are not valid here error, with its position, into the cold function. scope-mismatch-panic.test.ts passes unchanged (87 pass, 6 todo). The cache version goes from 35 to 36.

Measurements. Release builds of the base (#44883, 8d74cc4) and of this PR, same machine.

  • size_of::<PropertyOpts>(): 48 B -> 40 B (array length mismatch under cargo check -p bun_js_parser).

  • PropertyOpts init stores: class member 9 -> 9 (base: 8 into the struct and 1 for the first_decorator_loc slot), object-literal property 7 -> 7 (llvm-objdump, P<false, false>).

  • Instructions executed inside parse_property and parse_class, per unit, base -> PR. Method: qemu-x86_64 10.0.13 user mode, one instruction per translation block, the exec trace filtered to the address range of each function, (count for 2,000 units - count for 1,000 units) / 1,000. The count is the same on each run.

    Unit parse_class parse_property
    JavaScript class member m() {} 149 -> 149 399 -> 399
    JavaScript object property a: 1 247 -> 247
    JavaScript object method m() {} 382 -> 382
    TypeScript class field g = 1 145 -> 149 329 -> 328
    TypeScript class field private g = 1 145 -> 149 466 -> 465
    class A { static {} } 334 -> 329 237 -> 242
    class A { } 166 -> 161

    One transform executes about 3,600 instructions per object property and about 3,900 per TypeScript class member, so the TypeScript cost is under 0.1%.

  • node_modules/typescript/lib/typescript.js (9.1 MB), one transform: parse_property executes 5,392,834 instructions on both builds, parse_class 147,562 -> 147,322. The whole process executes 1,129,326,350 -> 1,129,373,887 (+0.004%). Two runs of one binary differ by about 40,000 outside these two functions.

  • Size: parse_property + parse_class over 5 monomorphizations plus the cold function: 75,620 B -> 75,351 B (nm -S). Release bun: .text 65,659,989 B -> 65,659,733 B, .rodata 20,603,628 B on both (size -A).

  • Behaviour: a matrix of 30 prefixes by 22 members (660 JavaScript class bodies) against V8: bun-only accepts 14 -> 0, bun-only rejects 0 -> 0. 37 TypeScript prefix-before-block rows: accepted 30 -> 2 (declare⏎static {} and abstract⏎static {}, a field and a block). The 5 decorated rows report the same error on both builds.

  • bun check: 7 cases (3 from test/cli/check/differential-cases.json, TypeScript's classStaticBlock19 and classStaticBlock20, every modifier, the escape, the line-break forms), 4,383 bytes, 74 diagnostics: 0 bytes differ between the base and the PR.

  • Transpiler cache: a 5 KiB module with static static {} that the base cached exits 1 with the PR. After the version change the first run rewrites 41 of 41 cached modules of a test program, the second run 0.

  • Existing TypeScript: an AST scan of the 19,470 TypeScript files on the machine (116 MB, 52 static blocks) finds 0 static blocks with a modifier.

Why member_start takes the place of declare_range. Nothing writes declare_range, and its one reader (Class fields that use "declare" cannot be initialized) never runs. A build that keeps it beside member_start executes 2 more instructions per object-literal property (parse_prefix stores one more constant) and 2 more per JavaScript class member (149 -> 151). #40817 uses the field and would add it again.

Why the arm reads the lexer. name_range.loc != opts.member_start || raw != b"static" is the same test. It keeps a local alive across Lexer::next() for the arm, and the release build then executes 6 more instructions per object-literal property in parse_property (247 -> 253). After next() the lexer has the end of the previous token (full_start), so the arm needs no local.

TypeScript keywords before a line break. The ordinary build reads public, private, protected, readonly and override as modifiers also before a line break. So public⏎static {} is a modifier before a static block, and static public⏎static {} (valid JavaScript) is an error in a .ts file. The base accepts both and drops the word. tsc reads the word as a field name there, and #38706 makes the ordinary build do the same. With #38706 both spellings are a field and a block.

Tests. In test/bundler/transpiler/transpiler.test.js: 24 rejected spellings (each in a class declaration, a class expression and export default class, with the message and the text the error points at), the scan pass, the valid orders, one arrow body that the parser reads twice, and two spawned processes (the module loader for .mjs, .cjs, .mts and .cts, and bun index.js). test/cli/run/syntax.test.ts times out with a debug build on main, so it has no new rows. Also run with the release build: all of test/bundler/transpiler/, test/bundler/esbuild/ts.test.ts, default.test.ts, bundler_edgecase.test.ts, test/js/bun/transpiler/, test/cli/run/syntax.test.ts (the same results as the base) and test/cli/check (1,062 pass. The 1 failure needs a package that is not installed, on main too).

Not changed. get static {}, set static {}, * static {} and accessor static {} are errors already, with 2 to 4 messages. declare or abstract on a method, accessor or index signature still deletes the member (#40817). async public foo() {} is still accepted.


[human-review] gate passed · iteration 0 · 5 files touched

fails on main (without fix)
ASAN without fix: 28 failed, 22 skipped
$ BUN_DEBUG_QUIET_LOGS=1 bun scripts/build.ts --profile=debug --quiet test "--reporter=junit" "--reporter-outfile=/tmp/pr_gate.xml" test/bundler/transpiler/transpiler.test.js
bun test v1.4.3 (367d939d9)

test/bundler/transpiler/transpiler.test.js:
(pass) Bun.Transpiler > handles errors when parsing macros [24.95ms]
(pass) Bun.Transpiler > normalizes \r\n [13.70ms]
1
(pass) Bun.Transpiler > doesn't hang indefinitely #2746 [10.92ms]
(pass) Bun.Transpiler > property access inlining > bails out with spread [18.18ms]
(pass) Bun.Transpiler > property access inlining > bails out with multiple items [6.20ms]
(pass) Bun.Transpiler > property access inlining > works [6.88ms]
(pass) Bun.Transpiler > property access inlining > works nested [7.07ms]
(pass) Bun.Transpiler > property access inlining > bails out when the array item is an optional chain [145.57ms]
(pass) Bun.Transpiler > property access inlining > bails out or strips `this` when the index is a call/assignment target [61.53ms]
(pass) Bun.Transpiler > property access inlining > preserves runtime semantics when inlining from a literal index [847.98ms]
(pass) Bun.Transpiler > property access inlining > bails out on opti
... (truncated)

release without fix: 22 skipped
bun test v1.4.3-canary.1 (1cd9930d7)

test/bundler/transpiler/transpiler.test.js:
(pass) Bun.Transpiler > handles errors when parsing macros [0.35ms]
(pass) Bun.Transpiler > normalizes \r\n [0.45ms]
1
(pass) Bun.Transpiler > doesn't hang indefinitely #2746 [0.23ms]
(pass) Bun.Transpiler > property access inlining > bails out with spread [0.24ms]
(pass) Bun.Transpiler > property access inlining > bails out with multiple items [0.17ms]
(pass) Bun.Transpiler > property access inlining > works [0.06ms]
(pass) Bun.Transpiler > property access inlining > works nested [0.05ms]
(pass) Bun.Transpiler > property access inlining > bails out when the array item is an optional chain [1.94ms]
(pass) Bun.Transpiler > property access inlining > bails out or strips `this` when the index is a call/assignment target [0.62ms]
(pass) Bun.Transpiler > property access inlining > preserves runtime semantics when inlining from a literal index [27.45ms]
(pass) Bun.Transpiler > property access inlining > bails out on optional-chain index into enum [1.87ms]
(pass) Bun.Transpiler > property access inlining > template literal around an inlined string enum member > member as the first part of the
... (truncated)
passes on PR (with fix)
ASAN with fix: 22 skipped
$ BUN_DEBUG_QUIET_LOGS=1 bun scripts/build.ts --profile=debug --quiet test "--reporter=junit" "--reporter-outfile=/tmp/pr_gate.xml" test/bundler/transpiler/transpiler.test.js
bun test v1.4.3 (367d939d9)

test/bundler/transpiler/transpiler.test.js:
(pass) Bun.Transpiler > handles errors when parsing macros [15.04ms]
(pass) Bun.Transpiler > normalizes \r\n [19.49ms]
1
(pass) Bun.Transpiler > doesn't hang indefinitely #2746 [11.19ms]
(pass) Bun.Transpiler > property access inlining > bails out with spread [19.28ms]
(pass) Bun.Transpiler > property access inlining > bails out with multiple items [5.62ms]
(pass) Bun.Transpiler > property access inlining > works [6.73ms]
(pass) Bun.Transpiler > property access inlining > works nested [6.32ms]
(pass) Bun.Transpiler > property access inlining > bails out when the array item is an optional chain [115.12ms]
(pass) Bun.Transpiler > property access inlining > bails out or strips `this` when the index is a call/assignment target [61.12ms]
(pass) Bun.Transpiler > property access inlining > preserves runtime semantics when inlining from a literal index [676.15ms]
(pass) Bun.Transpiler > property access inlining > bails out on opti
... (truncated)

release with fix: 22 skipped
$ bun scripts/build.ts --profile=release
[configured] bun-profile → bun (stripped) in 3022ms (unchanged)
ninja: Entering directory `/workspace/bun/build/release'
[1/94] gen generated_host_exports.rs
generated_host_exports.rs: 120 exports (host=5, lazy=10, generic=105, rust=0); 248 extern-C blocks audited
[2/93] build.rs build_script_build
[3/93] rustc bun_platform 
[4/93] rustc bun_core 
[5/93] rustc bun_zlib_sys 
[6/93] rustc bun_output 
[7/93] rustc bun_safety 
[8/93] rustc bun_brotli 
[9/93] rustc bun_boringssl_sys 
[10/93] rustc bun_zstd 
[11/93] rustc bun_base64 
[12/93] rustc bun_picohttp 
[13/93] rustc bun_cares_sys 
[14/93] rustc bun_lsquic_sys 
[15/93] rustc bun_ptr 
[16/93] rustc bun_errno 
[17/93] rustc bun_clap 
[18/93] rustc bun_valkey 
[19/93] rustc bun_tcc_sys 
[20/93] rustc bun_shell_parser 
warning: `feature(generic_const_exprs)` is not supported with the next-generation trait solver
 --> src/shell_parser/lib.rs:1:30
  |
1 | #![feature(adt_const_params, generic_const_exprs, allocator_api)]
  |                              ^^^^^^^^^^^^^^^^^^^
  |
  = note: `-Znext-solver=globally` is currently enabled by default for testing
  = note: reverted the s
... (truncated)
diff hotspot
src/js_parser/parse/mod.rs                 |  10 +-
 src/js_parser/parse/parse_property.rs      |  55 +++++---
 src/js_parser/parser.rs                    |   5 +-
 src/jsc/RuntimeTranspilerCache.rs          |   4 +-
 test/bundler/transpiler/transpiler.test.js | 199 +++++++++++++++++++++++++++++
 5 files changed, 248 insertions(+), 25 deletions(-)

gate history · 1 passed · 0 rejected · iteration 0

evidence per changed file
file                                        reads  edits  tests
src/js_parser/parse/mod.rs                      1      1     30
src/js_parser/parse/parse_property.rs           5      5     32
src/js_parser/parser.rs                         1      1     29
src/jsc/RuntimeTranspilerCache.rs               1      2     31
test/bundler/transpiler/transpiler.test.js      3      7     29

…block

After a modifier, or written with an escape, `static` before `{` is the
name of a method or of a field. The parser took it as a static block
and dropped what came before it, so programs that every engine rejects
ran:

    class A { async static {} }
    class A { static static {} }
    class A { st\u0061tic {} }

In a TypeScript file `public`, `private`, `protected`, `readonly` and
`override` were dropped the same way, and `declare` and `abstract`
deleted the block.

`parse_class` stores the position of the first token of the class
element in `PropertyOpts::member_start`. It takes the slot of
`declare_range`, which nothing wrote. The static block arm of
`parse_property` accepts the block only if the word ends six characters
after that position: the word is then the first token and has no
escape. Otherwise it reports one error and stops:

- with a decorator: `Decorators are not valid here`, as before
- after `async`: `Expected "(" but found "{"`
- in a TypeScript file, after a modifier: `Modifiers cannot appear here`
- otherwise: `Expected ";" but found "{"`

This one test replaces the test for a decorator in the arm.

`bun check` is not changed: its checker reports these (1184, 1206,
1260).
@robobun

robobun commented Oct 10, 2026 •

Copy link
Copy Markdown
Collaborator Author
Updated 1:43 AM PT - Oct 10th, 2026

✅ @robobun, your commit 6e415884d31d25f1415a1c19158558153af7a7f8 passed in Build #124266! 🎉


🧪   To try this PR locally:

bunx bun-pr 44909

That installs a local version of the PR into your bun-44909 executable, so you can run:

bun-44909 --bun

@robobun

robobun commented Oct 10, 2026

Copy link
Copy Markdown
Collaborator Author

Status: ready for review. This PR is stacked on #44883.

How I reproduced it, on main (e655c58) and on 1.4.3-canary. Each line is a whole .js file. Bun prints block and exits 0. node 26.3.0 throws SyntaxError: Unexpected token '{'.

class A { async static { console.log('block') } }
class A { static static { console.log('block') } }
class A { st\u0061tic { console.log('block') } }

In a .ts file, class A { public static { console.log('block') } } prints block, and class A { declare static { console.log('block') } } prints nothing.

With this branch each file reports one syntax error and exits 1. The test is test/bundler/transpiler/transpiler.test.js (a class static block is the first token of its class element).

@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.

Nothing blocking. The comments below are optional suggestions. There is no need to push a fix for them before merging.

Comment on lines 684 to 689
if !p.is_tolerant()
&& let Some(decorator) = opts.ts_decorators.slice().first()
&& p.lexer.full_start().start
!= opts.member_start.start + b"static".len() as i32
{
p.log().add_error(
Some(p.source),
p.real_loc(decorator.loc),
b"Decorators are not valid here",
);
p.static_block_is_not_first_token(opts, name_range.loc);
return Err(crate::Error::SyntaxError);

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.

🟡 (optional) TypeScript users whose class has a field named public, private, protected, readonly or override on its own line, followed by a static block, now get a SyntaxError where the base ran the block. tsc accepts public\nstatic {} as a field plus a block (the keyword is a modifier only on the same line), but the TS keyword arm at parse_property.rs:654-658 skips its newline check outside tolerant mode, so the new position test at parse_property.rs:685 fails and reports "Modifiers cannot appear here". Fix: treat these five keywords as a member name when a line break follows them in every mode, as the declare and abstract arms already do at parse_property.rs:573 and :604, so the block is the next element and the field is kept. [also at: src/js_parser/parse/parse_property.rs:690 - TypeScript users whose class has a bare public (or private/protected/readonly/override) field on its own line right before static {} now get "Modifiers cannot appear here" where the base ran the block and tsc reports nothing.]

Why this was flagged

Input: a .ts/.tsx/.mts/.cts class body public\nstatic { ... } (or private/protected/readonly/override in place of public) through the module loader, Bun.Transpiler or bun build. tsc's nextTokenCanFollowModifier requires these keywords to be followed on the same line, so tsc parses a field public and then a ClassStaticBlock and emits public;\nstatic { ... }. In Bun the arm at src/js_parser/parse/parse_property.rs:654-658 only applies the newline check when p.is_tolerant(), so in a normal parse public is pushed as a modifier and the loop restarts at static. The static-block arm at src/js_parser/parse/parse_property.rs:684-689 now compares p.lexer.full_start().start with opts.member_start.start + 6; member_start is the public token, so the test fails and static_block_is_not_first_token at src/js_parser/parse/parse_property.rs:1227-1231 logs "Modifiers cannot appear here" and the parse returns Err(SyntaxError). On the base the arm accepted the block and printed static { ... } (the public field was dropped, but the block ran).

Verification: Outside tolerant mode the is_tolerant() term at src/js_parser/parse/parse_property.rs:654-658 is false, so the newline is ignored and public is consumed as a modifier (continue 'restart). So static_block_is_not_first_token runs and logs "Modifiers cannot appear here" at public (lines 1225-1230), and the arm returns Err(SyntaxError). Input that loaded on the base (and is valid per tsc) now fails with a hard SyntaxError.

@robobun

robobun commented Oct 10, 2026

Copy link
Copy Markdown
Collaborator Author

The finding about public⏎static {} is correct. It is the second Downsides bullet of this PR.

The ordinary build reads public, private, protected, readonly and override as modifiers also before a line break. With that reading, public⏎static {} is a modifier in front of a static block, so it is an error here. node 26 rejects it for the same reason.

The suggested fix is #38706: one condition in the keyword arm. #38706 merges with main as it is. With it, public⏎static {} and static public⏎static {} are a field and a block with this PR too, and this PR needs no change. The first shape of this branch had that condition and tests for both spellings.

The condition is not in this PR for two reasons:

If a maintainer prefers one PR, I can add the condition here and close #38706.

This branch has not been deployed

No deployments
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