Skip to content

[JSC] Parser: arrow functions nested in parameter defaults no longer parse in exponential time - #699

Open
robobun wants to merge 2 commits into
mainfrom
robobun/88fbefc7/nested-arrow-default-parse-time
Open

robobun wants to merge 2 commits into
mainfrom
robobun/88fbefc7/nested-arrow-default-parse-time

Conversation

@robobun

@robobun robobun commented Sep 19, 2026 •

Copy link
Copy Markdown
Collaborator

Problem

  • Parse time more than doubles with each level of arrow functions nested in arrow function parameters. (a = (a = 9) => a) => a at depth 24 takes 17.2 s (release jsc of 000c489972, same in bun 1.4.3-canary). Node parses depth 1000 in 84 ms.
  • parseAssignmentExpression() (parser/Parser.cpp:4389) parses the text after ( three times: as an expression, as parameters in isArrowFunctionParameters(), then as the arrow function. Each pass reaches the nested arrow function, which runs the same three passes on its own text.

Fix

  • The parser keeps the offsets where it found an arrow function with parenthesized parameters. At a known offset, parseAssignmentExpression() skips the expression pass.
  • Correct because the expression pass never decides what ( ... ) => is. The parameter check and the arrow function parse still run on every visit. They depend on the context: async (a = (await) => 0) => a is an error only in the pass that knows the outer function is async.
  • If the parameters are not valid in a later pass, the expression pass runs as before, so the reported error stays the same.
  • Verified: the new JSTests/stress/arrow-function-nested-in-arrow-function-parameters-parse-time.js does not finish without the change. Depth 24 now takes 0.7 ms. A differential run of test262 language/ (44,493 runs) shows no difference.

Background

  • JavaScriptCore has no cover grammar for ( ... ). It parses the text as an expression, and parses again from a save point when => follows.
  • isArrowFunctionParameters() parses the parameters with a SyntaxChecker in a scope that it throws away.
  • SourceProviderCache keeps, per function start offset, the data that lets the parser step over a function it parsed before.
Notes

Shapes. The same growth holds for a pattern parameter (({ a = ... }) => a, ([a = ...]) => a), an async arrow function, a rest parameter after the default value, and the nest as a call argument or in parentheses. It is not a stack overflow, and #297 does not change it. The source provider cache answers the third pass, so the old cost was 2^N with the cache and 3^N without it.

Cost after the change. Depth 100 takes 9 ms. A visit of a known start still parses its parameters in isArrowFunctionParameters(), and that pass goes down the nest. A nest of depth N takes about N^2 parameter parses: depth 1000 takes 0.7 s. I did not remove that pass. It is what rejects async (a = (await) => 0) => a and async function f() { (a = (await) => 0) => a }. The arrow function parse alone accepts both, with and without the cache: its allowAwait comes from the parent scope, and an arrow function scope is never marked async. An earlier version of this change that skipped the parameter check failed 35 cases of the differential run for that reason.

Without the source provider cache the arrow function parse goes down the nest too, so the cost is 2^N there (3^N before). The new test requires the cache for that reason. no-cjit-validate-phases is the only test mode that runs without it. A parse for the debugger also runs without it.

One difference in generated code. An async function or async arrow function that never awaits is parsed twice when it is compiled: first with a SyntaxChecker, then with the ASTBuilder. In the second parse the arrow functions in its body are known starts, so the ASTBuilder no longer sees their parameters as an expression. For async () => ((a = (b = this) => b) => a)()() the old code marked the outer arrow function as a user of this because of that throwaway expression, and emitted a load of this that nothing used (create_cloned_arguments for arguments). Those instructions are gone. Results are the same: what an inner arrow function needs reaches the enclosing function through the scope (innerArrowFunctionFeatures, usesEval, the used variables). That already had to work for ({ z = 0 }, a = this.v) => a, where the expression pass stops at { z = 0 } and never sees this. I compared --dumpGeneratedBytecodes of two programs with this, arguments, super, new.target, eval, private names and tagged templates in nested default values. Only those async arrow functions differ.

Parse time of code with no nests, best of 400 runs, same machine: a synthetic file of 10,000 arrow functions with a default value takes 24.9 ms before and 25.4 ms after. typescript.js (9 MB) takes 136.6 ms before and 136.0 ms after. The known offsets are a sorted Vector<unsigned>, because a hash set cost 5% on the synthetic file. An arrow function is recorded after the ones in its parameters, so its offset is inserted before theirs. One arrow function with 100,000 arrow functions in a default value parses in 334 ms (375 ms before), so that insert does not show.

Tests run. The differential runs also cover 23,000 generated nests (about 15% of them valid code) and a corpus of 5,239 cases (169 expressions in 31 contexts). A second corpus of 144 whole programs reaches a known start by other ways: a destructuring assignment that is parsed as a literal first, the head of a for statement, a yield or await argument, an async function without await that is called, class fields and static blocks, and yield or await before a regular expression. The new test takes 45 to 130 ms per mode on that build and passes in all 17 modes of run-jsc-stress-tests. run-javascriptcore-tests --quick with name filters for arrow, async, await, yield, generator, destructuring, default parameter, syntax, parser, class field, static block, eval, function, es6 and the matching LayoutTests/js tests: about 7,200 runs, no failure. The differential runs used --useSourceProviderCache=false as well. The local build is Release with assertions on.

Found next to this, not changed here. A syntax error at the bottom of a nest of parentheses, array literals or object literals takes 2^N to report ((a = (a = 9 9)), [[[1 1]]]). A nest of destructuring assignments with default values takes 2^N ([a = [a = 9] = []] = []). function* g() { (a = (b = yield) => b) => a } is accepted with the cache and rejected without it.

@robobun
robobun force-pushed the robobun/88fbefc7/nested-arrow-default-parse-time branch from 67153ee to 0c10f7e Compare September 19, 2026 06:06
@coderabbitai

coderabbitai Bot commented Sep 19, 2026 •

Copy link
Copy Markdown

Review Change StackReview Change Stack

Important

Review skipped

We couldn't safely recover the incremental review. No full review was started, and the last reviewed checkpoint was preserved. Retry later, or explicitly request a full review by commenting @coderabbitai full review.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Essentials

Run ID: e320eb9b-f3da-4318-a8b0-e597b99656b1

📥 Commits

Reviewing files that changed from the base of the PR and between 0c10f7e and 2d32636.

📒 Files selected for processing (2)
  • JSTests/BUN-TEST-DIFFERENCES.md
  • JSTests/stress/arrow-function-nested-in-arrow-function-parameters-parse-time.js

Included review availability: Your plan provides up to 5 included reviews per hour; 1 remains after this review.


Walkthrough

The parser records known parenthesized arrow-function starts and rechecks them during assignment-expression parsing. A stress test covers nested arrow functions through evaluation, compilation, asynchronous execution, context-sensitive parameters, destructuring, syntax errors, and non-arrow expressions.

Changes

Nested arrow-function parsing

Layer / File(s) Summary
Track known arrow starts
Source/JavaScriptCore/parser/Parser.h
Parser stores sorted arrow-function start offsets and tracks the processed range boundary.
Reuse known arrow candidates
Source/JavaScriptCore/parser/Parser.cpp
The parser records parenthesized arrow starts, reparses known starts in the current context, and skips redundant candidate parsing when no arrow token exists.
Validate nested arrow parsing
JSTests/stress/arrow-function-nested-in-arrow-function-parameters-parse-time.js, JSTests/BUN-TEST-DIFFERENCES.md
The stress test covers depth-32 nested arrows, synchronous and asynchronous evaluation, closures, execution contexts, destructuring, syntax errors, ordinary non-arrow expressions, and source-provider-cache configuration.

Priority: ➖ Normal

🚥 Pre-merge checks | ✅ 3 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description gives a detailed problem statement, fix explanation, technical background, changed behavior, and test results. However, it omits required template information, including a Bugzilla lin… Add the associated Bugzilla URL, include the required “Reviewed by NOBODY (OOPS!).” line or actual reviewer, and list the changed files and relevant functions in the repository template format.
✅ Passed checks (3 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title clearly and concisely describes the main parser change: preventing exponential parse time for nested arrow functions in parameter defaults.
Full details: Description check

Explanation

The description gives a detailed problem statement, fix explanation, technical background, changed behavior, and test results. However, it omits required template information, including a Bugzilla link, the review line, and an explicit changed-file list.

Warning

Git: CodeRabbit could not clone the repository, so clone-backed analysis was skipped and this review may be incomplete. Verify repository clone access, such as SSH credentials, before requesting another full review. If clone access is intentionally unavailable, use path_filters to narrow the review scope.


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

@github-actions

github-actions Bot commented Sep 19, 2026 •

Copy link
Copy Markdown

Preview build of c204523: autobuild-preview-pr-699-c2045236

@claude claude Bot left a comment

Copy link
Copy Markdown

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.

Beyond the inline findings, I also checked the Parser.h hot-field layout (both new fields sit after m_parserState, so the verifyLayout static_asserts and the first three cache lines are unchanged) and the suppressed !lhs retry at Parser.cpp:4426 (a known start already ran parseArrowFunctionCandidate before the expression pass in the same visit, so the retry could only repeat the same failed parameter check and would report nothing new).

Extended reasoning...

Findings were posted inline (test runtime budget, missing BUN-TEST-DIFFERENCES.md entry, remaining exponential cost in the cache-less debugger parse), so the body only records what else was examined and ruled out: the layout of the two new Parser fields relative to the verifyLayout static_asserts, and whether dropping the !lhs retry for known starts can change which error is reported. Both checked out from the diff and Parser.h. The parser change itself is small but sits in a hot, subtle path (three-pass arrow parsing, context-dependent parameter validity), and the inline findings already indicate that a human should look, so this is not approved.

Comment thread Source/JavaScriptCore/parser/Parser.cpp Resolved
@robobun

robobun commented Sep 19, 2026

Copy link
Copy Markdown
Collaborator Author

The bun side is oven-sh/bun#43402. It pins the preview build of this branch and adds a test that spawns a child with a kill timeout.

@claude claude Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

The follow-up commit addresses both points from my earlier review (the test now walks a depth-12 nest and keeps depth 32 for the parse-once cases, and the requireOptions opt-out is listed in JSTests/BUN-TEST-DIFFERENCES.md); this automated review re-ran on the new head and found no bugs, but since this changes Parser::parseAssignmentExpression in the core JSC parser, a human look from a JSC reviewer is still worthwhile before merging.

What was reviewed:

  • The known-start path in Source/JavaScriptCore/parser/Parser.cpp:4396-4403 and the !lhs guard at :4426: when isArrowFunctionParameters() rejects the parameters in a later pass, parseArrowFunctionCandidate restores the save point (lexer, parser state, error message) and falls through to the expression pass, so the reported error is unchanged.
  • addKnownArrowFunctionStart / isKnownArrowFunctionStart in Parser.h: the sorted insert keeps the vector ordered when an inner start is found before its enclosing one, and duplicates are skipped; the new fields sit after m_parserState, so the verifyLayout() cache-line asserts are unaffected.
  • The second commit only touches the test and the differences table; the parser diff is identical to the version reviewed earlier.
Extended reasoning...

Overview

The PR touches four files: Source/JavaScriptCore/parser/Parser.cpp (a new early path in parseAssignmentExpression that, at an offset previously recorded as an arrow-function start, skips the expression pass and goes straight to parseArrowFunctionCandidate; and a tweak to the !lhs retry so a known start is not re-checked without =>), Source/JavaScriptCore/parser/Parser.h (a sorted Vector<unsigned> of known starts plus a high-water mark for the fast negative check), a new stress test, and a row in JSTests/BUN-TEST-DIFFERENCES.md. The second commit (2d32636) changed only the test and the differences table, shrinking the nests the test walks down so it stays within the 200 ms budget and recording the --useSourceProviderCache=true narrowing, which were the two nits from the previous review.

Security risks

None specific to this change. The parser only gains a per-Parser-instance vector of source offsets; it does not change what is accepted or rejected (the parameter check still runs on every visit, and the fall-through to the expression pass preserves error reporting). The motivating issue is a parse-time denial of service (exponential time for a small input), which this change removes for the cached case.

Level of scrutiny

Moderate to high. It is a small diff, but it lives in parseAssignmentExpression, the hottest and most subtle part of the JSC parser, and the PR itself documents one observable difference in generated bytecode for async functions that never await (a dead this load no longer emitted). The change relies on an invariant that the expression pass never decides whether ( ... ) => is an arrow function, which I re-read and agree with, and on save-point restoration being complete when the parameter check fails in a later pass, which restoreSavePointWithError covers (lexer offset, parser state, error strings). /Source/JavaScriptCore and /JSTests are covered by .github/CODEOWNERS, so approval is not appropriate from this review regardless.

Other factors

The multi-agent bug hunt ran to a dry streak with no findings. The test covers the shapes the fix targets (default values, patterns, rest, async, call/array/conditional contexts), the error cases that depend on enclosing context (await in an async arrow's default, static blocks, class fields), and capture semantics for this, arguments, super, new.target and eval inside nested defaults, so the bytecode-difference claim has behavioral coverage even if not a bytecode-dump comparison in CI. The PR description reports test262 language/ and a large generated-corpus differential run with no differences; that is the author's claim and not verified here. Remaining known limitation (exponential cost when the source provider cache is off, e.g. debugger parses) was raised in the earlier review as pre-existing and non-blocking and is unchanged.

parseAssignmentExpression() parses the text of an arrow function with
parenthesized parameters three times: as an expression, as parameters in
isArrowFunctionParameters(), then as the arrow function. Each pass reaches
the candidates in that text, for example an arrow function in a default
value, and each of them does the same three passes over its own text. The
source provider cache answers the third pass, so a nest of depth N took 2^N
passes with the cache and 3^N without it: depth 24 of
`(a = (a = 9) => a) => a` took 17 seconds.

The parser now keeps the offsets where it found an arrow function with
parenthesized parameters. When parseAssignmentExpression() starts at one of
them again, it goes to parseArrowFunctionCandidate() at once. For a text
that is `( ... ) =>`, the expression pass never decides what it is. The
parameter check and the arrow function parse still run on every visit,
because they depend on the context: `async (a = (await) => 0) => a` is an
error only in the pass that knows the outer function is async. When the
parameters are not valid in a later pass, the expression pass runs as
before, so the reported error does not change.

The normal path pays one compare of the token offset with the end of the
known offsets.
…eOptions

A call compiles one level of the nest with a new parser, which parses the
levels below it again, so the walk down a nest of depth 100 cost depth^3 and
the test took over a second. The nests that must finish are now 32 deep (2^32
passes before the change), and the walk down gets a nest of depth 12. The
whole file takes 45 to 130 ms in the modes I timed.

BUN-TEST-DIFFERENCES.md lists the test's --useSourceProviderCache=true.
@robobun
robobun force-pushed the robobun/88fbefc7/nested-arrow-default-parse-time branch from 2d32636 to c204523 Compare September 23, 2026 17:21
robobun added a commit to oven-sh/bun that referenced this pull request Sep 23, 2026
The parser no longer parses an arrow function nested in the parameters of
another arrow function as an expression on every pass, so the parse time no
longer doubles with each level of the nest.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant