Repository navigation
Conversation
67153ee to
0c10f7e
Compare
|
Important Review skippedWe 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 You can disable this status message by setting the Use the checkbox below for a quick retry:
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Organization UI Review profile: ASSERTIVE Plan: Essentials Run ID: 📒 Files selected for processing (2)
Included review availability: Your plan provides up to 5 included reviews per hour; 1 remains after this review. WalkthroughThe 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. ChangesNested arrow-function parsing
Priority: ➖ Normal 🚥 Pre-merge checks | ✅ 3 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (3 passed)
Full details: Description checkExplanation 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 Comment |
|
Preview build of c204523: |
There was a problem hiding this comment.
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.
|
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. |
There was a problem hiding this comment.
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-4403and the!lhsguard at:4426: whenisArrowFunctionParameters()rejects the parameters in a later pass,parseArrowFunctionCandidaterestores the save point (lexer, parser state, error message) and falls through to the expression pass, so the reported error is unchanged. addKnownArrowFunctionStart/isKnownArrowFunctionStartinParser.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 afterm_parserState, so theverifyLayout()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.
2d32636 to
c204523
Compare
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.
Problem
(a = (a = 9) => a) => aat depth 24 takes 17.2 s (releasejscof000c489972, same inbun1.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 inisArrowFunctionParameters(), then as the arrow function. Each pass reaches the nested arrow function, which runs the same three passes on its own text.Fix
parseAssignmentExpression()skips the expression pass.( ... ) =>is. The parameter check and the arrow function parse still run on every visit. They depend on the context:async (a = (await) => 0) => ais an error only in the pass that knows the outer function isasync.JSTests/stress/arrow-function-nested-in-arrow-function-parameters-parse-time.jsdoes not finish without the change. Depth 24 now takes 0.7 ms. A differential run of test262language/(44,493 runs) shows no difference.Background
( ... ). It parses the text as an expression, and parses again from a save point when=>follows.isArrowFunctionParameters()parses the parameters with aSyntaxCheckerin a scope that it throws away.SourceProviderCachekeeps, 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), anasyncarrow 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 rejectsasync (a = (await) => 0) => aandasync function f() { (a = (await) => 0) => a }. The arrow function parse alone accepts both, with and without the cache: itsallowAwaitcomes 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-phasesis the only test mode that runs without it. A parse for the debugger also runs without it.One difference in generated code. An
asyncfunction orasyncarrow function that never awaits is parsed twice when it is compiled: first with aSyntaxChecker, then with theASTBuilder. In the second parse the arrow functions in its body are known starts, so theASTBuilderno longer sees their parameters as an expression. Forasync () => ((a = (b = this) => b) => a)()()the old code marked the outer arrow function as a user ofthisbecause of that throwaway expression, and emitted a load ofthisthat nothing used (create_cloned_argumentsforarguments). 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 seesthis. I compared--dumpGeneratedBytecodesof two programs withthis,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 sortedVector<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
forstatement, ayieldorawaitargument, anasyncfunction withoutawaitthat is called, class fields and static blocks, andyieldorawaitbefore a regular expression. The new test takes 45 to 130 ms per mode on that build and passes in all 17 modes ofrun-jsc-stress-tests.run-javascriptcore-tests --quickwith name filters for arrow, async, await, yield, generator, destructuring, default parameter, syntax, parser, class field, static block, eval, function,es6and the matchingLayoutTests/jstests: about 7,200 runs, no failure. The differential runs used--useSourceProviderCache=falseas 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.