diff --git a/crates/lpm-security/src/behavioral/mod.rs b/crates/lpm-security/src/behavioral/mod.rs index c26ca08cf..c5b283ac8 100644 --- a/crates/lpm-security/src/behavioral/mod.rs +++ b/crates/lpm-security/src/behavioral/mod.rs @@ -3489,6 +3489,141 @@ mod tests { } } + #[test] + fn expressions_in_more_wrappers_than_real_code_has_are_read_without_parsing_in_linear_time() { + // The rules read through wrappers, and read an initializer again for + // each reference to it. + let analyze = |filename: &'static str, source: String| { + std::thread::Builder::new() + .stack_size(256 * 1024 * 1024) + .spawn(move || { + let started = std::time::Instant::now(); + let result = analyze_bytes(filename, source.as_bytes()); + (result, started.elapsed()) + }) + .unwrap() + .join() + .unwrap() + }; + let depth = 10_000; + let references = 20_000; + let parenthesized = nested("(", "function(){}", ")", depth); + for (filename, source) in [ + ( + "index.js", + format!( + "eval(y);const f={parenthesized};{}", + "f();".repeat(references) + ), + ), + ( + "index.js", + format!( + "eval(y);const f={parenthesized};var x;{}", + "x=f;".repeat(references) + ), + ), + ( + "index.ts", + format!( + "eval(y);const f=function(){{}}{};{}", + "!".repeat(depth), + "f();".repeat(references) + ), + ), + ] { + let flat = format!("{}eval(y);", "x;".repeat(source.len() / 2)); + let (flat_result, flat_time) = analyze(filename, flat); + let (result, nested_time) = analyze(filename, source); + assert_eq!(flat_result.unparsed_files, 0); + assert!(result.source.eval); + assert_eq!(result.unparsed_files, 1, "{filename}"); + assert!( + nested_time < flat_time * 5 + std::time::Duration::from_millis(200), + "{filename}: nested {nested_time:?}, flat {flat_time:?}" + ); + } + } + + #[test] + fn expressions_in_as_many_wrappers_as_real_code_could_have_are_parsed() { + // A run of wrappers continues only into the expression a wrapper + // wraps, and into the last expression of a sequence, as the rules read + // through them. + for (filename, source, unparsed) in [ + ( + "index.js", + format!("x={};", nested("(", "eval(y)", ")", 32)), + 0, + ), + ( + "index.js", + format!("x={};", nested("(", "eval(y)", ")", 33)), + 1, + ), + ( + "index.js", + format!("x={};", nested("(", "eval(y)", ",0)", 40)), + 0, + ), + ( + "index.js", + format!("x={};", nested("(0,", "eval(y)", ")", 40)), + 1, + ), + ( + "index.ts", + format!("x=a as {{[{}]:number}};eval(y);", nested("(", "k", ")", 32)), + 0, + ), + ("index.ts", format!("x=a{};eval(y);", " as T".repeat(33)), 1), + ( + "index.ts", + format!("x=a{};eval(y);", " satisfies T".repeat(33)), + 1, + ), + ("index.ts", format!("x={}a;eval(y);", "".repeat(33)), 1), + ("index.ts", format!("x=a{};eval(y);", "!".repeat(33)), 1), + ( + "index.ts", + format!("x={};eval(y);", nested("(", "a", ")", 31)), + 0, + ), + ( + "index.ts", + format!("x={};eval(y);", nested("(", "a", ")", 32)), + 1, + ), + ] { + let result = analyze_on_a_worker_stack(filename, source.clone()); + assert!(result.source.eval); + assert_eq!(result.unparsed_files, unparsed, "{source}"); + } + } + + #[test] + fn code_after_a_top_level_await_parsed_again_is_analyzed() { + // Found to be a module, each source's statement that starts with + // `await` ends earlier than its script reading did, and the code after + // it runs. + for source in [ + "await / a; x = /;0/ + eval(y);\nexport {};\n", + "await /a/\neval(y)\nexport {};\n", + ] { + let result = analyze_on_a_worker_stack("index.js", source.to_owned()); + assert_eq!(result.unparsed_files, 0, "{source}"); + assert!(result.source.eval, "{source}"); + } + } + + #[test] + fn a_source_in_too_many_wrappers_keeps_its_comments_and_literals_masked() { + let source = format!("/* eval(y) */x='eval(y)';x={};", nested("(", "a", ")", 33)); + let result = analyze_on_a_worker_stack("index.js", source); + assert_eq!(result.unparsed_files, 1); + assert!(!result.source.eval); + } + #[test] fn generic_arrow_heads_nested_in_defaults_are_read_without_parsing_in_linear_time() { // A TypeScript `<` that may open a generic arrow function is parsed diff --git a/crates/lpm-security/src/behavioral/syntax.rs b/crates/lpm-security/src/behavioral/syntax.rs index d73049fa4..d77be553a 100644 --- a/crates/lpm-security/src/behavioral/syntax.rs +++ b/crates/lpm-security/src/behavioral/syntax.rs @@ -1,4 +1,4 @@ -use oxc_allocator::Allocator; +use oxc_allocator::{Address, Allocator, GetAddress}; use oxc_ast::AstKind; use oxc_ast::ast::{Expression, JSXText, RegExpLiteral, Statement, StringLiteral, TemplateElement}; use oxc_ast_visit::{Visit, walk}; @@ -74,6 +74,14 @@ const RESOLUTION_LOOKUPS_FLOOR: u64 = 1 << 20; const PARSE_SPECULATION_PER_BYTE: u64 = 2; const PARSE_SPECULATION_FLOOR: u64 = 64 * 1024; +/// The most parentheses, TypeScript wrappers (`as`, `satisfies`, `!`, ``) +/// and sequences, through their last expression, an expression may sit in +/// directly for the rules to run on its source. The rules read through them, +/// and read a binding's initializer again for each reference to it, so an +/// initializer wrapped thousands of times made the analysis quadratic. Real +/// code wraps at most 5 deep. +const MAX_WRAPPER_RUN: u32 = 32; + fn parse_speculation_budget(source: &str) -> u64 { (source.len() as u64) .saturating_mul(PARSE_SPECULATION_PER_BYTE) @@ -105,6 +113,14 @@ struct LiteralSpans<'s> { resolution_lookups: u64, /// The visitor reached the stack floor and skips the rest. stopped: bool, + /// Wrappers the expression being visited sits in directly, itself + /// included when it is one. + wrapper_run: u32, + /// The most wrappers any expression visited sits in directly. + longest_wrapper_run: u32, + /// The expression that continues the run of the wrapper being visited: + /// the one it wraps, or the last expression of a sequence. + run_continues_into: Option
, } /// Whether nodes of this kind get a scope that `var` declarations are @@ -187,9 +203,31 @@ fn stack_address() -> usize { impl<'a> Visit<'a> for LiteralSpans<'_> { fn visit_expression(&mut self, expression: &Expression<'a>) { - if !self.reached_floor() { - walk::walk_expression(self, expression); + if self.reached_floor() { + return; } + let continued_into = self.run_continues_into.take(); + let outer_run = self.wrapper_run; + let wrapped = match expression { + Expression::ParenthesizedExpression(wrapper) => Some(&wrapper.expression), + Expression::TSAsExpression(wrapper) => Some(&wrapper.expression), + Expression::TSSatisfiesExpression(wrapper) => Some(&wrapper.expression), + Expression::TSNonNullExpression(wrapper) => Some(&wrapper.expression), + Expression::TSTypeAssertion(wrapper) => Some(&wrapper.expression), + Expression::TSInstantiationExpression(wrapper) => Some(&wrapper.expression), + Expression::SequenceExpression(sequence) => sequence.expressions.last(), + _ => None, + }; + self.wrapper_run = match wrapped { + Some(_) if continued_into == Some(expression.address()) => outer_run + 1, + Some(_) => 1, + None => 0, + }; + self.longest_wrapper_run = self.longest_wrapper_run.max(self.wrapper_run); + self.run_continues_into = wrapped.map(GetAddress::address); + walk::walk_expression(self, expression); + self.wrapper_run = outer_run; + self.run_continues_into = continued_into; } fn visit_statement(&mut self, statement: &Statement<'a>) { @@ -342,6 +380,9 @@ fn parse_above( labels: 0, resolution_lookups: 0, stopped: false, + wrapper_run: 0, + longest_wrapper_run: 0, + run_continues_into: None, }; std::panic::catch_unwind(AssertUnwindSafe(|| { literals.visit_program(&parsed.program); @@ -351,7 +392,11 @@ fn parse_above( return Err(Unparsed::OutOfStack); } let random_literal = (!parsed.fatal_error).then_some(literals.random_literal); - let complete = !parsed.fatal_error && !parsed.diagnostics.has_errors(); + // A source with a longer run of wrappers keeps its comments and literals + // masked, but the rules that read through wrappers don't run on it. + let complete = !parsed.fatal_error + && !parsed.diagnostics.has_errors() + && literals.longest_wrapper_run <= MAX_WRAPPER_RUN; let resolution_budget = (source.len() as u64) .saturating_mul(RESOLUTION_LOOKUPS_PER_BYTE) .max(RESOLUTION_LOOKUPS_FLOOR); @@ -727,14 +772,14 @@ mod tests { } /// How long parsing `source`, which is valid, takes on a stack deep - /// enough for it. - fn time_to_parse(source: String) -> std::time::Duration { + /// enough for it, with no speculation budget. + fn time_to_parse(source: String, source_type: SourceType) -> std::time::Duration { std::thread::Builder::new() .stack_size(512 * 1024 * 1024) .spawn(move || { let allocator = Allocator::default(); let started = std::time::Instant::now(); - let parsed = Parser::new(&allocator, &source, SourceType::cjs()) + let parsed = Parser::new(&allocator, &source, source_type) .with_options(ParseOptions { stack_floor: current_stack_floor().unwrap(), ..ParseOptions::default() @@ -754,8 +799,11 @@ mod tests { // Each closing parenthesis records where the expression innermost in // it starts, and must not walk every parenthesis inside it to find it. let depth = 40_000; - let nested = time_to_parse(format!("x={}a{};", "(".repeat(depth), ")".repeat(depth))); - let flat = time_to_parse("x;".repeat(depth + 1)); + let nested = time_to_parse( + format!("x={}a{};", "(".repeat(depth), ")".repeat(depth)), + SourceType::cjs(), + ); + let flat = time_to_parse("x;".repeat(depth + 1), SourceType::cjs()); assert!( nested < flat * 5 + std::time::Duration::from_millis(200), "nested {nested:?}, flat {flat:?}" @@ -774,8 +822,180 @@ mod tests { "async(a=function(){await})=>0;".repeat(literals / 2) ); let flat = "x;".repeat(source.len() / 2); - let parsed_again = time_to_parse(source); - let flat = time_to_parse(flat); + let parsed_again = time_to_parse(source, SourceType::cjs()); + let flat = time_to_parse(flat, SourceType::cjs()); + assert!( + parsed_again < flat * 5 + std::time::Duration::from_millis(200), + "parsed again {parsed_again:?}, flat {flat:?}" + ); + } + + #[test] + fn exports_of_many_imported_names_resolve_in_linear_time() { + // Each local export looks its name up among the import entries. + let names = 20_000; + let source = format!( + "import{{{}}}from'x';export{{{}}};", + "a,".repeat(names), + "b,".repeat(names) + ); + let flat = "x;".repeat(source.len() / 2); + let resolved = time_to_parse(source, SourceType::mjs()); + let flat = time_to_parse(flat, SourceType::mjs()); + assert!( + resolved < flat * 5 + std::time::Duration::from_millis(200), + "resolved {resolved:?}, flat {flat:?}" + ); + } + + #[test] + fn pure_comments_on_nested_parentheses_apply_in_linear_time() { + // A pure comment applies to the call inside the parentheses after it, + // and each level must not walk every parenthesis inside it again, even + // when a pure comment inside a computed key walks in between. + let depth = 30_000; + for source in [ + format!( + "{}a(){};", + "/*#__PURE__*/(".repeat(depth), + ")".repeat(depth) + ), + format!( + "{}a{};", + "/*#__PURE__*/(".repeat(depth), + ")[/*#__PURE__*/k()]".repeat(depth) + ), + ] { + let flat = "x;".repeat(source.len() / 2); + let end = source[source.len() - 40..].to_owned(); + let applied = time_to_parse(source, SourceType::cjs()); + let flat = time_to_parse(flat, SourceType::cjs()); + assert!( + applied < flat * 5 + std::time::Duration::from_millis(200), + "{end}: applied {applied:?}, flat {flat:?}" + ); + } + } + + #[test] + fn pure_comments_on_nested_wrappers_mark_the_call_inside_them() { + struct Calls { + pure: usize, + } + impl<'a> Visit<'a> for Calls { + fn visit_call_expression(&mut self, call: &oxc_ast::ast::CallExpression<'a>) { + self.pure += usize::from(call.pure); + walk::walk_call_expression(self, call); + } + } + for (source, source_type, pure_calls, applied_comments) in [ + ( + "x=/*#__PURE__*/(/*#__PURE__*/(/*#__PURE__*/(a())));", + SourceType::cjs(), + 1, + 3, + ), + ( + "x=/*#__PURE__*/(/*#__PURE__*/(a));", + SourceType::cjs(), + 0, + 0, + ), + ( + "x=/*#__PURE__*/(/*#__PURE__*/(a()).b);", + SourceType::cjs(), + 1, + 2, + ), + ( + "x=/*#__PURE__*//*#__PURE__*/a();", + SourceType::ts(), + 1, + 2, + ), + ] { + let allocator = Allocator::default(); + let parsed = Parser::new(&allocator, source, source_type).parse(); + assert!(parsed.diagnostics.is_empty(), "{source}"); + let mut calls = Calls { pure: 0 }; + calls.visit_program(&parsed.program); + let applied = parsed + .program + .comments + .iter() + .filter(|comment| comment.content == oxc_ast::CommentContent::Pure) + .count(); + assert_eq!( + (calls.pure, applied), + (pure_calls, applied_comments), + "{source}" + ); + } + } + + #[test] + fn a_top_level_await_parsed_again_replaces_the_statements_it_takes_in() { + // Found to be a module, `await\nawait\n0;` is one statement. In + // `await\nawait /x/\nfoo();` the second line was `await / x / foo()` + // as a script, so the statement parsed again ends inside it, and + // `foo();` is parsed again too. + for (source, expected) in [ + ( + "await\nawait\n0;\nexport {};\n", + &["await\nawait\n0;", "export {};"][..], + ), + ( + "await\nawait /x/\nfoo();\nexport {};\n", + &["await\nawait /x/", "foo();", "export {};"][..], + ), + ( + "await\nlet\nx = eval(y)\nexport {};\n", + &["await\nlet", "x = eval(y)", "export {};"][..], + ), + ( + "await / a; x = /;0/ + eval(y);\nexport {};\n", + &["await / a; x = /;", "0/ + eval(y);", "export {};"][..], + ), + ( + "await /a/\neval(y)\nexport {};\n", + &["await /a/", "eval(y)", "export {};"][..], + ), + ] { + let allocator = Allocator::default(); + let parsed = Parser::new(&allocator, source, SourceType::unambiguous()).parse(); + assert!(parsed.diagnostics.is_empty(), "{source}"); + let statements: Vec<&str> = parsed + .program + .body + .iter() + .map(|statement| { + let span = oxc_span::GetSpan::span(statement); + &source[span.start as usize..span.end as usize] + }) + .collect(); + assert_eq!(statements, expected, "{source}"); + } + } + + #[test] + fn a_top_level_await_parsed_again_records_its_dynamic_import_once() { + let allocator = Allocator::default(); + let source = "await\nimport('x');\nexport {};\n"; + let parsed = Parser::new(&allocator, source, SourceType::unambiguous()).parse(); + assert!(parsed.diagnostics.is_empty()); + assert_eq!(parsed.module_record.dynamic_imports.len(), 1); + } + + #[test] + fn top_level_awaits_parsed_again_as_a_module_take_linear_time() { + // A source whose module syntax is found late parses its statements + // that start with `await` again, and one parse again can take in the + // statements after it. + let awaits = 10_000; + let source = format!("{}0;\nexport {{}};\n", "await\n".repeat(awaits)); + let flat = "x;".repeat(source.len() / 2); + let parsed_again = time_to_parse(source, SourceType::unambiguous()); + let flat = time_to_parse(flat, SourceType::unambiguous()); assert!( parsed_again < flat * 5 + std::time::Duration::from_millis(200), "parsed again {parsed_again:?}, flat {flat:?}" @@ -812,6 +1032,9 @@ mod tests { labels: 0, resolution_lookups: 0, stopped: false, + wrapper_run: 0, + longest_wrapper_run: 0, + run_continues_into: None, }; let unwound = std::panic::catch_unwind(AssertUnwindSafe(|| { literals.visit_program(&parsed.program); diff --git a/vendor/oxc_parser/LPM-PATCH.md b/vendor/oxc_parser/LPM-PATCH.md index 3c7824948..230752d4e 100644 --- a/vendor/oxc_parser/LPM-PATCH.md +++ b/vendor/oxc_parser/LPM-PATCH.md @@ -2,10 +2,11 @@ This is `oxc_parser` 0.160.0 from crates.io (oxc commit `87e38f3270b00341695e02e8aaf681e9e985e4a3`, `crates/oxc_parser`), MIT -licensed (see `LICENSE`), with three changes: the parser can stop at a -stack floor instead of overflowing its thread's stack, it can stop at a -budget for the work it spends on speculative parses, and nested -parentheses and member chains take it linear time and constant stack. The workspace uses it through `[patch.crates-io]` in the root +licensed (see `LICENSE`), with three kinds of change: the parser can stop +at a stack floor instead of overflowing its thread's stack, it can stop at +a budget for the work it spends on speculative parses, and the inputs that +made upstream's parse quadratic without speculating take it linear time. +The workspace uses it through `[patch.crates-io]` in the root `Cargo.toml`. ## Why @@ -26,29 +27,42 @@ quadratic in the source's length: `x=(a=(a=…0)));` and `x=async(a=async(a=…await 0)=>0)=>0;` read each level again for every level around it. -Upstream 0.160 also walks every parenthesis inside a closing one to find -where the expression innermost in them starts, so `((((…a…))))` took -quadratic time without speculating: 80,000 levels, which fit on a 64 MiB -stack, took four seconds. And before parsing the arguments of an -`async(…)` that mention `await` again as parameters, it walked every entry -recorded for literals ending in a spread and a comma (`[...a,]`) anywhere -before them, reading almost nothing again: a 4 MiB file of those and of -`async(await)=>0` would have taken about 25 seconds, within the budget. +Some upstream work grows with what was parsed before it while reading +little or nothing again, so no budget on bytes read again bounds it. In +release builds: + +- closing a parenthesis walked every parenthesis inside it to find where + the expression innermost in them starts: 80,000 nested levels took 4 s; +- parsing the arguments of an `async(…)` again walked every entry recorded + for a literal ending in a spread and a comma (`[...a,]`) before them: a + 4 MiB file of those and `async(await)=>0` would have taken about 25 s; +- each local export searched every import entry for its name: 40,000 of + each took 3 s, and a 4 MiB module would take about half an hour; +- each `/*#__PURE__*/` before nested parentheses walked every parenthesis + inside it to find its call: 40,000 levels took 1.1 s; +- a source whose module syntax is found late parses each statement that + starts with `await` again, and one parse again can take in the + candidates after it, which were parsed again anyway: 8,000 lines of + `await` took 0.5 s and 1 GB. ## What changed -`lpm-stack-floor.patch` is the whole change against the published crate: +`lpm-stack-floor.patch` is the whole change against the published crate. + +Stack floor: - `ParseOptions::stack_floor`: the lowest stack address the parser may use. The default, `0`, never stops, so every other user of the parser behaves exactly as upstream. - Before moving to each token, the parser compares the stack pointer with - the floor: in `advance`, the JSX variants, and `advance_to`, which moves - to a token the lexer has already read. Every level of nesting in the - source reads at least one token, so the parser can't go deeper than the - frames between two tokens past it. Below the floor it records a fatal - error, which moves the lexer to the end of the source, so every caller - unwinds without reading more. + the lexer's `stop_below`: in `advance`, the JSX variants, and + `advance_to`, which moves to a token the lexer has already read. + `stop_below` starts at the floor and goes past every address once either + limit is reached, so one comparison per token checks both. Every level of + nesting in the source reads at least one token, so the parser can't go + deeper than the frames between two tokens past the floor. There it + records a fatal error, which moves the lexer to the end of the source, so + every caller unwinds without reading more. - Recursions that run over nodes already parsed and read no token check the floor once per level themselves, because their frames per level can be larger than those of the parse that built the nodes: @@ -66,6 +80,12 @@ before them, reading almost nothing again: a 4 MiB file of those and of the parser, so they record the stop in a `Cell` and fail; the parse then stops at the next token it reads, and reports the stop even if it reads none. +- Two recursions over a member chain, which the parser reads in a loop + and so without using stack per member, are loops instead: + `set_pure_on_call_or_new_expr`, for `/*#__PURE__*/a.b.c…`, and + `jsx_member_expression_eq`, which compares `` with its closing + tag. A debug build overflowed its stack on 200,000 members; a release + build relied on the optimizer turning the tail calls into loops. - Once the floor is reached, every later token read records the fatal error again. A speculative parse rewinds the fatal error away, and the parser then reads the other interpretation. If only reads below the floor @@ -74,6 +94,9 @@ before them, reading almost nothing again: a 4 MiB file of those and of speculative parse rewinds the fatal error away, because the speculation's outcome, and so the AST, may then differ from a parse with more stack. Callers discard a parse that reports it. + +Speculation budget: + - `ParseOptions::speculation_budget`: how much work the parser may spend on speculative parses. The lexer counts the bytes it moves back over in every rewind, the parser's and its own lookaheads', and the bytes it @@ -81,29 +104,43 @@ before them, reading almost nothing again: a 4 MiB file of those and of source. Their difference is what it has read beyond its position, so in all it has read at most its position plus that. The counts change only in rewinds and skips, and the lexer compares them with the budget at every - rewind, its own lookaheads' included, so a parse pays nothing for them - per token. Going past the budget stops the parse at the next token it - reads, the same way the floor does, sticky across later rewinds, and + rewind, so a parse pays nothing for them per token. Going past the budget + stops the parse at the next token it reads, the same way the floor does, + sticky across later rewinds, and `ParserReturn::speculation_budget_exhausted` reports it. A parse that reached the floor reports only that, so it can still be retried on a larger stack. The default, `0`, never stops. -- Two recursions over a member chain, which the parser reads in a loop - and so without using stack per member, are loops instead: - `set_pure_on_call_or_new_expr`, for `/*#__PURE__*/a.b.c…`, and - `jsx_member_expression_eq`, which compares `` with its closing - tag. Each recursed once per member, and a debug build overflowed its - stack on 200,000 members; a release build relied on the optimizer - turning the tail calls into loops. -- `ParserState::cover_initialized_name` and `trailing_commas` are ordered - maps, so parsing the arguments of `async(…)` again drops the entries - inside them with `split_off` instead of walking every entry before them. + +Linear time: + - `ParserState::last_parenthesized` keeps the start of the `ParenthesizedExpression` built last and of the expression innermost in its parentheses. Each place that builds one records it, and closing a - chain of parentheses reads the innermost start from there instead of - walking the chain. A rewind leaves no stale entry: only a parse of the - same offset can build another `ParenthesizedExpression` starting there, - and it records its own. + chain of parentheses reads the innermost start from there. +- `ParserState::cover_initialized_name` and `trailing_commas` are ordered + maps, so parsing the arguments of `async(…)` again drops the entries + inside them with `split_off`. +- `ModuleRecordBuilder::resolve_export_entries` looks local exports up in + an index of the import entries by local name once there are more than 16 + of them and a local export to look up, keeping the first entry for each + name as the search did. +- `ParserState::pure_walks` keeps where each walk for a `/*#__PURE__*/` + comment started and what it found. A walk that reaches one of those + expressions takes its answer, so no node is walked twice. +- `reparse_potential_top_level_awaits` skips the candidates that a + statement parsed again took in. When a statement parsed again ends inside + one the first parse read, as `await\nawait /x/` ends inside the script's + `await / x / foo()`, it parses on to the end of one, so the rest is parsed + again too. It then drops the statements it covered, so none overlap and + none is lost. The module record keeps a dynamic import or `import.meta` + recorded again only once. +- Neither cache can answer for the wrong node. `last_parenthesized` is + keyed by where a `ParenthesizedExpression` starts, and only a parse of + the same source can build another one there, which records its own. + `pure_walks` is keyed by a node's address: the arena never frees or + reuses a node, rewinds included, and no node on a walked path changes + after its walk. The one rewrite of a node after it is built, in + `parse_lhs_expression_rest`, comes before any walk that could reach it. `lpm-security`'s `behavioral/syntax.rs` sets the floor from the stack its thread has left, retries a source that runs out on a 64 MiB stack, and @@ -112,7 +149,8 @@ parse a speculation budget of twice the source's length, and at least 64 KiB, and reads a source that exceeds it without parsing it. Across the 370,776 JavaScript and TypeScript files of a local package store, the most any file read beyond its position was 0.75 bytes per byte, and no file used -more than 30% of its budget. +more than 30% of its budget. On 300 MB of those files, a release build +parses about 2% slower than the published crate. ## Upgrading oxc @@ -125,15 +163,17 @@ more than 30% of its budget. -x .cargo_vcs_info.json -x Cargo.lock`, with `a/` and `b/` file headers. 4. Look for every place the parser moves to a new token, and for new recursion that reads no token, such as conversions between AST shapes - after a parse, and give them floor checks like the ones above. - Look for walks over nodes already built, like the one through nested - parentheses, that run once per level of nesting, and for work at each - rewind or parse again that grows with what was parsed before it, not - with the bytes read again, like the walk over recorded literals. `lpm-security`'s + after a parse, and give them floor checks like the ones above. Look for + walks over nodes already built that run once per level of nesting, and + for work that grows with what was parsed before it, not with the bytes + read again, like the walks listed under "Why". Time nested and repeated + shapes in a release build, doubling their size. + `lpm-security`'s `parenthesized_lists_parsed_just_above_the_floor_become_parameters_or_expressions_without_overflowing` - test parses each shape it lists to the deepest nesting that fits. If the - release changes how the parser speculates or takes checkpoints, measure - again how much speculative work real code takes, against + test parses each shape it lists to the deepest nesting that fits, and + its `syntax.rs` timing tests cover the walks above. If the release + changes how the parser speculates or takes checkpoints, measure again + how much speculative work real code takes, against `PARSE_SPECULATION_PER_BYTE` in `lpm-security`'s `behavioral/syntax.rs`, and check that the sources its budget tests nest still speculate. 5. Bump every `oxc_*` dependency in the workspace to the same release: diff --git a/vendor/oxc_parser/lpm-stack-floor.patch b/vendor/oxc_parser/lpm-stack-floor.patch index f996bec54..5fb348e04 100644 --- a/vendor/oxc_parser/lpm-stack-floor.patch +++ b/vendor/oxc_parser/lpm-stack-floor.patch @@ -16,7 +16,21 @@ lexer::{Kind, LexerCheckpoint, Token, cold_branch}, }; -@@ -108,13 +110,85 @@ +@@ -20,6 +22,13 @@ + has_fatal_error: bool, + } + ++impl ParserCheckpoint<'_> { ++ /// Start of the token the parser was at when the checkpoint was taken. ++ pub(crate) fn token_start(&self) -> u32 { ++ self.cur_token.start() ++ } ++} ++ + impl<'a, C: Config> ParserImpl<'a, C> { + /// Get current token's span start. + #[inline] +@@ -108,13 +117,87 @@ if self.token.escaped() && kind.is_any_keyword() { self.report_escaped_keyword(self.token.span()); } @@ -29,13 +43,13 @@ + /// `ParseOptions::stack_floor` or speculative parses have spent more + /// than `ParseOptions::speculation_budget` allows, and on every token + /// read after that. The fatal error moves the lexer to the end of the source, -+ /// so every caller unwinds without reading more tokens. ++ /// so every caller unwinds without reading more tokens. Reaching either limit ++ /// raises the lexer's `stop_below` past every address, so this is one ++ /// comparison per token. + #[inline] + fn check_parse_limits(&mut self) { -+ if self.stack_exhausted.get() -+ || self.lexer.speculation_budget_exhausted() -+ || self.below_stack_floor() -+ { ++ let marker = 0u8; ++ if (&raw const marker).addr() < self.lexer.stop_below() { + self.stop_at_parse_limit(); + } + } @@ -70,6 +84,7 @@ + #[inline(never)] + fn stop_at_stack_floor(&mut self) { + self.stack_exhausted.set(true); ++ self.lexer.stop_before_every_token(); + self.set_fatal_error(diagnostics::stack_exhausted(self.token.span())); + } + @@ -92,6 +107,7 @@ + #[inline(never)] + pub(crate) fn stack_floor_error(&self, span: Span) -> ParserDiagnostic<'a> { + self.stack_exhausted.set(true); ++ self.lexer.stop_before_every_token(); + diagnostics::stack_exhausted(span) + } + @@ -102,7 +118,7 @@ self.prev_token_end = self.token.end(); self.token = self.lexer.next_jsx_child(); } -@@ -170,6 +244,9 @@ +@@ -170,6 +253,9 @@ if self.token.escaped() && self.token.kind().is_any_keyword() { self.report_escaped_keyword(self.token.span()); } @@ -112,7 +128,7 @@ self.prev_token_end = self.token.end(); self.token = next; } -@@ -263,6 +340,7 @@ +@@ -263,6 +349,7 @@ /// Move to the next token, lexing it as a JSX attribute value. pub(crate) fn advance_for_jsx_attribute_value(&mut self) { @@ -197,7 +213,24 @@ --- a/src/js/expression.rs +++ b/src/js/expression.rs -@@ -408,6 +408,7 @@ +@@ -1,7 +1,7 @@ + use std::num::NonZeroU32; + + use cow_utils::CowUtils; +-use oxc_allocator::{ArenaBox, ArenaVec, GetAllocator, ReplaceWith}; ++use oxc_allocator::{Address, ArenaBox, ArenaVec, GetAddress, GetAllocator, ReplaceWith}; + use oxc_ast::ast::*; + use oxc_data_structures::buffered_vec::BufferedVec; + #[cfg(feature = "regular_expression")] +@@ -9,6 +9,7 @@ + use oxc_span::{GetSpan, Span}; + use oxc_str::{Ident, JSStr, Str}; + use oxc_syntax::precedence::Precedence; ++use rustc_hash::FxHashMap; + + use super::{ + grammar::CoverGrammar, +@@ -408,6 +409,7 @@ } if self.options.preserve_parens { @@ -205,7 +238,19 @@ Expression::new_parenthesized_expression(self.end_span(start), expression, self) } else { expression -@@ -1939,34 +1940,36 @@ +@@ -1922,7 +1924,10 @@ + comments: (u32, NonZeroU32), + expr: &mut Expression<'a>, + ) { +- if Self::set_pure_on_call_or_new_expr(expr) { ++ let start = expr.address(); ++ let applied = Self::set_pure_on_call_or_new_expr(expr, &self.state.pure_walks); ++ self.state.pure_walks.insert(start, applied); ++ if applied { + self.lexer.trivia_builder.mark_pure_comments_applied(comments); + } + } +@@ -1939,34 +1944,49 @@ } } @@ -214,7 +259,17 @@ - Expression::CallExpression(call_expr) => { - call_expr.pure = true; - true -- } ++ /// Walks down wrappers and a member chain in a loop: the parser reads a chain without ++ /// recursing, so recursing once per member here could overflow the stack. Reaching an ++ /// expression an earlier walk started at, it takes that walk's answer from `walked`. ++ fn set_pure_on_call_or_new_expr( ++ mut expr: &mut Expression<'a>, ++ walked: &FxHashMap, ++ ) -> bool { ++ loop { ++ if let Some(&applied) = walked.get(&expr.address()) { ++ return applied; + } - Expression::NewExpression(new_expr) => { - new_expr.pure = true; - true @@ -224,11 +279,13 @@ - } - Expression::ChainExpression(chain_expr) => match &mut chain_expr.expression { - ChainElement::CallExpression(call_expr) => { -+ /// Walks down a member chain in a loop: the parser reads a chain without recursing, so -+ /// recursing once per member here could overflow the stack. -+ fn set_pure_on_call_or_new_expr(mut expr: &mut Expression<'a>) -> bool { -+ loop { -+ expr = match expr.get_inner_expression_mut() { ++ expr = match expr { ++ Expression::ParenthesizedExpression(wrapper) => &mut wrapper.expression, ++ Expression::TSAsExpression(wrapper) => &mut wrapper.expression, ++ Expression::TSSatisfiesExpression(wrapper) => &mut wrapper.expression, ++ Expression::TSInstantiationExpression(wrapper) => &mut wrapper.expression, ++ Expression::TSNonNullExpression(wrapper) => &mut wrapper.expression, ++ Expression::TSTypeAssertion(wrapper) => &mut wrapper.expression, + Expression::CallExpression(call_expr) => { call_expr.pure = true; - true @@ -389,7 +446,16 @@ } --- a/src/lexer/mod.rs +++ b/src/lexer/mod.rs -@@ -130,6 +130,20 @@ +@@ -5,7 +5,7 @@ + //! * [rustc](https://github.com/rust-lang/rust/blob/1.82.0/compiler/rustc_lexer/src) + //! * [v8](https://v8.dev/blog/scanner) + +-use std::mem; ++use std::{cell::Cell, mem}; + + use rustc_hash::FxHashMap; + +@@ -130,6 +130,25 @@ /// Config pub(crate) config: C, @@ -404,30 +470,48 @@ + /// `ParseOptions::speculation_budget`, with `u64::MAX` for no limit. + speculation_limit: u64, + ++ /// The stack address below which the parser stops before reading another token: ++ /// `ParseOptions::stack_floor`, and `usize::MAX` once a parse limit is reached. One ++ /// comparison per token covers both limits. ++ stop_below: Cell, ++ + /// A rewind left the lexer having read more beyond its position than + /// `speculation_limit` allows. + speculation_budget_exhausted: bool, } impl<'a, C: Config> Lexer<'a, C> { -@@ -176,9 +190,27 @@ +@@ -176,9 +195,40 @@ escaped_templates: FxHashMap::default(), tokens, config, + bytes_rewound: 0, + bytes_skipped: 0, + speculation_limit: u64::MAX, ++ stop_below: Cell::new(0), + speculation_budget_exhausted: false, } } -+ /// Limit the bytes the lexer may read beyond its position, by rewinding, to `budget`. -+ /// `0` is no limit. -+ pub(crate) fn with_speculation_budget(mut self, budget: u64) -> Self { ++ /// Stop the parse below `stack_floor`, and once the lexer has read more than `budget` ++ /// bytes beyond its position by rewinding. `0` is no limit for either. ++ pub(crate) fn with_parse_limits(mut self, stack_floor: usize, budget: u64) -> Self { ++ self.stop_below.set(stack_floor); + self.speculation_limit = if budget == 0 { u64::MAX } else { budget }; + self + } + ++ /// See [`Self::stop_below`]. ++ #[inline] ++ pub(crate) fn stop_below(&self) -> usize { ++ self.stop_below.get() ++ } ++ ++ /// Make the parser stop before every token it reads from now on. ++ pub(crate) fn stop_before_every_token(&self) { ++ self.stop_below.set(usize::MAX); ++ } ++ + /// Whether a rewind went past the speculation budget. Every rewind, the parser's and the + /// lexer's own lookaheads', checks it, and it stays set. + #[inline] @@ -438,7 +522,7 @@ /// Create a [`Lexer`], and call `f` with it. Returns what `f` returns. /// /// The `Lexer` is passed to `f`, not returned, because that's what makes `'brand` -@@ -239,10 +271,22 @@ +@@ -239,10 +289,23 @@ self.errors.truncate(checkpoint.errors_len); self.tokens.truncate(checkpoint.tokens_len); @@ -447,6 +531,7 @@ + self.bytes_rewound += u64::from(from.saturating_sub(self.offset())); + if self.bytes_read_ahead() > self.speculation_limit { + self.speculation_budget_exhausted = true; ++ self.stop_before_every_token(); + } self.trivia_builder.rewind(checkpoint.trivia); } @@ -461,7 +546,7 @@ /// Make rewinding to `checkpoint` keep the comments and irregular whitespace lexed after it. pub(crate) fn keep_trivia(&self, checkpoint: &mut LexerCheckpoint<'a>) { self.trivia_builder.keep_trivia(&mut checkpoint.trivia); -@@ -570,7 +614,9 @@ +@@ -570,7 +633,9 @@ /// Advance source cursor to end of file. #[inline] pub fn advance_to_end(&mut self) { @@ -482,6 +567,15 @@ mod ast_builder; pub mod config; +@@ -96,7 +96,7 @@ + }; + use oxc_data_structures::brands::{BrandOrigin, BrandScope, Unbranded}; + use oxc_diagnostics::Diagnostics; +-use oxc_span::{SourceType, Span}; ++use oxc_span::{GetSpan, SourceType, Span}; + use oxc_syntax::module_record::ModuleRecord; + + pub use crate::lexer::{Kind, Token}; @@ -221,6 +221,17 @@ /// Whether the file is [flow](https://flow.org). @@ -560,7 +654,7 @@ brand_origin, - ), + ) -+ .with_speculation_budget(options.speculation_budget), ++ .with_parse_limits(options.stack_floor, options.speculation_budget), source_type, source_text, errors: vec![], @@ -582,18 +676,182 @@ } } +@@ -836,7 +885,16 @@ + if self.lexer.config.tokens() { checkpoints.len() } else { 0 }, + self, + ); ++ let original_spans: Vec = statements.iter().map(GetSpan::span).collect(); ++ let mut replaced_statements = Vec::new(); ++ let mut reparsed_until = 0; + for (stmt_index, checkpoint) in checkpoints { ++ // A statement parsed again can take in the candidates after it, as in ++ // `await\nawait 0`. They are part of it, and parsing each of them again as well ++ // took time and memory quadratic in their number. ++ if checkpoint.token_start() < reparsed_until { ++ continue; ++ } + // Only the statement is parsed again, so trivia after it is not lexed again. + self.rewind_keeping_trivia(checkpoint); + let replacement_start = replacements.len(); +@@ -852,14 +910,27 @@ + } + let edit_start = original_index; + +- // Parse the statement with await context enabled (TopLevel context is already set) +- let stmt = self.context_add(Context::Await, |p| { +- p.parse_statement_list_item(StatementContext::Program) +- }); ++ // Parse the statement with await context enabled (TopLevel context is already set). ++ // It can end inside a statement the first parse read, as `await\nawait /x/` does ++ // inside `await / x / foo()`: parse on to the end of one, so the rest is parsed again. ++ let mut reparsed = ArenaVec::new_in(self); ++ loop { ++ let start = self.prev_token_end; ++ let stmt = self.context_add(Context::Await, |p| { ++ p.parse_statement_list_item(StatementContext::Program) ++ }); ++ reparsed.push(stmt); ++ let end = self.prev_token_end; ++ let following = original_spans.partition_point(|span| span.start < end); ++ let ends_inside = following > 0 && original_spans[following - 1].end > end; ++ if !ends_inside || end <= start || self.has_fatal_error() { ++ break; ++ } ++ } + +- // Replace the statement if the index is valid ++ reparsed_until = self.prev_token_end; + if stmt_index < statements.len() { +- statements[stmt_index] = stmt; ++ replaced_statements.push((stmt_index, reparsed)); + } + + if self.lexer.config.tokens() { +@@ -883,6 +954,30 @@ + edits.push((edit_start..original_index, replacement_start..replacements.len())); + } + } ++ ++ if !replaced_statements.is_empty() { ++ let added: usize = replaced_statements.iter().map(|(_, new)| new.len() - 1).sum(); ++ let mut replaced_statements = replaced_statements.into_iter().peekable(); ++ let mut rebuilt = ArenaVec::with_capacity_in(statements.len() + added, self); ++ for (index, statement) in statements.drain(..).enumerate() { ++ match replaced_statements.next_if(|(replaced, _)| *replaced == index) { ++ Some((_, new)) => rebuilt.extend(new), ++ None => rebuilt.push(statement), ++ } ++ } ++ *statements = rebuilt; ++ } ++ ++ // Drop the statements that statements parsed again took in, so none overlap. One that ++ // reaches past them, which only a parse again stopped by an error leaves, stays: an ++ // overlap loses no code. ++ let mut covered_until = 0; ++ statements.retain(|statement| { ++ let span = statement.span(); ++ let covered = span.start < covered_until && span.end <= covered_until; ++ covered_until = covered_until.max(span.end); ++ !covered ++ }); + + if let Some(mut tokens) = original_tokens { + let mut read = 0; +--- a/src/module_record.rs ++++ b/src/module_record.rs +@@ -5,6 +5,7 @@ + use oxc_ecmascript::BoundNames; + use oxc_span::{GetSpan, Span}; + use oxc_syntax::module_record::*; ++use rustc_hash::FxHashMap; + + use crate::diagnostics; + +@@ -60,8 +61,20 @@ + &exported_bindings_duplicated, + &skipped_default_exports, + ); +- module_record.dynamic_imports = dynamic_imports.into_vec(); +- module_record.import_metas = import_metas.into_vec(); ++ // A statement parsed again as a module records its dynamic imports and `import.meta` ++ // again, after the ones that follow it. ++ let mut dynamic_imports = dynamic_imports.into_vec(); ++ if !dynamic_imports.is_sorted_by(|a, b| a.span.start < b.span.start) { ++ dynamic_imports.sort_unstable_by_key(|import| import.span.start); ++ dynamic_imports.dedup_by_key(|import| import.span); ++ } ++ module_record.dynamic_imports = dynamic_imports; ++ let mut import_metas = import_metas.into_vec(); ++ if !import_metas.is_sorted_by(|a, b| a.start < b.start) { ++ import_metas.sort_unstable_by_key(|span| span.start); ++ import_metas.dedup(); ++ } ++ module_record.import_metas = import_metas; + (module_record, errors) + } + +@@ -157,6 +170,25 @@ + } + } + ++ // A local export looks its name up among the import entries. Past a few of them, an ++ // index by local name keeps many exports of many imports linear. It keeps the first ++ // entry for each name, as the search does. ++ let imports_by_local_name = (module_record.import_entries.len() > 16 ++ && export_entries.iter().any(|entry| { ++ entry.module_request.is_none() ++ && matches!(entry.local_name, ExportLocalName::Name(_)) ++ })) ++ .then(|| { ++ let mut index = FxHashMap::with_capacity_and_hasher( ++ module_record.import_entries.len(), ++ Default::default(), ++ ); ++ for (position, import) in module_record.import_entries.iter().enumerate() { ++ index.entry(import.local_name.name).or_insert(position); ++ } ++ index ++ }); ++ + // Retain local exports in their original buffer, avoiding a second arena allocation. + // 10. For each ExportEntry Record ee of exportEntries, do + export_entries.retain_mut(|entry| { +@@ -167,11 +199,16 @@ + // 1. Append ee to localExportEntries. + return true; + }; +- let Some(import) = module_record +- .import_entries +- .iter() +- .find(|import| import.local_name.name == local_name.name) +- else { ++ let import = match &imports_by_local_name { ++ Some(index) => index ++ .get(&local_name.name) ++ .map(|&position| &module_record.import_entries[position]), ++ None => module_record ++ .import_entries ++ .iter() ++ .find(|import| import.local_name.name == local_name.name), ++ }; ++ let Some(import) = import else { + // i. If ee.[[LocalName]] is not an element of importedBoundNames, then + // 1. Append ee to localExportEntries. + return true; --- a/src/state.rs +++ b/src/state.rs -@@ -1,5 +1,7 @@ --use rustc_hash::{FxHashMap, FxHashSet}; +@@ -1,6 +1,8 @@ +use std::collections::BTreeMap; - -+use rustc_hash::FxHashSet; + - use oxc_allocator::{Allocator, ArenaVec}; + use rustc_hash::{FxHashMap, FxHashSet}; + +-use oxc_allocator::{Allocator, ArenaVec}; ++use oxc_allocator::{Address, Allocator, ArenaVec}; use oxc_ast::ast::Expression; use oxc_span::Span; -@@ -43,6 +45,13 @@ + +@@ -43,6 +45,21 @@ /// Like `cover_elements`, each cover list owns the entries above its recorded length. pub cover_parenthesized: ArenaVec<'a, u32>, @@ -603,11 +861,19 @@ + /// quadratic in its length. A rewind leaves no stale entry: only a parse of the same offset + /// can build another `ParenthesizedExpression` that starts there, and it records its own. + pub last_parenthesized: (u32, u32), ++ ++ /// Where each walk for a `/*#__PURE__*/` comment started, as the address of the expression ++ /// after the comment, and whether it found a call. Nested `/*#__PURE__*/(` wraps each level's ++ /// expression around one a level inside it walked, so a walk stops at the first start it ++ /// reaches and takes its answer. Each node is then walked at most once. An address can't ++ /// name another node: the arena never frees or reuses one, and no node on a walked path ++ /// changes after its walk. ++ pub pure_walks: FxHashMap, + /// Zero outside speculative expression type arguments; otherwise their nesting depth. pub type_argument_depth: u32, -@@ -51,12 +60,17 @@ +@@ -51,12 +68,17 @@ /// Temporary storage for `CoverInitializedName` `({ foo = bar })`. /// Keyed by `ObjectProperty`'s span.start. @@ -627,11 +893,12 @@ /// Statements that may need reparsing when `sourceType` is `unambiguous`. /// -@@ -81,10 +95,11 @@ +@@ -81,10 +103,12 @@ mentions_await: false, cover_depth: 0, cover_parenthesized: ArenaVec::new_in(&allocator), + last_parenthesized: (u32::MAX, u32::MAX), ++ pure_walks: FxHashMap::default(), type_argument_depth: 0, type_argument_lookahead: None, - cover_initialized_name: FxHashMap::default(), diff --git a/vendor/oxc_parser/src/cursor.rs b/vendor/oxc_parser/src/cursor.rs index d595db26e..642c082f5 100644 --- a/vendor/oxc_parser/src/cursor.rs +++ b/vendor/oxc_parser/src/cursor.rs @@ -22,6 +22,13 @@ pub struct ParserCheckpoint<'a> { has_fatal_error: bool, } +impl ParserCheckpoint<'_> { + /// Start of the token the parser was at when the checkpoint was taken. + pub(crate) fn token_start(&self) -> u32 { + self.cur_token.start() + } +} + impl<'a, C: Config> ParserImpl<'a, C> { /// Get current token's span start. #[inline] @@ -119,13 +126,13 @@ impl<'a, C: Config> ParserImpl<'a, C> { /// `ParseOptions::stack_floor` or speculative parses have spent more /// than `ParseOptions::speculation_budget` allows, and on every token /// read after that. The fatal error moves the lexer to the end of the source, - /// so every caller unwinds without reading more tokens. + /// so every caller unwinds without reading more tokens. Reaching either limit + /// raises the lexer's `stop_below` past every address, so this is one + /// comparison per token. #[inline] fn check_parse_limits(&mut self) { - if self.stack_exhausted.get() - || self.lexer.speculation_budget_exhausted() - || self.below_stack_floor() - { + let marker = 0u8; + if (&raw const marker).addr() < self.lexer.stop_below() { self.stop_at_parse_limit(); } } @@ -160,6 +167,7 @@ impl<'a, C: Config> ParserImpl<'a, C> { #[inline(never)] fn stop_at_stack_floor(&mut self) { self.stack_exhausted.set(true); + self.lexer.stop_before_every_token(); self.set_fatal_error(diagnostics::stack_exhausted(self.token.span())); } @@ -182,6 +190,7 @@ impl<'a, C: Config> ParserImpl<'a, C> { #[inline(never)] pub(crate) fn stack_floor_error(&self, span: Span) -> ParserDiagnostic<'a> { self.stack_exhausted.set(true); + self.lexer.stop_before_every_token(); diagnostics::stack_exhausted(span) } diff --git a/vendor/oxc_parser/src/js/expression.rs b/vendor/oxc_parser/src/js/expression.rs index 2b1eeb978..8492dba81 100644 --- a/vendor/oxc_parser/src/js/expression.rs +++ b/vendor/oxc_parser/src/js/expression.rs @@ -1,7 +1,7 @@ use std::num::NonZeroU32; use cow_utils::CowUtils; -use oxc_allocator::{ArenaBox, ArenaVec, GetAllocator, ReplaceWith}; +use oxc_allocator::{Address, ArenaBox, ArenaVec, GetAddress, GetAllocator, ReplaceWith}; use oxc_ast::ast::*; use oxc_data_structures::buffered_vec::BufferedVec; #[cfg(feature = "regular_expression")] @@ -9,6 +9,7 @@ use oxc_regular_expression::ast::Pattern; use oxc_span::{GetSpan, Span}; use oxc_str::{Ident, JSStr, Str}; use oxc_syntax::precedence::Precedence; +use rustc_hash::FxHashMap; use super::{ grammar::CoverGrammar, @@ -1923,7 +1924,10 @@ impl<'a, C: Config> ParserImpl<'a, C> { comments: (u32, NonZeroU32), expr: &mut Expression<'a>, ) { - if Self::set_pure_on_call_or_new_expr(expr) { + let start = expr.address(); + let applied = Self::set_pure_on_call_or_new_expr(expr, &self.state.pure_walks); + self.state.pure_walks.insert(start, applied); + if applied { self.lexer.trivia_builder.mark_pure_comments_applied(comments); } } @@ -1940,11 +1944,24 @@ impl<'a, C: Config> ParserImpl<'a, C> { } } - /// Walks down a member chain in a loop: the parser reads a chain without recursing, so - /// recursing once per member here could overflow the stack. - fn set_pure_on_call_or_new_expr(mut expr: &mut Expression<'a>) -> bool { + /// Walks down wrappers and a member chain in a loop: the parser reads a chain without + /// recursing, so recursing once per member here could overflow the stack. Reaching an + /// expression an earlier walk started at, it takes that walk's answer from `walked`. + fn set_pure_on_call_or_new_expr( + mut expr: &mut Expression<'a>, + walked: &FxHashMap, + ) -> bool { loop { - expr = match expr.get_inner_expression_mut() { + if let Some(&applied) = walked.get(&expr.address()) { + return applied; + } + expr = match expr { + Expression::ParenthesizedExpression(wrapper) => &mut wrapper.expression, + Expression::TSAsExpression(wrapper) => &mut wrapper.expression, + Expression::TSSatisfiesExpression(wrapper) => &mut wrapper.expression, + Expression::TSInstantiationExpression(wrapper) => &mut wrapper.expression, + Expression::TSNonNullExpression(wrapper) => &mut wrapper.expression, + Expression::TSTypeAssertion(wrapper) => &mut wrapper.expression, Expression::CallExpression(call_expr) => { call_expr.pure = true; return true; diff --git a/vendor/oxc_parser/src/lexer/mod.rs b/vendor/oxc_parser/src/lexer/mod.rs index 952831620..a78a2aa57 100644 --- a/vendor/oxc_parser/src/lexer/mod.rs +++ b/vendor/oxc_parser/src/lexer/mod.rs @@ -5,7 +5,7 @@ //! * [rustc](https://github.com/rust-lang/rust/blob/1.82.0/compiler/rustc_lexer/src) //! * [v8](https://v8.dev/blog/scanner) -use std::mem; +use std::{cell::Cell, mem}; use rustc_hash::FxHashMap; @@ -141,6 +141,11 @@ pub struct Lexer<'a, C: Config> { /// `ParseOptions::speculation_budget`, with `u64::MAX` for no limit. speculation_limit: u64, + /// The stack address below which the parser stops before reading another token: + /// `ParseOptions::stack_floor`, and `usize::MAX` once a parse limit is reached. One + /// comparison per token covers both limits. + stop_below: Cell, + /// A rewind left the lexer having read more beyond its position than /// `speculation_limit` allows. speculation_budget_exhausted: bool, @@ -193,17 +198,30 @@ impl<'a, C: Config> Lexer<'a, C> { bytes_rewound: 0, bytes_skipped: 0, speculation_limit: u64::MAX, + stop_below: Cell::new(0), speculation_budget_exhausted: false, } } - /// Limit the bytes the lexer may read beyond its position, by rewinding, to `budget`. - /// `0` is no limit. - pub(crate) fn with_speculation_budget(mut self, budget: u64) -> Self { + /// Stop the parse below `stack_floor`, and once the lexer has read more than `budget` + /// bytes beyond its position by rewinding. `0` is no limit for either. + pub(crate) fn with_parse_limits(mut self, stack_floor: usize, budget: u64) -> Self { + self.stop_below.set(stack_floor); self.speculation_limit = if budget == 0 { u64::MAX } else { budget }; self } + /// See [`Self::stop_below`]. + #[inline] + pub(crate) fn stop_below(&self) -> usize { + self.stop_below.get() + } + + /// Make the parser stop before every token it reads from now on. + pub(crate) fn stop_before_every_token(&self) { + self.stop_below.set(usize::MAX); + } + /// Whether a rewind went past the speculation budget. Every rewind, the parser's and the /// lexer's own lookaheads', checks it, and it stays set. #[inline] @@ -276,6 +294,7 @@ impl<'a, C: Config> Lexer<'a, C> { self.bytes_rewound += u64::from(from.saturating_sub(self.offset())); if self.bytes_read_ahead() > self.speculation_limit { self.speculation_budget_exhausted = true; + self.stop_before_every_token(); } self.trivia_builder.rewind(checkpoint.trivia); } diff --git a/vendor/oxc_parser/src/lib.rs b/vendor/oxc_parser/src/lib.rs index 88385cd74..c8d351a5c 100644 --- a/vendor/oxc_parser/src/lib.rs +++ b/vendor/oxc_parser/src/lib.rs @@ -96,7 +96,7 @@ use oxc_ast::{ }; use oxc_data_structures::brands::{BrandOrigin, BrandScope, Unbranded}; use oxc_diagnostics::Diagnostics; -use oxc_span::{SourceType, Span}; +use oxc_span::{GetSpan, SourceType, Span}; use oxc_syntax::module_record::ModuleRecord; pub use crate::lexer::{Kind, Token}; @@ -634,7 +634,7 @@ impl<'a, C: ParserConfig> ParserImpl<'a, C> { config.lexer_config(), brand_origin, ) - .with_speculation_budget(options.speculation_budget), + .with_parse_limits(options.stack_floor, options.speculation_budget), source_type, source_text, errors: vec![], @@ -885,7 +885,16 @@ impl<'a, C: ParserConfig> ParserImpl<'a, C> { if self.lexer.config.tokens() { checkpoints.len() } else { 0 }, self, ); + let original_spans: Vec = statements.iter().map(GetSpan::span).collect(); + let mut replaced_statements = Vec::new(); + let mut reparsed_until = 0; for (stmt_index, checkpoint) in checkpoints { + // A statement parsed again can take in the candidates after it, as in + // `await\nawait 0`. They are part of it, and parsing each of them again as well + // took time and memory quadratic in their number. + if checkpoint.token_start() < reparsed_until { + continue; + } // Only the statement is parsed again, so trivia after it is not lexed again. self.rewind_keeping_trivia(checkpoint); let replacement_start = replacements.len(); @@ -901,14 +910,27 @@ impl<'a, C: ParserConfig> ParserImpl<'a, C> { } let edit_start = original_index; - // Parse the statement with await context enabled (TopLevel context is already set) - let stmt = self.context_add(Context::Await, |p| { - p.parse_statement_list_item(StatementContext::Program) - }); + // Parse the statement with await context enabled (TopLevel context is already set). + // It can end inside a statement the first parse read, as `await\nawait /x/` does + // inside `await / x / foo()`: parse on to the end of one, so the rest is parsed again. + let mut reparsed = ArenaVec::new_in(self); + loop { + let start = self.prev_token_end; + let stmt = self.context_add(Context::Await, |p| { + p.parse_statement_list_item(StatementContext::Program) + }); + reparsed.push(stmt); + let end = self.prev_token_end; + let following = original_spans.partition_point(|span| span.start < end); + let ends_inside = following > 0 && original_spans[following - 1].end > end; + if !ends_inside || end <= start || self.has_fatal_error() { + break; + } + } - // Replace the statement if the index is valid + reparsed_until = self.prev_token_end; if stmt_index < statements.len() { - statements[stmt_index] = stmt; + replaced_statements.push((stmt_index, reparsed)); } if self.lexer.config.tokens() { @@ -933,6 +955,30 @@ impl<'a, C: ParserConfig> ParserImpl<'a, C> { } } + if !replaced_statements.is_empty() { + let added: usize = replaced_statements.iter().map(|(_, new)| new.len() - 1).sum(); + let mut replaced_statements = replaced_statements.into_iter().peekable(); + let mut rebuilt = ArenaVec::with_capacity_in(statements.len() + added, self); + for (index, statement) in statements.drain(..).enumerate() { + match replaced_statements.next_if(|(replaced, _)| *replaced == index) { + Some((_, new)) => rebuilt.extend(new), + None => rebuilt.push(statement), + } + } + *statements = rebuilt; + } + + // Drop the statements that statements parsed again took in, so none overlap. One that + // reaches past them, which only a parse again stopped by an error leaves, stays: an + // overlap loses no code. + let mut covered_until = 0; + statements.retain(|statement| { + let span = statement.span(); + let covered = span.start < covered_until && span.end <= covered_until; + covered_until = covered_until.max(span.end); + !covered + }); + if let Some(mut tokens) = original_tokens { let mut read = 0; if edits.iter().all(|(range, replacement)| replacement.len() <= range.len()) { diff --git a/vendor/oxc_parser/src/module_record.rs b/vendor/oxc_parser/src/module_record.rs index a6660743e..e2aa57e64 100644 --- a/vendor/oxc_parser/src/module_record.rs +++ b/vendor/oxc_parser/src/module_record.rs @@ -5,6 +5,7 @@ use oxc_diagnostics::OxcDiagnostic; use oxc_ecmascript::BoundNames; use oxc_span::{GetSpan, Span}; use oxc_syntax::module_record::*; +use rustc_hash::FxHashMap; use crate::diagnostics; @@ -60,8 +61,20 @@ impl<'a> ModuleRecordBuilder<'a> { &exported_bindings_duplicated, &skipped_default_exports, ); - module_record.dynamic_imports = dynamic_imports.into_vec(); - module_record.import_metas = import_metas.into_vec(); + // A statement parsed again as a module records its dynamic imports and `import.meta` + // again, after the ones that follow it. + let mut dynamic_imports = dynamic_imports.into_vec(); + if !dynamic_imports.is_sorted_by(|a, b| a.span.start < b.span.start) { + dynamic_imports.sort_unstable_by_key(|import| import.span.start); + dynamic_imports.dedup_by_key(|import| import.span); + } + module_record.dynamic_imports = dynamic_imports; + let mut import_metas = import_metas.into_vec(); + if !import_metas.is_sorted_by(|a, b| a.start < b.start) { + import_metas.sort_unstable_by_key(|span| span.start); + import_metas.dedup(); + } + module_record.import_metas = import_metas; (module_record, errors) } @@ -157,6 +170,25 @@ impl<'a> ModuleRecordBuilder<'a> { } } + // A local export looks its name up among the import entries. Past a few of them, an + // index by local name keeps many exports of many imports linear. It keeps the first + // entry for each name, as the search does. + let imports_by_local_name = (module_record.import_entries.len() > 16 + && export_entries.iter().any(|entry| { + entry.module_request.is_none() + && matches!(entry.local_name, ExportLocalName::Name(_)) + })) + .then(|| { + let mut index = FxHashMap::with_capacity_and_hasher( + module_record.import_entries.len(), + Default::default(), + ); + for (position, import) in module_record.import_entries.iter().enumerate() { + index.entry(import.local_name.name).or_insert(position); + } + index + }); + // Retain local exports in their original buffer, avoiding a second arena allocation. // 10. For each ExportEntry Record ee of exportEntries, do export_entries.retain_mut(|entry| { @@ -167,11 +199,16 @@ impl<'a> ModuleRecordBuilder<'a> { // 1. Append ee to localExportEntries. return true; }; - let Some(import) = module_record - .import_entries - .iter() - .find(|import| import.local_name.name == local_name.name) - else { + let import = match &imports_by_local_name { + Some(index) => index + .get(&local_name.name) + .map(|&position| &module_record.import_entries[position]), + None => module_record + .import_entries + .iter() + .find(|import| import.local_name.name == local_name.name), + }; + let Some(import) = import else { // i. If ee.[[LocalName]] is not an element of importedBoundNames, then // 1. Append ee to localExportEntries. return true; diff --git a/vendor/oxc_parser/src/state.rs b/vendor/oxc_parser/src/state.rs index 7facefa4c..298f47337 100644 --- a/vendor/oxc_parser/src/state.rs +++ b/vendor/oxc_parser/src/state.rs @@ -1,8 +1,8 @@ use std::collections::BTreeMap; -use rustc_hash::FxHashSet; +use rustc_hash::{FxHashMap, FxHashSet}; -use oxc_allocator::{Allocator, ArenaVec}; +use oxc_allocator::{Address, Allocator, ArenaVec}; use oxc_ast::ast::Expression; use oxc_span::Span; @@ -52,6 +52,14 @@ pub struct ParserState<'a> { /// can build another `ParenthesizedExpression` that starts there, and it records its own. pub last_parenthesized: (u32, u32), + /// Where each walk for a `/*#__PURE__*/` comment started, as the address of the expression + /// after the comment, and whether it found a call. Nested `/*#__PURE__*/(` wraps each level's + /// expression around one a level inside it walked, so a walk stops at the first start it + /// reaches and takes its answer. Each node is then walked at most once. An address can't + /// name another node: the arena never frees or reuses one, and no node on a walked path + /// changes after its walk. + pub pure_walks: FxHashMap, + /// Zero outside speculative expression type arguments; otherwise their nesting depth. pub type_argument_depth: u32, @@ -96,6 +104,7 @@ impl<'a> ParserState<'a> { cover_depth: 0, cover_parenthesized: ArenaVec::new_in(&allocator), last_parenthesized: (u32::MAX, u32::MAX), + pure_walks: FxHashMap::default(), type_argument_depth: 0, type_argument_lookahead: None, cover_initialized_name: BTreeMap::new(),