Skip to content

perf(parser): dispatch tokens through handlers which finish the token - #29617

Merged
Boshen merged 1 commit into
mainfrom
perf/parser-token-handlers
Nov 16, 2026
Merged

Boshen merged 1 commit into
mainfrom
perf/parser-token-handlers

Conversation

@Boshen

@Boshen Boshen commented Nov 15, 2026 •

Copy link
Copy Markdown
Member

First of a stack of 7 PRs which cut the work the lexer does for each token and each comment. By the top of the stack (#29623), a full parse of 63,739 real-world files takes 10.8% fewer instructions and 5.6% fewer CPU cycles than on main.

next_token looped over byte handlers until one produced a token, then finished it in finish_next_inner. That reads and resets pending, and checks for flags and for comments to attach, whatever the token is. Most tokens directly follow the previous token, or one space, and need none of it.

next_token now skips one space, completes a single-byte token in place, and otherwise calls a token handler from a second 256-entry table. A token handler takes the position of the first byte of a token and returns the finished Token. Handlers for bytes which only ever start a token without flags (& * ^ ! | + % ?, and . < - = after a look at the next byte) finish it themselves. The others call the byte handler for the same byte and take the existing path, as do whitespace, line breaks and comments.

next_token relies on pending being PendingToken::NONE, which it is not at the start of the source, so parse_expression now reads its first token with first_token_without_hashbang.

In debug builds, which tests and conformance runs are, every token finished this way is lexed again by the byte handler for its first byte, and the two must agree on kind, end, flags and diagnostics.

The table of token handlers is an associated constant of Lexer, as token handlers are generic over the lexer's config and a static cannot be generic. LexerConfig is unchanged. A reference to the constant is to static memory, so getting a handler is one load, as it is from the static tables which LexerConfig::byte_handlers returns. The parser for each config is compiled once, inside oxc_parser, so a binary has one table for each config it uses. A crate which uses Lexer directly, which only the benchmarks can, gets its own copy of the table and of the token handlers.

Instructions retired per parse on macOS arm64, Rust 1.100.0, measured with /usr/bin/time -l over a fixed number of parses. Each figure is the lower of two sets of 3 runs, which differ by up to 0.26% for antd.js and up to 0.16% for the other fixtures; negative is fewer.

Fixture vs main
App.tsx −3.01%
kitchen-sink.tsx −3.17%
RadixUIAdoptionSection.jsx −2.69%
pdf.mjs −3.24%
checker.ts −2.83%
react.development.js −2.54%
binder.ts −2.53%
antd.js −2.46%

The same measurement over 63,739 real-world files (69.6M tokens), sampled from published npm packages and from application and library repositories. Each run also reads the files, so between runs the figure for one kind of file varies by up to 0.4%, and the total by 0.05%:

Files vs main
npm packages, .js −2.78%
npm packages, minified .js −3.07%
npm packages, .d.ts −2.25%
npm packages, .ts −2.53%
repositories, .ts −2.81%
repositories, .tsx / .jsx −2.73%
repositories, .d.ts −2.02%
repositories, .js −3.02%
All −2.75%

CPU cycles. Less of what is saved here shows up as cycles than in the PRs above. On the same 63,739 files, cycles against main are −1.3% at this PR, −2.6% with #29618, −3.6% with #29619, and −5.6% for the whole stack. Two builds of main differ by 0.3% in that measurement.

The lexer benchmark uses Lexer directly, so it runs its own copy of the token handlers, compiled apart from the parser's. It is one tight loop, and its cycle count depends on how the build lays out the code. On an Apple M4 Pro it takes 6.0% fewer instructions at this PR over its five fixtures. With every function aligned to 64 bytes it took 0.7% and 0.8% fewer cycles in two runs. The default build took between 0.7% and 5.5% more in three runs. With #29618 it takes 13.3% fewer instructions, and in the aligned build 4.7% and 5.6% fewer cycles. The default build ranged from 6.6% fewer to 11.5% more.

Benchmark bot. It reports lexer[kitchen-sink.tsx] as 4.5% faster (10 ms to 9.5 ms), lexer[App.tsx] as 3.3% faster (4.5 ms to 4.3 ms) and parser[kitchen-sink.tsx] as 3.2% faster (37.2 ms to 36.1 ms), and no other benchmark as changed. An earlier revision of this PR kept the table in a static for each config, reached through LexerConfig, so the lexer benchmark ran the parser's copy of the handlers. For that revision the bot reported lexer[RadixUIAdoptionSection.jsx] as 6.3% slower, which it no longer does. The parser takes the same number of instructions in both revisions, within 0.05% on every fixture and 0.01% over the real-world files.

Validation: oxc_parser lint, rustdoc and unit tests pass, and cargo coverage parser snapshots are unchanged, at this commit. Tokens, comments and diagnostics are identical to main on the 63,739 files above and on 100,279 files from the conformance suites (Test262, Babel, TypeScript, and the misc fixtures). In debug builds, which include every test and conformance run, each token finished by a token handler is lexed again by the byte handler for its first byte, and the two must agree.

AI-assisted: written with Claude Fable 5.2 (model ID claude-fable-5-2) in Claude Code.

🤖 Generated with Claude Code

@github-actions github-actions Bot added the A-parser Area - JS/TS parsing and syntax errors, oxc_parser label Nov 15, 2026
@Boshen
Boshen added this pull request to stack #29624 November 15, 2026 19:38
@codspeed

codspeed Bot commented Nov 15, 2026 •

Copy link
Copy Markdown
Contributor

Merging this PR will improve performance by 3.65%

⚡ 3 improved benchmarks
✅ 88 untouched benchmarks
⏩ 19 skipped benchmarks1

Performance Changes

Mode Benchmark BASE HEAD Efficiency
⚡ CPU Simulation lexer[kitchen-sink.tsx] 10 ms 9.5 ms +4.51%
⚡ CPU Simulation lexer[App.tsx] 4.5 ms 4.3 ms +3.29%
⚡ CPU Simulation parser[kitchen-sink.tsx] 37.2 ms 36.1 ms +3.15%

Tip

Curious why performance improved? Comment @codspeedbot explain why performance improved on this PR, or directly use the CodSpeed MCP with your agent.


Comparing perf/parser-token-handlers (424024e) with main (a53df45)

Open in CodSpeed

Footnotes

  1. 19 benchmarks were skipped, so the baseline results were used instead. If they were deleted from the codebase, click here and archive them to remove them from the performance reports. ↩

@Boshen
Boshen force-pushed the perf/parser-token-handlers branch from 51d8f49 to e82e4bc Compare November 16, 2026 04:10
@Boshen
Boshen removed this pull request from stack #29624 November 16, 2026 04:11
@Boshen
Boshen changed the base branch from main to refactor/parser-lexer-safe-handlers November 16, 2026 04:11
@Boshen
Boshen added this pull request to stack #29644 November 16, 2026 04:12
@Boshen
Boshen removed this pull request from stack #29644 November 16, 2026 08:46
@Boshen
Boshen changed the base branch from refactor/parser-lexer-safe-handlers to main November 16, 2026 08:47
@Boshen
Boshen force-pushed the perf/parser-token-handlers branch from e82e4bc to 51d8f49 Compare November 16, 2026 08:47
@Boshen
Boshen added this pull request to stack #29663 November 16, 2026 08:47
@Boshen
Boshen force-pushed the perf/parser-token-handlers branch from 51d8f49 to 47a6f5c Compare November 16, 2026 09:10
@Boshen
Boshen marked this pull request as ready for review November 16, 2026 09:24
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 16, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-16T12:24:10.033154Z 424024e New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@Boshen
Boshen force-pushed the perf/parser-token-handlers branch from 47a6f5c to 6558141 Compare November 16, 2026 09:58
`next_token` looped over byte handlers until one produced a token, then
finished it in `finish_next_inner`. That reads and resets `pending`,
and checks for flags and for comments to attach, whatever the token is.
Most tokens directly follow the previous token, or one space, and need
none of it.

`next_token` now skips one space, completes a single-byte token in
place, and otherwise calls a token handler from a second 256-entry
table. A token handler takes the position of the first byte of a token
and returns the finished `Token`. Handlers for bytes which only ever
start a token without flags (`& * ^ ! | + % ?`, and `. < - =` after a
look at the next byte) finish it themselves. The others call the byte
handler for the same byte and take the existing path, as do whitespace,
line breaks and comments.

Token handlers are generic over the lexer's config, so their table is an
associated constant of `Lexer`. `LexerConfig` is unchanged.

`next_token` relies on `pending` being `PendingToken::NONE`, which it
is not at the start of the source, so `parse_expression` now reads its
first token with `first_token_without_hashbang`.

In debug builds, which tests and conformance runs are, every token
finished this way is lexed again by the byte handler for its first
byte, and the two must agree on kind, end, flags and diagnostics.

AI-assisted.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
@Boshen
Boshen force-pushed the perf/parser-token-handlers branch from 6558141 to 424024e Compare November 16, 2026 12:21
@Boshen
Boshen merged commit bb08acb into main Nov 16, 2026
42 checks passed
@Boshen
Boshen deleted the perf/parser-token-handlers branch November 16, 2026 14:12
Boshen added a commit that referenced this pull request Nov 16, 2026
…dler (#29618)

The token handlers for identifier-start bytes called the byte handler
and then `finish_next_inner`. An identifier has no flags unless it
contains an escape, so these handlers now scan the identifier, match
keywords where the first letter can start one, and finish the token
directly.

An identifier which contains a Unicode character or an escape takes one
cold call into the existing code, which finishes it the general way.

Instructions retired per parse on macOS arm64, Rust 1.100.0, measured
with `/usr/bin/time -l` over a fixed number of parses. Each figure is
the lower of two sets of 3 runs, which differ by up to 0.26% for
`antd.js` and up to 0.16% for the other fixtures; negative is fewer.

| Fixture | vs #29617 | Stack so far vs main |
| --- | ---: | ---: |
| App.tsx | −3.45% | −6.36% |
| kitchen-sink.tsx | −3.86% | −6.90% |
| RadixUIAdoptionSection.jsx | −3.36% | −5.96% |
| pdf.mjs | −3.38% | −6.51% |
| checker.ts | −4.07% | −6.79% |
| react.development.js | −3.17% | −5.63% |
| binder.ts | −3.90% | −6.33% |
| antd.js | −2.36% | −4.76% |

The same measurement over 63,739 real-world files (69.6M tokens),
sampled from published npm packages and from application and library
repositories. Each run also reads the files, so between runs the figure
for one kind of file varies by up to 0.4%, and the total by 0.05%:

| Files | vs #29617 | Stack so far vs main |
| --- | ---: | ---: |
| npm packages, `.js` | −3.13% | −5.82% |
| npm packages, minified `.js` | −3.88% | −6.82% |
| npm packages, `.d.ts` | −3.29% | −5.46% |
| npm packages, `.ts` | −3.56% | −6.00% |
| repositories, `.ts` | −2.94% | −5.66% |
| repositories, `.tsx` / `.jsx` | −2.92% | −5.56% |
| repositories, `.d.ts` | −2.80% | −4.76% |
| repositories, `.js` | −3.78% | −6.69% |
| **All** | −3.37% | −6.03% |

CPU cycles on the same 63,739 files are −2.6% against `main` at this PR,
from −1.3% at #29617. Two builds of `main` differ by 0.3% in that
measurement.

Validation: `oxc_parser` lint, rustdoc and unit tests pass, and `cargo
coverage parser` snapshots are unchanged, at this commit. Tokens,
comments and diagnostics are identical to `main` on the 63,739 files
above and on 100,279 files from the conformance suites (Test262, Babel,
TypeScript, and the `misc` fixtures). In debug builds, which include
every test and conformance run, each token finished by a token handler
is lexed again by the byte handler for its first byte, and the two must
agree.

AI-assisted: written with Claude Fable 5.2 (model ID `claude-fable-5-2`)
in Claude Code.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
camc314 added a commit that referenced this pull request Nov 23, 2026
### 💥 BREAKING CHANGES

- f573c93 syntax: [**BREAKING**] Remove `NumberBase` and `BigintBase`
types (#29920) (overlookmotel)
- b90b3aa ast: [**BREAKING**] Remove `base` field from `NumericLiteral`
and `BigIntLiteral` (#29919) (overlookmotel)
- 8c2abc4 diagnostics: [**BREAKING**] Implement `SourceCode` for `&T`
(#29852) (overlookmotel)
- 2bc8e89 diagnostics: [**BREAKING**] `NamedSource` support `&str` as
name (#29851) (overlookmotel)

### 🚀 Features

- 2384875 minifier: Remove redundant `| 0` under bitwise operators
(#29991) (Cameron)
- abf889f minifier: Flatten nested string concatenations (#30015)
(Cameron)
- 5f51bd3 minifier: Fold division with short numeric results (#29994)
(Cameron)
- 1102f24 minifier: Flatten nested untagged template literals (#29993)
(Cameron)
- 12897a0 minifier: Fold switch with one case and default into if-else
(#29990) (Cameron)
- f9e90de minifier: Fold numeric identities like `x - 0` and `x * 1`
(#29926) (Dunqing)
- c265eda minifier,ecmascript: Fold additive zero and safe offsets on
int32/uint32 expressions (#29865) (Andre_Ramirez)
- 37ec2e2 compat: Add standard decorators compatibility data (#29448)
(Dunqing)
- 22e4d0b runtime: Add standard decorator helpers (#29447) (Dunqing)
- a67ac1f data_structures: Add brand types (#29756) (overlookmotel)

### 🐛 Bug Fixes

- 38cd470 transformer: Share auto-accessor lowering and fix its private
storage names (#29449) (Dunqing)
- 6838760 packages/codegen: Parenthesize for-of targets that start with
`let` (#30071) (Cameron)
- 13dd5ac packages/codegen: Parenthesize comma expressions in enum
initializers (#30070) (Cameron)
- c4e4fcc packages/codegen: Parenthesize private `in` checks in for
initializers (#30073) (Cameron)
- 32882ef packages/codegen: Parenthesize comma expressions in export
assignments (#30072) (Cameron)
- 7d8998d packages/codegen: Parenthesize comma expressions in JSX
containers (#30074) (Cameron)
- c98b8b1 packages/codegen: Parenthesize TypeScript instantiation
operands (#30068) (Cameron)
- d615de4 codegen: Parenthesize TypeScript instantiation expressions
used as operands (#30065) (Cameron)
- 90b5af9 codegen: Keep `()` on minified `new` expressions with type
arguments (#30062) (Cameron)
- 4b1efd3 transformer/legacy-decorator: Move class self-references to
alias symbol (#30056) (Dunqing)
- adf284e mangler: Use debug names for private members (#30061)
(Cameron)
- bbe2fba transformer/legacy-decorator: Avoid class name shadowing in
static setters (#30058) (Dunqing)
- 7fa5d50 codegen: Keep comments from ending a line after code (#29814)
(Yuji Sugiura)
- 41dbc08 mangler: Keep names set by redeclarations with keepNames
(#30055) (Dunqing)
- 8921865 transformer/legacy-decorator: Keep static private brand checks
on the original class (#30054) (Dunqing)
- abb3593 transformer/legacy-decorator: Share anonymous default class
bindings (#29753) (Dunqing)
- bbc6772 lexer: Read << as a shift where TypeScript opens no type
arguments (#30051) (Shanon Jackson)
- 52b5506 transformer/class-properties: Preserve names of anonymous
classes (#29931) (Dunqing)
- 8488767 codegen: Parenthesize private `in` tests in `for` initializers
(#30037) (Cameron)
- 395913e parser: Parse `<=` after `as` and `satisfies` (#30028)
(Cameron)
- 9570bc8 parser: Require `class` keyword for decorated class export
(#30027) (Cameron)
- e9e80b1 codegen: Parenthesize for-of heads that print a leading `let`
or `async` (#30025) (Cameron)
- a54befb codegen: Avoid double parentheses around `as`/`satisfies`
for-of heads (#30024) (Cameron)
- 157673a codegen: Parenthesize comma expressions in export assignments
(#30022) (Cameron)
- bedf3f5 codegen: Parenthesize comma expressions in enum initializers
(#30021) (Cameron)
- 11bafb6 codegen: Parenthesize comma expressions in JSX containers
(#30020) (Cameron)
- 967a97c codegen: Print a computed key for renamed `__proto__`
shorthand (#30019) (Cameron)
- 64b7176 minifier: Preserve throwing `String.fromCodePoint` calls
(#30014) (Cameron)
- f17a216 ecmascript: Evaluate unary expressions in `ToNumber` (#30009)
(Cameron)
- 181dd40 ecmascript: Canonicalize RegExp flags in string conversion
(#30008) (Cameron)
- cf35a2e ecmascript: Respect shadowed `NaN` in strict equality (#30005)
(Cameron)
- 2d9246e minifier: Don't inline block-level vars visible to an outer
direct eval (#29992) (Cameron)
- 08023ad transformer: Keep TypeScript assign semantics for preserved
classes (#29930) (Dunqing)
- 32798b3 minifier: Don't treat reassigned `@__NO_SIDE_EFFECTS__`
functions as pure (#29974) (oxc-captain[bot])
- 0167451 parser: Treat `import x = require()` as module syntax (#29908)
(camc314)
- e27f727 semantic: Align JSDoc nullable type suggestions with
TypeScript (#29947) (camc314)
- 831fbca transformer: Don't fold computed key assignments into
non-computed method keys (#29912) (Dunqing)
- 6db561f transformer: Keep correct keys on leftover fields with
setPublicClassFields (#29911) (Dunqing)
- e4e2ac4 parser,semantic: Reject invalid types in type arguments
(#29945) (camc314)
- bdbed9e transformer/async-to-generator: Avoid invalid and shadowing
inferred function names (#29815) (YT)
- a0f67fa parser: Parse TSX `<T extends U` as start of generic arrow
function (#29910) (overlookmotel)
- 8c84c5f parser: Never parse `<` as start of generic arrow function in
JSX files (#29909) (overlookmotel)
- f5022f2 lexer: Read yield and await by enclosing function in modules
(#29890) (Shanon Jackson)
- 168daf3 lexer: Keep async and generator scope across class members and
generic async arrows (#29889) (Shanon Jackson)
- 777d2d1 parser: Report import/export in unambiguous code resolved to
script (#29902) (camc314)
- e385fe8 parser: Don't treat `await` in function parameters and class
fields as top-level await (#29901) (camc314)
- 5442f8a parser: Report misplaced import/export before checking parse
goal (#29898) (camc314)
- c589002 minifier: Drop redeclarations of removed declarations (#29415)
(Dunqing)
- 24a1aaf parser: Discard comments from rewound speculative parses
(#29847) (camc314)
- 1aadbe7 isolated-declarations: Preserve const literal initializers
through parentheses (#29041) (camc314)
- a7ea78b transformer: Keep classes whose decorators are preserved
(#29748) (Dunqing)
- 5ece804 transformer/async-to-generator: Remove leading digits from
inferred function names (#29816) (YT)
- 15bdce3 parser: `parse_expression` produce correct error for overlong
source (#29761) (overlookmotel)
- b6ff506 react-compiler: Do not treat the receiver of a JSX ref
property load as a ref (#29754) (Boshen)
- 2f6a11f semantic: Keep catch parameters in the catch clause scope
(#29635) (Dunqing)
- 60718a1 minifier: Keep unused classes with a static computed
`prototype` key (#27966) (baltasarblanco)
- d59aa8e transformer/legacy-decorator: Apply static member decorators
last (#27744) (Yunus Ozen)
- 97307e3 transformer/legacy-decorator: Emit `String`/`Number` metadata
for enums declared after the class (#29724) (Max Schwenk)
- 3586c66 transformer: Preserve object rest assignment evaluation
(#29645) (Boshen)
- 4fb4887 allocator: Require Sync allocator for Drain Send (#26152)
(Cameron)
- f860f1b semantic: Resolve a private name to the enclosing class that
declares it (#29714) (Nadir Ali)
- 7b2b207 parser: Parse contextual keywords after relational expressions
(#25097) (camc314)
- b7e2beb minifier: Preserve indirect calls when inlining eval aliases
(#29725) (Yunfei He)
- 279185a react-compiler: Ignore ESLint suppressions when hooks and memo
validations are enabled (#29655) (Boshen)
- d69ba66 napi/parser: Walk skipped ESTree fields in lazy visitor
(#29381) (Ryan Tsao)
- f22757c transformer/class-properties: Preserve receivers in TS-wrapped
private calls (#29684) (camc314)
- 0e1ef65 transformer/exponentiation-operator: Scope default parameter
temporaries (#29685) (camc314)

### ⚡ Performance

- 209f078 mangler: Include digits in trailing character frequency order
(#29437) (camc314)
- 5e7abd1 parser: Remove unnecessary conversion when parsing BigInts
(#29913) (overlookmotel)
- 5ac3942 parser: Mark missing-digit lexer errors cold (#29806) (Boshen)
- 892f086 various: Avoid copying source text in
`OxcDiagnostic::render_with_source_code` callers (#29850)
(overlookmotel)
- 27777a9 diagnostics: Loosen lifetime bound on
`OxcDiagnostic::with_source_code` (#29849) (overlookmotel)
- a2eed1b parser: Read each comment once (#29794) (Boshen)
- ec4090d semantic: Size the `Scoping` arena from symbol, reference and
scope counts (#29809) (Boshen)
- 7c39be0 minifier: Avoid rebuilding variable declarations when keeping
all declarators (#29767) (camc314)
- 0537b09 parser: Take the name of a JSX identifier from its token
(#29746) (Boshen)
- 1c2cd7c parser: Take the value of a string literal without escapes
from its source text (#29745) (Boshen)
- 1d84d3f parser: Take the value of JSX text from its source text
(#29744) (Boshen)
- 41e3075 parser: Check for the `<` of type arguments without a call
(#29743) (Boshen)
- 6e783b1 parser: Keep the token read after `import` (#29742) (Boshen)
- eb9c7a4 parser: Parse `(<div />)` as a parenthesized expression
directly (#29741) (Boshen)
- 7acf20a parser: Parse JSX at the start of an expression without
speculation (#29740) (Boshen)
- aea847b estree: Merge compact `serialize_field` writes (#28399)
(codspeed[bot])
- 414532b parser: Cache failed type argument speculation (#29518)
(Boshen)
- d91c961 parser: Take comments from the lexer without copying inline
storage (#29623) (Boshen)
- dda1781 parser: Finish plain strings and integers in their token
handler (#29622) (Boshen)
- 6f5d371 parser: Choose how to scan a block comment from its first
bytes (#29621) (Boshen)
- d80d731 parser: Do less work to record each comment (#29620) (Boshen)
- ce2b7aa parser: Lex the token after a line break in its token handler
(#29619) (Boshen)
- 7833ea0 parser: Finish identifier and keyword tokens in their token
handler (#29618) (Boshen)
- bb08acb parser: Dispatch tokens through handlers which finish the
token (#29617) (Boshen)
- a1ed5af parser: Parse `(…)` once with a cover grammar for arrow
functions (#29603) (Boshen)

### 📚 Documentation

- 158fcf5 minifier: Fix duplicated word in comment (#30059) (Dunqing)
- 3ff249b skills: Share PR title guidance with triagebot (#29980)
(Cameron)
- 983ebc7 ast: Clarify which keys `PropertyKey::static_name` supports
(#29905) (camc314)
- 1da6ea8 skills: Merge PR guidance into pr-guide skill (#29866)
(Dunqing)
- 9740083 minifier: Clarify when variable declarations are merged
(#29768) (camc314)

---------

Co-authored-by: Cameron <cameron.clark@hey.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

A-parser Area - JS/TS parsing and syntax errors, oxc_parser

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant