From 52d3117f73d222f2d3b2fbe96ecfd27e9953ccd3 Mon Sep 17 00:00:00 2001 From: Tolga Ergin Date: Wed, 25 Nov 2026 01:13:49 +0000 Subject: [PATCH 1/4] Take oxc 0.160 and carry the parser's stack floor and speculation budget over Moves every oxc crate from 0.158.0 to 0.160.0 in one step, as the shared AST types and the vendored parser require, and rebases vendor/oxc_parser on 0.160.0. 0.160 parses a parenthesized list once and turns its elements into arrow parameters or an expression after its `)`. The patch now also checks the stack floor in advance_to, which moves to a token the lexer has already read, and in the new conversions and checks that turn those elements into parameters. The checks borrow the parser, so the stop is kept in a Cell and reported even when no further token is read. Checkpoints no longer copy the lexer's diagnostics, so the budget counts only bytes read again after rewinds. Across the 370,776 JavaScript and TypeScript files of a local package store, the most any file read again was 0.75 bytes per byte, and none used more than 30% of its budget. 0.160 gives a key written without brackets its own PropertyKey variants: StaticStringLiteral, StaticNumericLiteral and StaticBigIntLiteral. The threat rules matched `"name":` and `17:` keys by the old variants, which still compiled but no longer matched. That missed `rm` of the home directory through `const {'rmSync': remove} = require('fs')` and an environment upload through a bundle's numbered module table. They now match both forms. Tests: - Parenthesized lists that 0.158 parsed twice now parse in linear time. - The budget tests use TypeScript generic arrow heads nested in defaults, which 0.160 still parses twice per level. - The floor test now parses lists that become arrow parameters. - The deep-calls timing test runs on a 256 MiB stack, because a debug build of 0.160 parses its deepest source in more than 64 MiB. Dependabot proposes oxc crates as one group from now on. Co-Authored-By: Claude Opus 5.5 --- .github/dependabot.yml | 9 + Cargo.lock | 79 +- crates/lpm-cli/Cargo.toml | 10 +- crates/lpm-runner/Cargo.toml | 14 +- crates/lpm-security/Cargo.toml | 14 +- crates/lpm-security/src/behavioral/mod.rs | 85 +- crates/lpm-security/src/behavioral/syntax.rs | 75 +- crates/lpm-security/src/behavioral/threats.rs | 39 +- .../src/behavioral/threats/ancestry.rs | 17 +- .../src/behavioral/threats/archive_tests.rs | 10 +- .../src/behavioral/threats/bundles.rs | 3 +- vendor/oxc_parser/Cargo.toml | 33 +- vendor/oxc_parser/Cargo.toml.orig | 4 +- vendor/oxc_parser/LPM-PATCH.md | 106 +- vendor/oxc_parser/README.md | 10 +- vendor/oxc_parser/examples/parser.rs | 8 +- vendor/oxc_parser/examples/parser_tsx.rs | 6 +- .../oxc_parser/examples/regular_expression.rs | 33 +- vendor/oxc_parser/examples/visitor.rs | 8 +- vendor/oxc_parser/lpm-stack-floor.patch | 227 ++-- vendor/oxc_parser/src/context.rs | 50 +- vendor/oxc_parser/src/cursor.rs | 437 ++---- vendor/oxc_parser/src/diagnostics.rs | 19 +- vendor/oxc_parser/src/error_handler.rs | 1 + vendor/oxc_parser/src/js/arrow.rs | 1168 +++++++++++------ vendor/oxc_parser/src/js/binding.rs | 4 +- vendor/oxc_parser/src/js/class.rs | 124 +- vendor/oxc_parser/src/js/cover.rs | 919 +++++++++++++ vendor/oxc_parser/src/js/declaration.rs | 73 +- vendor/oxc_parser/src/js/expression.rs | 462 ++++--- vendor/oxc_parser/src/js/function.rs | 260 ++-- vendor/oxc_parser/src/js/grammar.rs | 403 +++++- vendor/oxc_parser/src/js/mod.rs | 4 + vendor/oxc_parser/src/js/module.rs | 53 +- vendor/oxc_parser/src/js/object.rs | 81 +- vendor/oxc_parser/src/js/statement.rs | 181 +-- vendor/oxc_parser/src/jsx/mod.rs | 272 ++-- vendor/oxc_parser/src/lexer/byte_handlers.rs | 743 ++++++----- vendor/oxc_parser/src/lexer/comment.rs | 707 +++++++--- vendor/oxc_parser/src/lexer/identifier.rs | 166 ++- vendor/oxc_parser/src/lexer/jsx.rs | 15 +- vendor/oxc_parser/src/lexer/keyword.rs | 113 ++ vendor/oxc_parser/src/lexer/kind.rs | 12 +- vendor/oxc_parser/src/lexer/mod.rs | 400 ++++-- vendor/oxc_parser/src/lexer/number.rs | 14 +- vendor/oxc_parser/src/lexer/numeric.rs | 33 +- vendor/oxc_parser/src/lexer/punctuation.rs | 10 +- vendor/oxc_parser/src/lexer/regex.rs | 14 +- vendor/oxc_parser/src/lexer/source.rs | 101 +- vendor/oxc_parser/src/lexer/string.rs | 329 ++++- vendor/oxc_parser/src/lexer/template.rs | 32 +- vendor/oxc_parser/src/lexer/token.rs | 337 ++--- vendor/oxc_parser/src/lexer/trivia_builder.rs | 755 +++++++---- vendor/oxc_parser/src/lexer/typescript.rs | 10 +- vendor/oxc_parser/src/lexer/unicode.rs | 210 +-- vendor/oxc_parser/src/lexer/whitespace.rs | 110 +- vendor/oxc_parser/src/lib.rs | 705 +++++----- vendor/oxc_parser/src/list.rs | 253 ++++ vendor/oxc_parser/src/modifiers.rs | 111 +- vendor/oxc_parser/src/module_record.rs | 306 +++-- vendor/oxc_parser/src/state.rs | 47 +- vendor/oxc_parser/src/ts/mod.rs | 3 + vendor/oxc_parser/src/ts/statement.rs | 38 +- vendor/oxc_parser/src/ts/type_arguments.rs | 236 ++++ vendor/oxc_parser/src/ts/types.rs | 371 +++++- 65 files changed, 7858 insertions(+), 3624 deletions(-) create mode 100644 vendor/oxc_parser/src/js/cover.rs create mode 100644 vendor/oxc_parser/src/lexer/keyword.rs create mode 100644 vendor/oxc_parser/src/list.rs create mode 100644 vendor/oxc_parser/src/ts/type_arguments.rs diff --git a/.github/dependabot.yml b/.github/dependabot.yml index 83f47dc07..9a6cc5a4d 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -79,6 +79,15 @@ updates: - "windows-*" exclude-patterns: - "windows-native-keyring-store" + # lpm-cli, lpm-runner and lpm-security pin every oxc crate to one + # release, and vendor/oxc_parser patches the parser for all of them, so + # a bump of any one alone can't build. Each release also needs that + # patch carried over by hand (vendor/oxc_parser/LPM-PATCH.md). This + # group must stay above the one below too. + oxc: + applies-to: version-updates + patterns: + - "oxc_*" rust-minor-and-patch: applies-to: version-updates update-types: diff --git a/Cargo.lock b/Cargo.lock index 31cfa5499..afe2957c0 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5164,9 +5164,9 @@ dependencies = [ [[package]] name = "oxc_allocator" -version = "0.158.0" +version = "0.160.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9f65d07f047239a6535aee5f9eb5f741ce9d7a19c13d3f5d68a507878368f847" +checksum = "fff8d79a61ccac3b777cc79317a3f1b8afdaa86489532d427c7eb42e1370790a" dependencies = [ "allocator-api2", "hashbrown 0.17.1", @@ -5176,9 +5176,9 @@ dependencies = [ [[package]] name = "oxc_ast" -version = "0.158.0" +version = "0.160.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "01a1cff5a82c7f5480d1103288072df539da8ca8aa3d9acb29f5381c45799420" +checksum = "a343abb24d332d5b4cb71cb73ebec6844bb52e18d35e7e96395a09cbd55e27bc" dependencies = [ "bitflags 2.13.2", "oxc_allocator", @@ -5194,9 +5194,9 @@ dependencies = [ [[package]] name = "oxc_ast_macros" -version = "0.158.0" +version = "0.160.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e65142ee558d453f2d53bc20ebabccb4fbbccec3889fea4c5e595631ae70197e" +checksum = "19676b79dfb20271f963e1e66becb6532e7ba87b888d0542a7e20a79cf037fbe" dependencies = [ "phf 0.14.0", "proc-macro2", @@ -5206,9 +5206,9 @@ dependencies = [ [[package]] name = "oxc_ast_visit" -version = "0.158.0" +version = "0.160.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ab53ea63411df424b987fcf4830afe8be259a9d95585f34610603bae61e4eb94" +checksum = "28c94c27823c5f321eb4e9bf51bec581cf0d22522b6ac6e42276cb5cda0729d0" dependencies = [ "oxc_allocator", "oxc_ast", @@ -5218,9 +5218,9 @@ dependencies = [ [[package]] name = "oxc_codegen" -version = "0.158.0" +version = "0.160.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4e96b922b09e06196c28df4bc860b692957246ebf705fe1f49198871e0c91d81" +checksum = "bfd23bfa766e8f74bdd02783a09bc6bc8ad22bb11cb69b44969473cc40606576" dependencies = [ "bitflags 2.13.2", "cow-utils", @@ -5240,9 +5240,9 @@ dependencies = [ [[package]] name = "oxc_compat" -version = "0.158.0" +version = "0.160.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4a664fbec0ceda1154dff4744b0b94c5a60191faddf14916f11d16842c12a2a9" +checksum = "87fee33b02c0aac10d95e82528d83a18de80b36eb3089735553fc46e9a02f6cc" dependencies = [ "cow-utils", "oxc-browserslist", @@ -5253,18 +5253,18 @@ dependencies = [ [[package]] name = "oxc_data_structures" -version = "0.158.0" +version = "0.160.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "624adb3217f685fd08e5866ed1a2c9e3bd01878ad6dda1a8427308f9742c610d" +checksum = "829101f9ff612a0a01f66bd0d92ae42841c124317b2cd067e00e358588e2380f" dependencies = [ "ropey", ] [[package]] name = "oxc_diagnostics" -version = "0.158.0" +version = "0.160.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "768fdbb6291cab3d79b44e80e9fae84ce626ee5e54a5df6ca56c3ed1d835838b" +checksum = "867139409477751e9bb583922d335357948a3797ed425db7ed76a3f314f1e5b4" dependencies = [ "bytecount", "cow-utils", @@ -5280,9 +5280,9 @@ dependencies = [ [[package]] name = "oxc_ecmascript" -version = "0.158.0" +version = "0.160.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c336b5de230f15686a2b6d3e8661d305ef3af9645efc1cf15ef5e7763fc38274" +checksum = "dbccdfc89f27c4121dcd58bde8065fc786e044adb02bf72e3597eff3eb12eab4" dependencies = [ "itoa", "memchr", @@ -5298,9 +5298,9 @@ dependencies = [ [[package]] name = "oxc_estree" -version = "0.158.0" +version = "0.160.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "97635d924b6f8cb6a0ee66d6b9a4970d6a9c2ab361575e84195fe730820e6601" +checksum = "50a08e107a7d8406ed92b6c6b5fe52091486797e9c403c28a8ecc9f656ff070e" [[package]] name = "oxc_index" @@ -5314,7 +5314,7 @@ dependencies = [ [[package]] name = "oxc_parser" -version = "0.158.0" +version = "0.160.0" dependencies = [ "bitflags 2.13.2", "cow-utils", @@ -5336,13 +5336,14 @@ dependencies = [ [[package]] name = "oxc_regular_expression" -version = "0.158.0" +version = "0.160.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6a4569041514ee03f1043609b07e36e383a9653aa38ee70171709eea64081c6c" +checksum = "6418c95b350802b0696d4ce7aa498c5b6be62ee15d1668956d1d350eff095d49" dependencies = [ "bitflags 2.13.2", "oxc_allocator", "oxc_ast_macros", + "oxc_data_structures", "oxc_diagnostics", "oxc_span", "oxc_str", @@ -5353,9 +5354,9 @@ dependencies = [ [[package]] name = "oxc_semantic" -version = "0.158.0" +version = "0.160.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "36c8301783f312c94916a56eab2dcd1e3493f2d8d59bbd7fbc9169425502bb97" +checksum = "7faadf1ec0cc8f88f04a7a79d80cfeeeb7e550e3fef50449680b185aa98b478a" dependencies = [ "itertools 0.15.0", "memchr", @@ -5376,9 +5377,9 @@ dependencies = [ [[package]] name = "oxc_sourcemap" -version = "9.0.0" +version = "10.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1133371a5fadc14b9f66a8fec14be3564a77647c7ab21b1ef0ec973bd82613ce" +checksum = "1ca9998ccb8eabb05099c5827ce983cca9f5dfc008c6c47d7dcc034cee301e91" dependencies = [ "base64-simd", "json-escape-simd", @@ -5389,35 +5390,34 @@ dependencies = [ [[package]] name = "oxc_span" -version = "0.158.0" +version = "0.160.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ac083572f49ac3941fb954304666da42e44e9154abbdd32fd9b594fd269a952c" +checksum = "109cc73d34598dd5f93f5cfcbca2c4ab139b78aec59cece5ff65212ece878f92" dependencies = [ - "compact_str 0.10.0", "oxc_allocator", "oxc_ast_macros", "oxc_estree", - "oxc_str", ] [[package]] name = "oxc_str" -version = "0.158.0" +version = "0.160.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "828e3decc148b651b8be6c8b94569536789069477d7ffbecc4661226bd39dcc7" +checksum = "d4f292499ebd8bfdd7259a34e8156b8d00a4f555718d527f4858eb5db8847ec2" dependencies = [ "compact_str 0.10.0", "hashbrown 0.17.1", "memchr", "oxc_allocator", "oxc_estree", + "oxc_span", ] [[package]] name = "oxc_syntax" -version = "0.158.0" +version = "0.160.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e23801ef775d1cd5743d7abd9d88f826ec4408b85a715bede0526228d688b372" +checksum = "9af4778625a495c0460feb876b5f206436405e5acb5831b7a77c6a5317c547d3" dependencies = [ "bitflags 2.13.2", "cow-utils", @@ -5435,9 +5435,9 @@ dependencies = [ [[package]] name = "oxc_transformer" -version = "0.158.0" +version = "0.160.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "29aec3b41aa32785e92cbdb1e1454f85fabd92377c840ebed12a7342966ba11d" +checksum = "51c86f0003be3a4daa5bc917b383e4cbe2e6f4df054abda9392501215d09e7a1" dependencies = [ "base64 0.23.1", "compact_str 0.10.0", @@ -5461,13 +5461,14 @@ dependencies = [ "rustc-hash 2.1.3", "serde", "serde_json", + "smallvec", ] [[package]] name = "oxc_traverse" -version = "0.158.0" +version = "0.160.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ed84cd5585f66a0ae5209c73be55f6148c921e164dab1ca932be322cce74785d" +checksum = "677f431956f85e2b471252642b38b820957b39ce074203287e3d2ea55a4c00fe" dependencies = [ "itoa", "oxc_allocator", diff --git a/crates/lpm-cli/Cargo.toml b/crates/lpm-cli/Cargo.toml index a9c1824bc..07d10b7fc 100644 --- a/crates/lpm-cli/Cargo.toml +++ b/crates/lpm-cli/Cargo.toml @@ -49,11 +49,11 @@ lpm-dashboard = { workspace = true } lpm-migrate = { workspace = true } cap-fs-ext = { workspace = true } cap-std = "4.0.2" -oxc_allocator = "=0.158.0" -oxc_ast = "=0.158.0" -oxc_ast_visit = "=0.158.0" -oxc_parser = "=0.158.0" -oxc_span = "=0.158.0" +oxc_allocator = "=0.160.0" +oxc_ast = "=0.160.0" +oxc_ast_visit = "=0.160.0" +oxc_parser = "=0.160.0" +oxc_span = "=0.160.0" clap = { workspace = true, features = ["string"] } time = { workspace = true, features = ["local-offset"] } clap_complete = { workspace = true } diff --git a/crates/lpm-runner/Cargo.toml b/crates/lpm-runner/Cargo.toml index 0636361c6..10e9030e3 100644 --- a/crates/lpm-runner/Cargo.toml +++ b/crates/lpm-runner/Cargo.toml @@ -31,13 +31,13 @@ toml = { workspace = true } parking_lot = { workspace = true } fd-lock = { workspace = true } -oxc_allocator = "=0.158.0" -oxc_parser = "=0.158.0" -oxc_semantic = "=0.158.0" -oxc_transformer = "=0.158.0" -oxc_codegen = "=0.158.0" -oxc_span = "=0.158.0" -oxc_ast = "=0.158.0" +oxc_allocator = "=0.160.0" +oxc_parser = "=0.160.0" +oxc_semantic = "=0.160.0" +oxc_transformer = "=0.160.0" +oxc_codegen = "=0.160.0" +oxc_span = "=0.160.0" +oxc_ast = "=0.160.0" [target.'cfg(unix)'.dependencies] libc = "0.2" diff --git a/crates/lpm-security/Cargo.toml b/crates/lpm-security/Cargo.toml index b245bd7f6..50a93c11a 100644 --- a/crates/lpm-security/Cargo.toml +++ b/crates/lpm-security/Cargo.toml @@ -35,13 +35,13 @@ spdx = { version = "0.13.5", default-features = false } time = { version = "0.3", features = ["formatting", "parsing"] } tracing = { workspace = true } url = "2" -oxc_allocator = "=0.158.0" -oxc_ast = "=0.158.0" -oxc_ast_visit = "=0.158.0" -oxc_parser = "=0.158.0" -oxc_span = "=0.158.0" -oxc_str = "=0.158.0" -oxc_semantic = "=0.158.0" +oxc_allocator = "=0.160.0" +oxc_ast = "=0.160.0" +oxc_ast_visit = "=0.160.0" +oxc_parser = "=0.160.0" +oxc_span = "=0.160.0" +oxc_str = "=0.160.0" +oxc_semantic = "=0.160.0" [target.'cfg(unix)'.dependencies] libc = "0.2" diff --git a/crates/lpm-security/src/behavioral/mod.rs b/crates/lpm-security/src/behavioral/mod.rs index 51ed22d8d..9c2faedc3 100644 --- a/crates/lpm-security/src/behavioral/mod.rs +++ b/crates/lpm-security/src/behavioral/mod.rs @@ -3462,10 +3462,10 @@ mod tests { } #[test] - fn parenthesized_lists_nested_in_defaults_are_read_without_parsing_in_linear_time() { - // A parenthesized list that may be arrow parameters is parsed as - // parameters and, when it turns out not to be, parsed again as an - // expression, with every list nested in it. + fn parenthesized_lists_nested_in_defaults_are_parsed_in_linear_time() { + // A parenthesized list that may be arrow parameters must be parsed + // once, not as parameters and then again as an expression with every + // list nested in it. for (filename, open) in [ ("index.js", "([,],a=y,b="), ("index.js", "({a=1}=y,b="), @@ -3481,7 +3481,7 @@ mod tests { let nested_time = started.elapsed(); assert_eq!(flat_result.unparsed_files, 0); assert!(result.source.eval); - assert_eq!(result.unparsed_files, 1, "{filename} {open}"); + assert_eq!(result.unparsed_files, 0, "{filename} {open}"); assert!( nested_time < flat_time * 5 + std::time::Duration::from_millis(200), "{filename} {open}: nested {nested_time:?}, flat {flat_time:?}" @@ -3489,10 +3489,32 @@ mod tests { } } + #[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 + // as one and, when no `=>` follows its parameters, parsed again as a + // type assertion, with every head nested in its defaults. + let source = format!("x={};eval(y);", nested("(a=y,b=", "0", ")", 3_000)); + let flat = format!("{}eval(y);", "x;".repeat(source.len() / 2)); + let started = std::time::Instant::now(); + let flat_result = analyze_on_a_worker_stack("index.ts", flat); + let flat_time = started.elapsed(); + let started = std::time::Instant::now(); + let result = analyze_on_a_worker_stack("index.ts", source); + let nested_time = started.elapsed(); + assert_eq!(flat_result.unparsed_files, 0); + assert!(result.source.eval); + assert_eq!(result.unparsed_files, 1); + assert!( + nested_time < flat_time * 5 + std::time::Duration::from_millis(200), + "nested {nested_time:?}, flat {flat_time:?}" + ); + } + #[test] fn arrow_heads_after_many_lexer_errors_are_analyzed_in_linear_time() { - // Each parenthesized list that may be arrow parameters takes a - // checkpoint that copies every diagnostic the lexer has recorded. + // A checkpoint taken at each parenthesized list that may be arrow + // parameters must not copy every diagnostic the lexer has recorded. for (filename, head) in [ ("index.js", "(a,b)=>0;"), ("index.js", "(a,b);"), @@ -3520,30 +3542,31 @@ mod tests { } #[test] - fn tokens_read_ahead_inside_nested_lists_count_toward_the_parse_budget() { - // Deciding whether a parenthesized list is arrow parameters reads a - // few tokens ahead and rewinds the lexer, and each enclosing list - // parsed again reads them again. - for filename in ["index.js", "index.ts"] { - let source = format!( - "x={}(] \"{}\" 0", - "(a=".repeat(2_000), - "a".repeat(256 * 1024) - ); - let flat = format!("{}eval(y);", "x;".repeat(source.len() / 2)); - let started = std::time::Instant::now(); - let flat_result = analyze_on_a_worker_stack(filename, flat); - let flat_time = started.elapsed(); - let started = std::time::Instant::now(); - let result = analyze_on_a_worker_stack(filename, source); - let nested_time = started.elapsed(); - assert_eq!(flat_result.unparsed_files, 0); - 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:?}" - ); - } + fn long_tokens_read_again_by_nested_speculation_count_toward_the_parse_budget() { + // Each enclosing generic arrow head parsed again reads the string + // again: the budget counts bytes, not tokens. + let source = format!( + "x={};", + nested( + "(a=", + &format!("\"{}\"", "a".repeat(256 * 1024)), + ")", + 2_000 + ) + ); + let flat = format!("{}eval(y);", "x;".repeat(source.len() / 2)); + let started = std::time::Instant::now(); + let flat_result = analyze_on_a_worker_stack("index.ts", flat); + let flat_time = started.elapsed(); + let started = std::time::Instant::now(); + let result = analyze_on_a_worker_stack("index.ts", source); + let nested_time = started.elapsed(); + assert_eq!(flat_result.unparsed_files, 0); + assert_eq!(result.unparsed_files, 1); + assert!( + nested_time < flat_time * 5 + std::time::Duration::from_millis(200), + "nested {nested_time:?}, flat {flat_time:?}" + ); } #[test] diff --git a/crates/lpm-security/src/behavioral/syntax.rs b/crates/lpm-security/src/behavioral/syntax.rs index 209cbdba6..d0e742259 100644 --- a/crates/lpm-security/src/behavioral/syntax.rs +++ b/crates/lpm-security/src/behavioral/syntax.rs @@ -65,13 +65,11 @@ const RESOLUTION_LOOKUPS_PER_BYTE: u64 = 16; const RESOLUTION_LOOKUPS_FLOOR: u64 = 1 << 20; /// Work the parser may spend on speculative parses, per byte of source and -/// for any source: the bytes it reads again after rewinds, and the lexer -/// diagnostics it copies into checkpoints. A parenthesized list that may be -/// arrow parameters, or a `<` that may open type arguments, is parsed one +/// for any source: the bytes it reads again after rewinds. A TypeScript `<` +/// that may open a generic arrow function or type arguments is parsed one /// way and, when that fails, parsed again the other way with all it holds, -/// so nested speculation, or speculation after many diagnostics, can make -/// parsing quadratic. Real code spends under one per byte, and none copies -/// a diagnostic. +/// so nested speculation can make parsing quadratic. Real code spends under +/// one per byte. const PARSE_SPECULATION_PER_BYTE: u64 = 2; const PARSE_SPECULATION_FLOOR: u64 = 64 * 1024; @@ -567,35 +565,54 @@ impl<'s> SourceContext<'s> { mod tests { use super::*; - /// Whether parsing `source` with the floor [`current_stack_floor`] sets - /// stopped at it. - fn parse_reaches_the_floor(source: &str) -> bool { + /// Whether parsing `source`, which is valid, with the floor + /// [`current_stack_floor`] stopped at it. A parse that didn't must have + /// read the source whole. + fn parse_reaches_the_floor(source: &str, source_type: SourceType) -> bool { let allocator = Allocator::default(); - 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() }) - .parse() - .stack_exhausted + .parse(); + assert!( + parsed.stack_exhausted || (!parsed.fatal_error && !parsed.diagnostics.has_errors()), + "{}: {:?}", + &source[..source.len().min(40)], + parsed.diagnostics + ); + parsed.stack_exhausted } #[test] - fn patterns_parsed_to_just_above_the_floor_turn_into_expressions_without_overflowing() { - // A parenthesized list that parses as arrow parameters, with no `=>` - // after it, is turned back into an expression by recursing through its - // patterns without reading a token. At the deepest nesting the parse - // fits above the floor, that recursion must fit too. - let shapes: [(&str, &str, &str, &str, &str); 6] = [ - ("x=(", "[", "a", "]", ");"), - ("x=(", "[", "a", "]", "=0);"), - ("x=(", "{a:", "b", "}", ");"), - ("x=(", "{a:", "b", "}", "=0);"), - ("x=(", "[a=", "0", "]", ");"), - ("x=(", "[", "a", "]", ",b);"), + fn parenthesized_lists_parsed_just_above_the_floor_become_parameters_or_expressions_without_overflowing() + { + // The elements of a parenthesized list are parsed once, and turned + // into arrow parameters at `=>`, or into an expression, by recursing + // through them without reading a token. At the deepest nesting the + // parse fits above the floor, that recursion must fit too. + let (js, ts) = (SourceType::cjs(), SourceType::ts()); + let shapes: [(SourceType, &str, &str, &str, &str, &str); 16] = [ + (js, "x=(", "[", "a", "]", ");"), + (js, "x=(", "[", "a", "]", "=0);"), + (js, "x=(", "{a:", "b", "}", ");"), + (js, "x=(", "{a:", "b", "}", "=0);"), + (js, "x=(", "[a=", "0", "]", ");"), + (js, "x=(", "[", "a", "]", ",b);"), + (js, "x=(", "[", "a", "]", ")=>0;"), + (js, "x=(", "[", "a", "]", "=0)=>0;"), + (js, "x=(", "{a:", "b", "}", ")=>0;"), + (js, "x=(", "[", "a", "]=0", ")=>0;"), + (js, "x=(", "{a:", "b", "}=0", ")=>0;"), + (js, "x=(", "[...", "a", "]", ")=>0;"), + (js, "x=async(", "[", "a", "]", ")=>0;"), + (js, "x=async(...", "[", "a", "]", ")=>0;"), + (ts, "x=(", "[", "a", "]", "):T=>0;"), + (ts, "x=(", "[", "a", "]", ":T)=>0;"), ]; for stack in [2 * 1024 * 1024, DEEP_PARSE_STACK] { - for (prefix, open, middle, close, suffix) in shapes { + for (source_type, prefix, open, middle, close, suffix) in shapes { let deepest = std::thread::Builder::new() .stack_size(stack) .spawn(move || { @@ -606,12 +623,14 @@ mod tests { close.repeat(depth) ) }; + let reaches_the_floor = + |depth| parse_reaches_the_floor(&source(depth), source_type); let (mut fits, mut too_deep) = (1, 8_000_000); - assert!(!parse_reaches_the_floor(&source(fits))); - assert!(parse_reaches_the_floor(&source(too_deep))); + assert!(!reaches_the_floor(fits)); + assert!(reaches_the_floor(too_deep)); while too_deep - fits > 1 { let depth = fits + (too_deep - fits) / 2; - if parse_reaches_the_floor(&source(depth)) { + if reaches_the_floor(depth) { too_deep = depth; } else { fits = depth; diff --git a/crates/lpm-security/src/behavioral/threats.rs b/crates/lpm-security/src/behavioral/threats.rs index 753e1b3a5..33316a834 100644 --- a/crates/lpm-security/src/behavioral/threats.rs +++ b/crates/lpm-security/src/behavioral/threats.rs @@ -659,7 +659,9 @@ fn destructured_methods<'a>(semantic: &Semantic<'a>) -> HashMap Some(key.name.as_str()), - PropertyKey::StringLiteral(key) => key.value.as_str(), + PropertyKey::StaticStringLiteral(key) | PropertyKey::StringLiteral(key) => { + key.value.as_str() + } _ => None, }; if let Some(name) = name @@ -932,9 +934,14 @@ mod tests { #[test] fn bundled_class_helper_preserves_the_environment_upload_flow() { - assert!(leaks( - r#"var modules = {17: (m,e,r) => { r.d(e, {Publisher: () => Publisher}); class Publisher { publish(data) { this.client.rest.repos.createOrUpdateFileContents({content: Buffer.from(data).toString('base64')}); } } }}; function load(id) { const m = {exports:{}}; modules[id].call(m.exports,m,m.exports,load); return m.exports; } const api = load(17); const publisher = new api.Publisher(); publisher.publish(JSON.stringify({environment:process.env}));"# - )); + for factory_key in ["17", "[17]"] { + assert!( + leaks(&format!( + r#"var modules = {{{factory_key}: (m,e,r) => {{ r.d(e, {{Publisher: () => Publisher}}); class Publisher {{ publish(data) {{ this.client.rest.repos.createOrUpdateFileContents({{content: Buffer.from(data).toString('base64')}}); }} }} }}}}; function load(id) {{ const m = {{exports:{{}}}}; modules[id].call(m.exports,m,m.exports,load); return m.exports; }} const api = load(17); const publisher = new api.Publisher(); publisher.publish(JSON.stringify({{environment:process.env}}));"# + )), + "{factory_key}" + ); + } } #[test] @@ -1071,12 +1078,24 @@ mod tests { } fn time_to_analyze(sources: &[String]) -> std::time::Duration { - let started = std::time::Instant::now(); - for source in sources { - let result = super::super::analyze_bytes("index.js", source.as_bytes()); - assert_eq!(result.unparsed_files, 0, "{}", &source[..80]); - } - started.elapsed() + // Parsing recurses once per level, and a debug build parses the + // deepest of these sources in more than the 64 MiB stack a deep + // parse falls back to. + std::thread::scope(|scope| { + std::thread::Builder::new() + .stack_size(256 * 1024 * 1024) + .spawn_scoped(scope, || { + let started = std::time::Instant::now(); + for source in sources { + let result = super::super::analyze_bytes("index.js", source.as_bytes()); + assert_eq!(result.unparsed_files, 0, "{}", &source[..80]); + } + started.elapsed() + }) + .unwrap() + .join() + .unwrap() + }) } #[test] diff --git a/crates/lpm-security/src/behavioral/threats/ancestry.rs b/crates/lpm-security/src/behavioral/threats/ancestry.rs index 32824482e..cfdcbb511 100644 --- a/crates/lpm-security/src/behavioral/threats/ancestry.rs +++ b/crates/lpm-security/src/behavioral/threats/ancestry.rs @@ -68,11 +68,7 @@ impl Ancestry { None => ancestry.block[up], }; ancestry.numeric_property[child] = match parent_kind { - AstKind::ObjectProperty(property) - if matches!(property.key, PropertyKey::NumericLiteral(_)) => - { - Some(parent) - } + AstKind::ObjectProperty(property) if has_numeric_key(property) => Some(parent), _ => ancestry.numeric_property[up], }; ancestry.declarator[child] = match parent_kind { @@ -157,6 +153,15 @@ impl Ancestry { } } +/// Whether a property is keyed by a number, plain (`17:`) or computed +/// (`[17]:`), as a bundle's module table keys its factories. +fn has_numeric_key(property: &ObjectProperty<'_>) -> bool { + matches!( + property.key, + PropertyKey::StaticNumericLiteral(_) | PropertyKey::NumericLiteral(_) + ) +} + /// Whether a node starting at `start`, under `statement`, is in the branch /// an `if` on a boolean literal never takes. fn skipped_branch(statement: &IfStatement<'_>, start: u32) -> bool { @@ -311,7 +316,7 @@ mod tests { walked( semantic, id, - |kind| matches!(kind, AstKind::ObjectProperty(property) if matches!(property.key, PropertyKey::NumericLiteral(_))) + |kind| matches!(kind, AstKind::ObjectProperty(property) if has_numeric_key(property)) ), ); assert_eq!( diff --git a/crates/lpm-security/src/behavioral/threats/archive_tests.rs b/crates/lpm-security/src/behavioral/threats/archive_tests.rs index 438518ed1..15f50c44b 100644 --- a/crates/lpm-security/src/behavioral/threats/archive_tests.rs +++ b/crates/lpm-security/src/behavioral/threats/archive_tests.rs @@ -154,10 +154,12 @@ fn aliased_filesystem_methods_keep_their_imported_identity() { "import {rmSync as remove} from 'node:fs'; import {homedir as home} from 'node:os'; remove(home(),{recursive:true});", "destructiveFilesystem" )); - assert!(detected( - "const {rmSync:remove}=require('fs'); const os=require('os'); remove(os.homedir(),{recursive:true});", - "destructiveFilesystem" - )); + for key in ["rmSync", "'rmSync'", "['rmSync']"] { + let source = format!( + "const {{{key}:remove}}=require('fs'); const os=require('os'); remove(os.homedir(),{{recursive:true}});" + ); + assert!(detected(&source, "destructiveFilesystem"), "{source}"); + } } #[test] diff --git a/crates/lpm-security/src/behavioral/threats/bundles.rs b/crates/lpm-security/src/behavioral/threats/bundles.rs index 98d305fa9..aca9ff016 100644 --- a/crates/lpm-security/src/behavioral/threats/bundles.rs +++ b/crates/lpm-security/src/behavioral/threats/bundles.rs @@ -92,7 +92,8 @@ impl Bundles { continue; }; let AstKind::ObjectProperty(ObjectProperty { - key: PropertyKey::NumericLiteral(key), + key: + PropertyKey::StaticNumericLiteral(key) | PropertyKey::NumericLiteral(key), .. }) = semantic.nodes().kind(factory) else { diff --git a/vendor/oxc_parser/Cargo.toml b/vendor/oxc_parser/Cargo.toml index 6d4b5ffff..f6e0733b5 100644 --- a/vendor/oxc_parser/Cargo.toml +++ b/vendor/oxc_parser/Cargo.toml @@ -11,9 +11,9 @@ [package] edition = "2024" -rust-version = "1.97.0" +rust-version = "1.98.0" name = "oxc_parser" -version = "0.158.0" +version = "0.160.0" authors = [ "Boshen ", "Oxc contributors", @@ -89,37 +89,39 @@ version = "0.5.0" version = "0.2.19" [dependencies.oxc_allocator] -version = "0.158.0" +version = "0.160.0" [dependencies.oxc_ast] -version = "0.158.0" +version = "0.160.0" [dependencies.oxc_data_structures] -version = "0.158.0" +version = "0.160.0" features = [ "assert_unchecked", "branch_hints", + "brands", + "buffered_vec", "fieldless_enum", ] [dependencies.oxc_diagnostics] -version = "0.158.0" +version = "0.160.0" [dependencies.oxc_ecmascript] -version = "0.158.0" +version = "0.160.0" [dependencies.oxc_regular_expression] -version = "0.158.0" +version = "0.160.0" optional = true [dependencies.oxc_span] -version = "0.158.0" +version = "0.160.0" [dependencies.oxc_str] -version = "0.158.0" +version = "0.160.0" [dependencies.oxc_syntax] -version = "0.158.0" +version = "0.160.0" [dependencies.rustc-hash] version = "2" @@ -128,16 +130,20 @@ version = "2" version = "0.3.6" [dev-dependencies.oxc_ast] -version = "0.158.0" +version = "0.160.0" features = ["serialize"] [dev-dependencies.oxc_ast_visit] -version = "0.158.0" +version = "0.160.0" features = ["serialize"] [dev-dependencies.pico-args] version = "0.5.0" +[lints.cargo] +unused_dependencies = "allow" +unused_workspace_dependencies = "allow" + [lints.clippy] allow_attributes = "warn" branches_sharing_code = "allow" @@ -148,6 +154,7 @@ dbg_macro = "warn" doc_markdown = "allow" empty_drop = "warn" empty_enum_variants_with_brackets = "warn" +empty_enums = "allow" empty_structs_with_brackets = "warn" error_impl_error = "warn" exit = "warn" diff --git a/vendor/oxc_parser/Cargo.toml.orig b/vendor/oxc_parser/Cargo.toml.orig index ad30a887e..8810067d5 100644 --- a/vendor/oxc_parser/Cargo.toml.orig +++ b/vendor/oxc_parser/Cargo.toml.orig @@ -1,6 +1,6 @@ [package] name = "oxc_parser" -version = "0.158.0" +version = "0.160.0" authors.workspace = true categories.workspace = true edition.workspace = true @@ -24,6 +24,8 @@ oxc_ast = { workspace = true } oxc_data_structures = { workspace = true, features = [ "assert_unchecked", "branch_hints", + "brands", + "buffered_vec", "fieldless_enum", ] } oxc_diagnostics = { workspace = true } diff --git a/vendor/oxc_parser/LPM-PATCH.md b/vendor/oxc_parser/LPM-PATCH.md index 93329aa50..d89fc6f83 100644 --- a/vendor/oxc_parser/LPM-PATCH.md +++ b/vendor/oxc_parser/LPM-PATCH.md @@ -1,7 +1,7 @@ -# oxc_parser 0.158.0, patched +# oxc_parser 0.160.0, patched -This is `oxc_parser` 0.158.0 from crates.io (oxc commit -`74e5e665ab8227c3d43abf3ce0e4383830e80c12`, `crates/oxc_parser`), MIT +This is `oxc_parser` 0.160.0 from crates.io (oxc commit +`87e38f3270b00341695e02e8aaf681e9e985e4a3`, `crates/oxc_parser`), MIT licensed (see `LICENSE`), with two changes: the parser can stop at a stack floor instead of overflowing its thread's stack, and at a budget for the work it spends on speculative parses. The workspace uses it through @@ -16,13 +16,12 @@ code of every package it analyzes, including packages written to attack it, so a crafted package could abort `lpm audit`, an install's analysis, or a registry's release scan. -The parser also speculates. A parenthesized list that may be arrow -parameters, or a `<` that may open type arguments, is parsed one way and, -when that fails, rewound and parsed again the other way, with everything -nested in it. The checkpoint for a parenthesized list also copies every -diagnostic the lexer has recorded. Nested speculation, or speculation after -many lexer diagnostics, can make a parse take time quadratic in the -source's length. +The parser also speculates. In TypeScript, a `<` that may open a generic +arrow function or type arguments is parsed one way and, when that fails, +rewound and parsed again the other way, with everything nested in it. +Nested speculation can make a parse take time quadratic in the source's +length: `x=(a=(a=…0)));` reads each level again for every level +around it. ## What changed @@ -31,29 +30,32 @@ source's length. - `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 reading each token, the parser compares the stack pointer with the - floor. 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. -- Two recursions run over nodes already parsed and read no token, so they - check the floor once per level themselves: - - the cover grammar, which turns an expression into a destructuring - assignment target (`AssignmentTarget::cover` in `js/grammar.rs`), stops - with the same fatal error; - - turning parenthesized arrow parameters back into an expression when no - `=>` follows (`cover_binding_as_expression` in `js/arrow.rs`, new in - 0.158) gives up instead, and the parser reads the source again as an - expression, which checks the floor per token. - Either can go deeper than the parse that built its nodes, because its - frames per level can be larger. In 0.158, parsing `x=([[…a…]]);` to just - above the floor and converting it overflowed a 2 MiB stack. +- 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. +- 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: + - the cover grammar that turns an expression into a destructuring + assignment target (`AssignmentTarget::cover` in `js/grammar.rs`); + - the conversions that turn the elements of a parenthesized list into + arrow parameters once `=>` follows it + (`cover_expression_to_binding_pattern` and + `cover_assignment_target_to_binding_pattern`), which stop with the + same fatal error; + - the checks that decide whether those elements can be parameters + (`check_cover_binding` and `check_cover_binding_target`). They borrow + 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. - Once the floor is reached, every later token read records the fatal error - again. A speculative parse, such as an arrow function's parameters, rewinds - the fatal error away, and the parser then reads the other interpretation. - If only reads below the floor stopped, each nested speculation would read - back down to the floor: a source of arrow functions nested in parameter - defaults took seconds and gigabytes of arena memory to give up on. + again. A speculative parse rewinds the fatal error away, and the parser + then reads the other interpretation. If only reads below the floor + stopped, each nested speculation would read back down to the floor. - `ParserReturn::stack_exhausted` reports it. It stays set even when a 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. @@ -63,24 +65,23 @@ source's length. every rewind, the parser's and its own lookaheads', and the bytes it skips without reading when a fatal error moves it to the end of the source. Their difference is what it has read beyond its position, so in - all it has read at most its position plus that. Each checkpoint that can - restore the lexer's diagnostics also spends 16 per diagnostic it copies. - The counts change only in rewinds, skips and those checkpoints, so a - parse pays nothing for them per token. A parse already stopped at the - floor is unwinding and isn't checked against the budget, so it can still - be retried on a larger stack. Going past the budget stops the parse the - same way the floor does, sticky across later rewinds, and - `ParserReturn::speculation_budget_exhausted` reports it. The default, - `0`, never stops. + all it has read at most its position plus that. The counts change only in + rewinds and skips, and the parser compares them with the budget at each + of its rewinds, so a parse pays nothing for them per token. A parse + already stopped at the floor is unwinding and isn't checked against the + budget, so it can still be retried on a larger stack. Going past the + budget stops the parse the same way the floor does, sticky across later + rewinds, and `ParserReturn::speculation_budget_exhausted` reports it. The + default, `0`, never stops. `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 reads one that runs out of that too without parsing it. It gives each 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,000 JavaScript and TypeScript files of a local package store, the most -any file read beyond its position was 0.93 bytes per byte, no file copied a -diagnostic, and no file used more than 30% of its budget. +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. ## Upgrading oxc @@ -91,19 +92,24 @@ diagnostic, and no file used more than 30% of its budget. 3. Regenerate the patch from a pristine copy of the release: `diff -ruN . -x LICENSE -x LPM-PATCH.md -x lpm-stack-floor.patch -x .cargo_vcs_info.json -x Cargo.lock`, with `a/` and `b/` file headers. -4. Look for new recursion that reads no token, such as conversions between - AST shapes after a parse, and give it a floor check like the ones above. +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. `lpm-security`'s - `patterns_parsed_to_just_above_the_floor_turn_into_expressions_without_overflowing` + `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 - `PARSE_SPECULATION_PER_BYTE` in `lpm-security`'s `behavioral/syntax.rs`. + `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: `lpm-cli`, `lpm-runner` and `lpm-security` pin them exactly, the crates share AST types, and the patch replaces `oxc_parser` for all of them. - Then run `cargo test -p lpm-security`, whose deep-nesting tests cover the - parser, the AST visitors and semantic analysis. + Dependabot proposes them together, in its `oxc` group. Then run + `cargo test -p lpm-security`, whose deep-nesting tests cover the parser, + the AST visitors and semantic analysis, and whose rule tests catch AST + changes that still compile, such as a new variant for keys the rules + match. If oxc gains a depth or stack limit of its own, switch to it and drop this directory and the `[patch.crates-io]` entry. diff --git a/vendor/oxc_parser/README.md b/vendor/oxc_parser/README.md index 319d4091b..ddecace38 100644 --- a/vendor/oxc_parser/README.md +++ b/vendor/oxc_parser/README.md @@ -4,14 +4,14 @@ High-performance JavaScript and TypeScript parser with comprehensive language su ## Overview -This crate provides a fast, spec-compliant parser for JavaScript and TypeScript that produces a complete Abstract Syntax Tree (AST). It supports all modern language features including JSX, TSX, and the latest ECMAScript proposals. +This crate provides a fast, spec-compliant parser for JavaScript and TypeScript that produces a complete Abstract Syntax Tree (AST). It supports JavaScript, TypeScript, JSX, TSX, and selected ECMAScript proposals. ## Key Features - **Complete language support**: JavaScript, TypeScript, JSX, and TSX -- **Latest ECMAScript**: All stable ECMAScript features plus stage 3+ proposals +- **Latest ECMAScript**: Stable ECMAScript syntax plus selected Stage 3 proposals - **High performance**: Significantly faster than traditional parsers -- **Error recovery**: Continues parsing after errors to provide complete AST +- **Error recovery**: Recovers from some syntax errors; fatal errors return an empty program - **Comprehensive AST**: Detailed node information with accurate source positions ## Architecture @@ -21,7 +21,7 @@ This crate provides a fast, spec-compliant parser for JavaScript and TypeScript - **Recursive descent**: Traditional recursive descent parser architecture - **Error recovery**: Sophisticated error recovery for IDE-friendly parsing - **Memory efficient**: Uses arena allocation for optimal performance -- **Streaming**: Processes source text in a single pass +- **Source input**: Parses a complete UTF-8 source string, with lookahead where needed ### Language Support @@ -35,7 +35,7 @@ This crate provides a fast, spec-compliant parser for JavaScript and TypeScript The parser produces an AST that closely follows ECMAScript specifications: - **Accurate positions**: Every node has precise source location information -- **Complete information**: Preserves all syntactic details including trivia +- **Comments and source text**: Records comments and source spans; whitespace is available through the original source text - **Type-safe**: Leverages Rust's type system for correctness - **Visitor-friendly**: Designed for easy traversal and transformation diff --git a/vendor/oxc_parser/examples/parser.rs b/vendor/oxc_parser/examples/parser.rs index 54220994b..412c025f2 100644 --- a/vendor/oxc_parser/examples/parser.rs +++ b/vendor/oxc_parser/examples/parser.rs @@ -47,7 +47,11 @@ fn main() -> Result<(), String> { // Parse the source code let allocator = Allocator::default(); let ret = Parser::new(&allocator, &source_text, source_type) - .with_options(ParseOptions { parse_regular_expression: true, ..ParseOptions::default() }) + .with_options(ParseOptions { + parse_regular_expression: true, + enable_ident_hashes: false, + ..ParseOptions::default() + }) .parse(); let mut program = ret.program; @@ -82,7 +86,7 @@ fn main() -> Result<(), String> { println!("Parsed Successfully."); } else { for error in ret.diagnostics { - println!("{}", error.render_with_source_code(source_text.clone())); + println!("{}", error.render_with_source_code(source_text.as_str())); } println!("Parsed with Errors."); } diff --git a/vendor/oxc_parser/examples/parser_tsx.rs b/vendor/oxc_parser/examples/parser_tsx.rs index 672101f6a..f47b8871c 100644 --- a/vendor/oxc_parser/examples/parser_tsx.rs +++ b/vendor/oxc_parser/examples/parser_tsx.rs @@ -10,7 +10,7 @@ //! ``` use oxc_allocator::Allocator; -use oxc_parser::{Parser, ParserReturn}; +use oxc_parser::{ParseOptions, Parser, ParserReturn}; use oxc_span::SourceType; /// Parse a TypeScript JSX file and validate the results @@ -43,7 +43,9 @@ export const Counter: React.FC = () => { diagnostics, // Syntax errors fatal_error, // Parser encountered an error it couldn't recover from .. - } = Parser::new(&allocator, source_text, source_type).parse(); + } = Parser::new(&allocator, source_text, source_type) + .with_options(ParseOptions { enable_ident_hashes: false, ..ParseOptions::default() }) + .parse(); if fatal_error { return Err("Parser encountered a fatal error".to_string()); diff --git a/vendor/oxc_parser/examples/regular_expression.rs b/vendor/oxc_parser/examples/regular_expression.rs index d124c5b19..ba61d26a7 100644 --- a/vendor/oxc_parser/examples/regular_expression.rs +++ b/vendor/oxc_parser/examples/regular_expression.rs @@ -1,5 +1,5 @@ #![expect(clippy::print_stdout)] -use std::{env, fs, path::Path, sync::Arc}; +use std::{env, fs, path::Path}; use oxc_allocator::Allocator; use oxc_ast::ast::*; @@ -15,18 +15,22 @@ fn main() { let name = env::args().nth(1).unwrap_or_else(|| "test.js".to_string()); let path = Path::new(&name); - let source_text: Arc = Arc::from(fs::read_to_string(path).unwrap()); + let source_text = fs::read_to_string(path).unwrap(); let source_type = SourceType::from_path(path).unwrap(); let allocator = Allocator::default(); - let options = ParseOptions { parse_regular_expression: true, ..ParseOptions::default() }; + let options = ParseOptions { + parse_regular_expression: true, + enable_ident_hashes: false, + ..ParseOptions::default() + }; let parser_ret = - Parser::new(&allocator, source_text.as_ref(), source_type).with_options(options).parse(); + Parser::new(&allocator, &source_text, source_type).with_options(options).parse(); if !parser_ret.diagnostics.is_empty() { println!("Parsing failed:"); for error in parser_ret.diagnostics { - println!("{}", error.render_with_source_code(Arc::clone(&source_text))); + println!("{}", error.render_with_source_code(source_text.as_str())); } return; } @@ -34,17 +38,16 @@ fn main() { // Parse regular expressions // - RegExpLiteral // - new RegExp() with string or template literal if static - RegularExpressionVisitor { source_text: Arc::clone(&source_text) } - .visit_program(&parser_ret.program); + RegularExpressionVisitor { source_text: &source_text }.visit_program(&parser_ret.program); } -struct RegularExpressionVisitor { - source_text: Arc, +struct RegularExpressionVisitor<'a> { + source_text: &'a str, } -impl<'a> VisitJs<'a> for RegularExpressionVisitor { +impl<'a> VisitJs<'a> for RegularExpressionVisitor<'a> { fn visit_reg_exp_literal(&mut self, re: &RegExpLiteral<'a>) { - println!("🍀 {}", re.span.source_text(self.source_text.as_ref())); + println!("🍀 {}", re.span.source_text(self.source_text)); println!("{re:#?}"); println!(); @@ -52,7 +55,7 @@ impl<'a> VisitJs<'a> for RegularExpressionVisitor { fn visit_new_expression(&mut self, new_expr: &NewExpression<'a>) { if new_expr.callee.get_identifier_reference().is_some_and(|ident| ident.name == "RegExp") { - println!("🍀 {}", new_expr.span.source_text(&self.source_text)); + println!("🍀 {}", new_expr.span.source_text(self.source_text)); let pattern_span = match new_expr.arguments.first() { Some(Argument::StringLiteral(sl)) => sl.span, @@ -67,8 +70,8 @@ impl<'a> VisitJs<'a> for RegularExpressionVisitor { let allocator = Allocator::default(); let parsed = RegExpParser::new( &allocator, - pattern_span.source_text(&self.source_text), - flags_span.map(|span| span.source_text(&self.source_text)), + pattern_span.source_text(self.source_text), + flags_span.map(|span| span.source_text(self.source_text)), RegExpParserOptions { pattern_span_offset: pattern_span.start, flags_span_offset: flags_span.map_or(0, |span| span.start), @@ -77,7 +80,7 @@ impl<'a> VisitJs<'a> for RegularExpressionVisitor { .parse(); if let Err(error) = parsed { - println!("{}", error.render_with_source_code(Arc::clone(&self.source_text))); + println!("{}", error.render_with_source_code(self.source_text)); return; } println!("{parsed:#?}"); diff --git a/vendor/oxc_parser/examples/visitor.rs b/vendor/oxc_parser/examples/visitor.rs index 1fe231eef..535f5fffb 100644 --- a/vendor/oxc_parser/examples/visitor.rs +++ b/vendor/oxc_parser/examples/visitor.rs @@ -16,7 +16,7 @@ use std::{env, path::Path}; use oxc_allocator::Allocator; use oxc_ast::ast::{Class, Function, TSImportType}; use oxc_ast_visit::{Visit, walk}; -use oxc_parser::Parser; +use oxc_parser::{ParseOptions, Parser}; use oxc_span::SourceType; use oxc_syntax::scope::ScopeFlags; @@ -32,11 +32,13 @@ fn main() -> std::io::Result<()> { let source_text = std::fs::read_to_string(path)?; let allocator = Allocator::default(); let source_type = SourceType::from_path(path).unwrap(); - let ret = Parser::new(&allocator, &source_text, source_type).parse(); + let ret = Parser::new(&allocator, &source_text, source_type) + .with_options(ParseOptions { enable_ident_hashes: false, ..ParseOptions::default() }) + .parse(); // Report any parsing errors for error in ret.diagnostics { - println!("{}", error.render_with_source_code(source_text.clone())); + println!("{}", error.render_with_source_code(source_text.as_str())); } let program = ret.program; diff --git a/vendor/oxc_parser/lpm-stack-floor.patch b/vendor/oxc_parser/lpm-stack-floor.patch index 86a3ee7f4..440b25faa 100644 --- a/vendor/oxc_parser/lpm-stack-floor.patch +++ b/vendor/oxc_parser/lpm-stack-floor.patch @@ -1,25 +1,22 @@ --- a/src/cursor.rs +++ b/src/cursor.rs -@@ -1,6 +1,6 @@ - //! Code related to navigating `Token`s from the lexer +@@ -1,12 +1,14 @@ + //! Token cursor: reading, consuming, expecting and re-lexing the current token, + //! and checkpoints for backtracking. --use oxc_allocator::{ArenaBox, ArenaVec}; -+use oxc_allocator::{ArenaBox, ArenaVec, Dummy, GetAllocator}; - use oxc_ast::ast::{BindingRestElement, RegExpFlags}; - use oxc_span::{GetSpan, Span}; ++use oxc_allocator::{Dummy, GetAllocator}; + use oxc_ast::ast::RegExpFlags; + use oxc_span::Span; use oxc_str::JSStr; -@@ -12,6 +12,10 @@ + + use crate::{ +- ParserConfig as Config, ParserImpl, diagnostics, ++ ParserConfig as Config, ParserImpl, ++ diagnostics::{self, ParserDiagnostic}, lexer::{Kind, LexerCheckpoint, Token, cold_branch}, }; -+/// Speculation budget spent on each lexer diagnostic copied into a -+/// checkpoint, in bytes read. -+const DIAGNOSTIC_COPY_COST: u64 = 16; -+ - pub struct ParserCheckpoint<'a> { - lexer: LexerCheckpoint<'a>, - cur_token: Token, -@@ -108,13 +112,69 @@ +@@ -108,13 +110,85 @@ if self.token.escaped() && kind.is_any_keyword() { self.report_escaped_keyword(self.token.span()); } @@ -35,7 +32,10 @@ + /// so every caller unwinds without reading more tokens. + #[inline] + fn check_parse_limits(&mut self) { -+ if self.stack_exhausted || self.speculation_budget_exhausted || self.below_stack_floor() { ++ if self.stack_exhausted.get() ++ || self.speculation_budget_exhausted ++ || self.below_stack_floor() ++ { + self.stop_at_parse_limit(); + } + } @@ -59,7 +59,7 @@ + #[cold] + #[inline(never)] + fn stop_at_parse_limit(&mut self) { -+ if self.speculation_budget_exhausted && !self.stack_exhausted { ++ if self.speculation_budget_exhausted && !self.stack_exhausted.get() { + self.set_fatal_error(diagnostics::speculation_budget_exhausted(self.token.span())); + } else { + self.stop_at_stack_floor(); @@ -69,7 +69,7 @@ + #[cold] + #[inline(never)] + fn stop_at_stack_floor(&mut self) { -+ self.stack_exhausted = true; ++ self.stack_exhausted.set(true); + self.set_fatal_error(diagnostics::stack_exhausted(self.token.span())); + } + @@ -81,6 +81,19 @@ + self.stop_at_stack_floor(); + Dummy::dummy(self.allocator()) + } ++ ++ /// [`Self::stop_at_stack_floor`] for a check that reads no token and ++ /// can't change the parser: the error the check fails with. The parse ++ /// stops at the next token it reads, and reports ++ /// [`ParserReturn::stack_exhausted`] even if it reads none. ++ /// ++ /// [`ParserReturn::stack_exhausted`]: crate::ParserReturn::stack_exhausted ++ #[cold] ++ #[inline(never)] ++ pub(crate) fn stack_floor_error(&self, span: Span) -> ParserDiagnostic<'a> { ++ self.stack_exhausted.set(true); ++ diagnostics::stack_exhausted(span) ++ } + /// Move to the next `JSXChild` /// Checks if the current token is escaped if it is a keyword @@ -89,7 +102,17 @@ self.prev_token_end = self.token.end(); self.token = self.lexer.next_jsx_child(); } -@@ -233,6 +293,7 @@ +@@ -170,6 +244,9 @@ + if self.token.escaped() && self.token.kind().is_any_keyword() { + self.report_escaped_keyword(self.token.span()); + } ++ // The lexer read `next` before this check, so a parse that stops ++ // here still moves to it, and unwinds at the token after. ++ self.check_parse_limits(); + self.prev_token_end = self.token.end(); + self.token = next; + } +@@ -263,6 +340,7 @@ /// Move to the next token, lexing it as a JSX attribute value. pub(crate) fn advance_for_jsx_attribute_value(&mut self) { @@ -97,48 +120,33 @@ self.prev_token_end = self.token.end(); self.token = self.lexer.next_jsx_attribute_value(); } -@@ -323,6 +384,9 @@ - } - - pub(crate) fn checkpoint_with_error_recovery(&mut self) -> ParserCheckpoint<'a> { -+ // The lexer's checkpoint copies every diagnostic it has recorded. -+ self.diagnostics_copied += self.lexer.errors.len() as u64; -+ self.check_speculation_budget(); - ParserCheckpoint { - lexer: self.lexer.checkpoint_with_error_recovery(), - cur_token: self.token, -@@ -337,10 +401,27 @@ - checkpoint; - +@@ -373,10 +451,22 @@ + self.lexer.errors.push(fatal_error.error); + } self.lexer.rewind(lexer); + self.check_speculation_budget(); self.token = cur_token; self.prev_token_end = prev_token_end; self.errors.truncate(errors_pos); - self.fatal_error = fatal_error; + self.state.cover_parenthesized.truncate(cover_parenthesized_len); + } + + /// Sets the budget's stop once the work spent on speculation passes it: + /// the bytes the lexer has read beyond its position, which a rewind made -+ /// it read or will make it read again, and the diagnostics copied into -+ /// checkpoints, each an allocation of about a hundred bytes, at -+ /// [`DIAGNOSTIC_COPY_COST`] each. A parse already stopped at the stack -+ /// floor is unwinding, and reads nothing again. ++ /// it read or will make it read again. A parse already stopped at the ++ /// stack floor is unwinding, and reads nothing again. + #[inline] + fn check_speculation_budget(&mut self) { -+ let work = self.lexer.bytes_read_ahead().saturating_add( -+ self.diagnostics_copied.saturating_mul(DIAGNOSTIC_COPY_COST), -+ ); -+ if !self.stack_exhausted && work > self.speculation_limit { ++ if !self.stack_exhausted.get() && self.lexer.bytes_read_ahead() > self.speculation_limit { + self.speculation_budget_exhausted = true; + } } - pub(crate) fn lookahead(&mut self, predicate: impl Fn(&mut ParserImpl<'a, C>) -> U) -> U { + /// Rewind to `checkpoint`, keeping the comments and irregular whitespace lexed after it. --- a/src/diagnostics.rs +++ b/src/diagnostics.rs -@@ -91,6 +91,16 @@ - OxcDiagnostic::error("Source length exceeds 4 GiB limit") +@@ -94,6 +94,16 @@ + OxcDiagnostic::error(MAX_LEN_ERROR) }; + stack_exhausted(span: Span) => { @@ -154,24 +162,9 @@ file_appears_to_be_binary() => { ts_error("1490", "File appears to be binary.") }; ---- a/src/js/arrow.rs -+++ b/src/js/arrow.rs -@@ -537,6 +537,12 @@ - &mut self, - pattern: BindingPattern<'a>, - ) -> Option> { -+ // This reads no token, so it checks the stack floor itself. Below it, -+ // the caller parses the source again as an expression, which checks -+ // the floor per token. -+ if self.below_stack_floor() { -+ return None; -+ } - Some(match pattern { - BindingPattern::BindingIdentifier(ident) => { - if ident.name == "await" && !self.ctx.has_await() { --- a/src/js/grammar.rs +++ b/src/js/grammar.rs -@@ -12,6 +12,11 @@ +@@ -14,6 +14,11 @@ impl<'a, C: Config> CoverGrammar<'a, Expression<'a>, C> for AssignmentTarget<'a> { fn cover(expr: Expression<'a>, p: &mut ParserImpl<'a, C>) -> Self { @@ -183,9 +176,52 @@ match expr { Expression::ArrayExpression(array_expr) => { let pat = ArrayAssignmentTarget::cover(array_expr.unbox(), p); +@@ -303,6 +308,12 @@ + + /// Check that `expression` covers a `BindingIdentifier` or a `BindingPattern`. + pub(super) fn check_cover_binding(&self, expression: &Expression<'a>) -> CoverCheck<'a> { ++ // The checks and conversions of binding patterns read no token, so they ++ // check the stack floor themselves. Nested elements pass through here, ++ // or through `check_cover_binding_target`, once per level. ++ if self.below_stack_floor() { ++ return Err(self.stack_floor_error(expression.span())); ++ } + match expression { + Expression::Identifier(ident) if !self.is_cover_parenthesized(ident.span.start) => { + Ok(()) +@@ -376,6 +387,9 @@ + /// Check that an assignment target, which an expression was already refined to, covers + /// a `BindingIdentifier` or a `BindingPattern`. + fn check_cover_binding_target(&self, target: &AssignmentTarget<'a>) -> CoverCheck<'a> { ++ if self.below_stack_floor() { ++ return Err(self.stack_floor_error(target.span())); ++ } + match target { + AssignmentTarget::AssignmentTargetIdentifier(ident) + if !self.is_cover_parenthesized(ident.span.start) => +@@ -452,6 +466,9 @@ + &mut self, + expression: Expression<'a>, + ) -> BindingPattern<'a> { ++ if self.below_stack_floor() { ++ return self.stopped_at_stack_floor(); ++ } + match expression { + Expression::Identifier(ident) => { + BindingPattern::new_binding_identifier(ident.span, ident.name, self) +@@ -555,6 +572,9 @@ + &mut self, + target: AssignmentTarget<'a>, + ) -> BindingPattern<'a> { ++ if self.below_stack_floor() { ++ return self.stopped_at_stack_floor(); ++ } + match target { + AssignmentTarget::AssignmentTargetIdentifier(ident) => { + BindingPattern::new_binding_identifier(ident.span, ident.name, self) --- a/src/lexer/mod.rs +++ b/src/lexer/mod.rs -@@ -120,6 +120,13 @@ +@@ -130,6 +130,13 @@ /// Config pub(crate) config: C, @@ -199,8 +235,8 @@ } impl<'a, C: Config> Lexer<'a, C> { -@@ -168,6 +175,8 @@ - multi_line_comment_end_finder: None, +@@ -176,6 +183,8 @@ + escaped_templates: FxHashMap::default(), tokens, config, + bytes_rewound: 0, @@ -208,14 +244,14 @@ } } -@@ -248,10 +257,19 @@ - } +@@ -239,10 +248,19 @@ + self.errors.truncate(checkpoint.errors_len); self.tokens.truncate(checkpoint.tokens_len); + let from = self.offset(); self.source.set_position(checkpoint.source_position); + self.bytes_rewound += u64::from(from.saturating_sub(self.offset())); - self.trivia_builder.annotation_comments = checkpoint.annotation_comments; + self.trivia_builder.rewind(checkpoint.trivia); } + /// Bytes the lexer has read beyond its current position: those it read @@ -225,10 +261,10 @@ + self.bytes_rewound.saturating_sub(self.bytes_skipped) + } + - pub fn peek_token(&mut self) -> Token { - let checkpoint = self.checkpoint(); - let token = self.next_token(); -@@ -405,7 +423,9 @@ + /// 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 +588,9 @@ /// Advance source cursor to end of file. #[inline] pub fn advance_to_end(&mut self) { @@ -240,7 +276,16 @@ // ---------- Private Methods ---------- // --- a/src/lib.rs +++ b/src/lib.rs -@@ -213,6 +213,15 @@ +@@ -64,7 +64,7 @@ + //! + //! See [full linter example](https://github.com/Boshen/oxc/blob/ab2ef4f89ba3ca50c68abb2ca43e36b7793f3673/crates/oxc_linter/examples/linter.rs#L38-L39) + +-use std::any::Any; ++use std::{any::Any, cell::Cell}; + + mod ast_builder; + pub mod config; +@@ -221,6 +221,15 @@ /// Whether the file is [flow](https://flow.org). pub is_flow_language: bool, @@ -255,8 +300,8 @@ + pub speculation_budget_exhausted: bool, } - /// Parse options -@@ -267,6 +276,34 @@ + // `ParserReturn` is the output of `ParserImpl::parse`. +@@ -291,6 +300,33 @@ /// /// Default: `true` pub enable_ident_hashes: bool, @@ -276,14 +321,13 @@ + + /// How much work the parser may spend on speculative parses. + /// -+ /// A speculative parse, such as of a parenthesized list that may be -+ /// arrow parameters, takes a checkpoint and rewinds to it when it fails, -+ /// and a lookahead reads a few tokens and rewinds the lexer. Each byte the -+ /// lexer has read beyond its position after such rewinds costs one, and -+ /// each lexer diagnostic copied into a checkpoint that can restore them -+ /// costs 16. When the total passes this budget, the parser stops with a -+ /// fatal error and [`ParserReturn::speculation_budget_exhausted`] set. A -+ /// budget proportional to the source's length keeps the work spent on ++ /// A speculative parse, such as of type arguments that may turn out to be ++ /// comparisons, takes a checkpoint and rewinds to it when it fails, and a ++ /// lookahead reads a few tokens and rewinds the lexer. Each byte the lexer ++ /// has read beyond its position after such rewinds costs one. When the ++ /// total passes this budget, the parser stops with a fatal error and ++ /// [`ParserReturn::speculation_budget_exhausted`] set. A budget ++ /// proportional to the source's length keeps the work spent on + /// speculation proportional to it too. + /// + /// Default: `0`, no limit @@ -291,7 +335,7 @@ } impl Default for ParseOptions { -@@ -278,6 +315,8 @@ +@@ -302,6 +338,8 @@ preserve_parens: true, allow_v8_intrinsics: false, enable_ident_hashes: true, @@ -300,45 +344,42 @@ } } } -@@ -670,6 +709,18 @@ +@@ -563,6 +601,16 @@ /// Precomputed typescript detection is_ts: bool, + -+ /// Parsing reached [`ParseOptions::stack_floor`]. -+ stack_exhausted: bool, ++ /// Parsing reached [`ParseOptions::stack_floor`]. A `Cell`, so that a ++ /// check that reads no token and borrows the parser can record it. ++ stack_exhausted: Cell, + + /// [`ParseOptions::speculation_budget`], with `u64::MAX` for no limit. + speculation_limit: u64, + -+ /// Lexer diagnostics copied into checkpoints so far. -+ diagnostics_copied: u64, -+ + /// Parsing reached [`ParseOptions::speculation_budget`]. + speculation_budget_exhausted: bool, } impl<'a, C: ParserConfig> ParserImpl<'a, C> { -@@ -702,6 +753,14 @@ +@@ -602,6 +650,13 @@ ast: ParserAstBuilder::new(allocator), module_record_builder: ModuleRecordBuilder::new(allocator, source_type), is_ts: source_type.is_typescript(), -+ stack_exhausted: false, ++ stack_exhausted: Cell::new(false), + speculation_limit: if options.speculation_budget == 0 { + u64::MAX + } else { + options.speculation_budget + }, -+ diagnostics_copied: 0, + speculation_budget_exhausted: false, } } -@@ -795,6 +854,8 @@ +@@ -719,6 +774,8 @@ tokens, fatal_error: has_fatal_error, is_flow_language, -+ stack_exhausted: self.stack_exhausted, ++ stack_exhausted: self.stack_exhausted.get(), + speculation_budget_exhausted: self.speculation_budget_exhausted, } } diff --git a/vendor/oxc_parser/src/context.rs b/vendor/oxc_parser/src/context.rs index 05d3023ba..b761b09d2 100644 --- a/vendor/oxc_parser/src/context.rs +++ b/vendor/oxc_parser/src/context.rs @@ -1,7 +1,9 @@ -//! ECMAScript Grammar Contexts: `[In`] `[Yield]` `[Await]` +//! ECMAScript Grammar Contexts: `[In]` `[Yield]` `[Await]` use bitflags::bitflags; +use crate::{ParserConfig as Config, ParserImpl}; + bitflags! { /// 5.1.5 Grammar Notation /// A production may be parameterized by a subscripted annotation of the form “[parameters]”, @@ -166,6 +168,11 @@ impl Context { self.and(Self::NewTarget, include) } + #[inline] + pub(crate) fn and_top_level(self, include: bool) -> Self { + self.and(Self::TopLevel, include) + } + #[inline] fn and(self, flag: Self, set: bool) -> Self { if set { self | flag } else { self - flag } @@ -191,3 +198,44 @@ impl StatementContext { !matches!(self, Self::Program | Self::StatementList) } } + +impl ParserImpl<'_, C> { + #[expect(clippy::inline_always)] + #[inline(always)] // inline because this is always on a hot path + pub(crate) fn context_add(&mut self, add_flags: Context, cb: F) -> T + where + F: FnOnce(&mut Self) -> T, + { + let ctx = self.ctx; + self.ctx = ctx.union(add_flags); + let result = cb(self); + self.ctx = ctx; + result + } + + #[expect(clippy::inline_always)] + #[inline(always)] // inline because this is always on a hot path + pub(crate) fn context_remove(&mut self, remove_flags: Context, cb: F) -> T + where + F: FnOnce(&mut Self) -> T, + { + let ctx = self.ctx; + self.ctx = ctx.difference(remove_flags); + let result = cb(self); + self.ctx = ctx; + result + } + + #[expect(clippy::inline_always)] + #[inline(always)] // inline because this is always on a hot path + pub(crate) fn context(&mut self, add_flags: Context, remove_flags: Context, cb: F) -> T + where + F: FnOnce(&mut Self) -> T, + { + let ctx = self.ctx; + self.ctx = ctx.difference(remove_flags).union(add_flags); + let result = cb(self); + self.ctx = ctx; + result + } +} diff --git a/vendor/oxc_parser/src/cursor.rs b/vendor/oxc_parser/src/cursor.rs index 672ee2119..071a4d24d 100644 --- a/vendor/oxc_parser/src/cursor.rs +++ b/vendor/oxc_parser/src/cursor.rs @@ -1,27 +1,25 @@ -//! Code related to navigating `Token`s from the lexer +//! Token cursor: reading, consuming, expecting and re-lexing the current token, +//! and checkpoints for backtracking. -use oxc_allocator::{ArenaBox, ArenaVec, Dummy, GetAllocator}; -use oxc_ast::ast::{BindingRestElement, RegExpFlags}; -use oxc_span::{GetSpan, Span}; +use oxc_allocator::{Dummy, GetAllocator}; +use oxc_ast::ast::RegExpFlags; +use oxc_span::Span; use oxc_str::JSStr; use crate::{ - Context, ParserConfig as Config, ParserImpl, + ParserConfig as Config, ParserImpl, diagnostics::{self, ParserDiagnostic}, - error_handler::FatalError, lexer::{Kind, LexerCheckpoint, Token, cold_branch}, }; -/// Speculation budget spent on each lexer diagnostic copied into a -/// checkpoint, in bytes read. -const DIAGNOSTIC_COPY_COST: u64 = 16; - +#[derive(Clone, Copy)] pub struct ParserCheckpoint<'a> { lexer: LexerCheckpoint<'a>, cur_token: Token, prev_token_end: u32, errors_pos: usize, - fatal_error: Option>, + cover_parenthesized_len: usize, + has_fatal_error: bool, } impl<'a, C: Config> ParserImpl<'a, C> { @@ -124,7 +122,10 @@ impl<'a, C: Config> ParserImpl<'a, C> { /// so every caller unwinds without reading more tokens. #[inline] fn check_parse_limits(&mut self) { - if self.stack_exhausted || self.speculation_budget_exhausted || self.below_stack_floor() { + if self.stack_exhausted.get() + || self.speculation_budget_exhausted + || self.below_stack_floor() + { self.stop_at_parse_limit(); } } @@ -148,7 +149,7 @@ impl<'a, C: Config> ParserImpl<'a, C> { #[cold] #[inline(never)] fn stop_at_parse_limit(&mut self) { - if self.speculation_budget_exhausted && !self.stack_exhausted { + if self.speculation_budget_exhausted && !self.stack_exhausted.get() { self.set_fatal_error(diagnostics::speculation_budget_exhausted(self.token.span())); } else { self.stop_at_stack_floor(); @@ -158,7 +159,7 @@ impl<'a, C: Config> ParserImpl<'a, C> { #[cold] #[inline(never)] fn stop_at_stack_floor(&mut self) { - self.stack_exhausted = true; + self.stack_exhausted.set(true); self.set_fatal_error(diagnostics::stack_exhausted(self.token.span())); } @@ -171,6 +172,19 @@ impl<'a, C: Config> ParserImpl<'a, C> { Dummy::dummy(self.allocator()) } + /// [`Self::stop_at_stack_floor`] for a check that reads no token and + /// can't change the parser: the error the check fails with. The parse + /// stops at the next token it reads, and reports + /// [`ParserReturn::stack_exhausted`] even if it reads none. + /// + /// [`ParserReturn::stack_exhausted`]: crate::ParserReturn::stack_exhausted + #[cold] + #[inline(never)] + pub(crate) fn stack_floor_error(&self, span: Span) -> ParserDiagnostic<'a> { + self.stack_exhausted.set(true); + diagnostics::stack_exhausted(span) + } + /// Move to the next `JSXChild` /// Checks if the current token is escaped if it is a keyword pub(crate) fn advance_for_jsx_child(&mut self) { @@ -204,6 +218,39 @@ impl<'a, C: Config> ParserImpl<'a, C> { self.advance(self.cur_kind()); } + /// Advance if `accept` holds for the token after the current one. + /// + /// Use this instead of [`Lexer::peek_token`] where the answer is nearly always yes, such as + /// a modifier keyword, which is nearly always followed by the member it modifies. The token + /// after is then lexed once and kept. Peeking lexes it, discards it, and leaves it to be + /// lexed again. + /// + /// [`Lexer::peek_token`]: crate::lexer::Lexer::peek_token + #[inline] + pub(crate) fn eat_if_next(&mut self, accept: impl FnOnce(Token) -> bool) -> bool { + let checkpoint = self.lexer.checkpoint(); + let next = self.lexer.next_token(); + if !accept(next) { + self.lexer.rewind(checkpoint); + return false; + } + self.advance_to(next); + true + } + + /// Move to `next`, the token after the current one, which the lexer has already read. + #[inline] + pub(crate) fn advance_to(&mut self, next: Token) { + if self.token.escaped() && self.token.kind().is_any_keyword() { + self.report_escaped_keyword(self.token.span()); + } + // The lexer read `next` before this check, so a parse that stops + // here still moves to it, and unwinds at the token after. + self.check_parse_limits(); + self.prev_token_end = self.token.end(); + self.token = next; + } + /// [Automatic Semicolon Insertion](https://tc39.es/ecma262/#sec-automatic-semicolon-insertion) /// # Errors pub(crate) fn asi(&mut self) { @@ -318,6 +365,7 @@ impl<'a, C: Config> ParserImpl<'a, C> { /// Tell lexer to continue reading jsx identifier if the lexer character position is at `-` for ``. /// /// Returns `true` if was continued. + #[inline] pub(crate) fn continue_lex_jsx_identifier(&mut self) -> bool { if let Some(token) = self.lexer.continue_lex_jsx_identifier(self.token.start()) { self.token = token; @@ -346,7 +394,7 @@ impl<'a, C: Config> ParserImpl<'a, C> { return false; } let kind = self.cur_kind(); - if kind == Kind::ShiftLeft || kind == Kind::LtEq { + if kind == Kind::ShiftLeft { self.token = self.lexer.re_lex_as_typescript_l_angle(2); true } else if kind == Kind::ShiftLeftEq { @@ -373,362 +421,65 @@ impl<'a, C: Config> ParserImpl<'a, C> { } } - pub(crate) fn checkpoint(&mut self) -> ParserCheckpoint<'a> { + pub(crate) fn checkpoint(&self) -> ParserCheckpoint<'a> { ParserCheckpoint { lexer: self.lexer.checkpoint(), cur_token: self.token, prev_token_end: self.prev_token_end, errors_pos: self.errors.len(), - fatal_error: self.fatal_error.take(), - } - } - - pub(crate) fn checkpoint_with_error_recovery(&mut self) -> ParserCheckpoint<'a> { - // The lexer's checkpoint copies every diagnostic it has recorded. - self.diagnostics_copied += self.lexer.errors.len() as u64; - self.check_speculation_budget(); - ParserCheckpoint { - lexer: self.lexer.checkpoint_with_error_recovery(), - cur_token: self.token, - prev_token_end: self.prev_token_end, - errors_pos: self.errors.len(), - fatal_error: self.fatal_error.take(), + cover_parenthesized_len: self.state.cover_parenthesized.len(), + has_fatal_error: self.fatal_error.is_some(), } } pub(crate) fn rewind(&mut self, checkpoint: ParserCheckpoint<'a>) { - let ParserCheckpoint { lexer, cur_token, prev_token_end, errors_pos, fatal_error } = - checkpoint; - + let ParserCheckpoint { + lexer, + cur_token, + prev_token_end, + errors_pos, + cover_parenthesized_len, + has_fatal_error, + } = checkpoint; + + // A fatal error set after the checkpoint is discarded. If it is a lexer error that + // `set_unexpected` took from the lexer, give it back. + if !has_fatal_error + && let Some(fatal_error) = self.fatal_error.take() + && self.lexer.errors.len() < lexer.errors_len() + { + self.lexer.errors.push(fatal_error.error); + } self.lexer.rewind(lexer); self.check_speculation_budget(); self.token = cur_token; self.prev_token_end = prev_token_end; self.errors.truncate(errors_pos); - self.fatal_error = fatal_error; + self.state.cover_parenthesized.truncate(cover_parenthesized_len); } /// Sets the budget's stop once the work spent on speculation passes it: /// the bytes the lexer has read beyond its position, which a rewind made - /// it read or will make it read again, and the diagnostics copied into - /// checkpoints, each an allocation of about a hundred bytes, at - /// [`DIAGNOSTIC_COPY_COST`] each. A parse already stopped at the stack - /// floor is unwinding, and reads nothing again. + /// it read or will make it read again. A parse already stopped at the + /// stack floor is unwinding, and reads nothing again. #[inline] fn check_speculation_budget(&mut self) { - let work = self.lexer.bytes_read_ahead().saturating_add( - self.diagnostics_copied.saturating_mul(DIAGNOSTIC_COPY_COST), - ); - if !self.stack_exhausted && work > self.speculation_limit { + if !self.stack_exhausted.get() && self.lexer.bytes_read_ahead() > self.speculation_limit { self.speculation_budget_exhausted = true; } } + /// Rewind to `checkpoint`, keeping the comments and irregular whitespace lexed after it. + /// Only for when the source after `checkpoint` is not all lexed again. + pub(crate) fn rewind_keeping_trivia(&mut self, mut checkpoint: ParserCheckpoint<'a>) { + self.lexer.keep_trivia(&mut checkpoint.lexer); + self.rewind(checkpoint); + } + pub(crate) fn lookahead(&mut self, predicate: impl Fn(&mut ParserImpl<'a, C>) -> U) -> U { let checkpoint = self.checkpoint(); let answer = predicate(self); self.rewind(checkpoint); answer } - - #[expect(clippy::inline_always)] - #[inline(always)] // inline because this is always on a hot path - pub(crate) fn context_add(&mut self, add_flags: Context, cb: F) -> T - where - F: FnOnce(&mut Self) -> T, - { - let ctx = self.ctx; - self.ctx = ctx.union(add_flags); - let result = cb(self); - self.ctx = ctx; - result - } - - #[expect(clippy::inline_always)] - #[inline(always)] // inline because this is always on a hot path - pub(crate) fn context_remove(&mut self, remove_flags: Context, cb: F) -> T - where - F: FnOnce(&mut Self) -> T, - { - let ctx = self.ctx; - self.ctx = ctx.difference(remove_flags); - let result = cb(self); - self.ctx = ctx; - result - } - - #[expect(clippy::inline_always)] - #[inline(always)] // inline because this is always on a hot path - pub(crate) fn context(&mut self, add_flags: Context, remove_flags: Context, cb: F) -> T - where - F: FnOnce(&mut Self) -> T, - { - let ctx = self.ctx; - self.ctx = ctx.difference(remove_flags).union(add_flags); - let result = cb(self); - self.ctx = ctx; - result - } - - pub(crate) fn parse_normal_list( - &mut self, - open: Kind, - close: Kind, - f: F, - ) -> ArenaVec<'a, T> - where - F: FnMut(&mut Self) -> T, - { - let opening_span = self.cur_token().span(); - self.expect(open); - let mut list = ArenaVec::new_in(self); - self.parse_normal_list_into(&mut list, close, f); - self.expect_closing(close, opening_span); - list - } - - #[expect(clippy::inline_always)] - #[inline(always)] - pub(crate) fn parse_normal_list_into( - &mut self, - list: &mut ArenaVec<'a, T>, - close: Kind, - mut parse_element: F, - ) where - F: FnMut(&mut Self) -> T, - { - loop { - if self.at(close) || self.has_fatal_error() { - break; - } - let element = parse_element(self); - list.push(element); - } - } - - pub(crate) fn parse_normal_list_breakable( - &mut self, - open: Kind, - close: Kind, - f: F, - ) -> ArenaVec<'a, T> - where - F: Fn(&mut Self) -> Option, - { - let opening_span = self.cur_token().span(); - self.expect(open); - let mut list = ArenaVec::new_in(self); - self.parse_normal_list_breakable_into(&mut list, close, f); - self.expect_closing(close, opening_span); - list - } - - #[expect(clippy::inline_always)] - #[inline(always)] - fn parse_normal_list_breakable_into( - &mut self, - list: &mut ArenaVec<'a, T>, - close: Kind, - parse_element: F, - ) where - F: Fn(&mut Self) -> Option, - { - loop { - if self.at(close) || self.has_fatal_error() { - break; - } - if let Some(element) = parse_element(self) { - list.push(element); - } else { - break; - } - } - } - - pub(crate) fn parse_delimited_list( - &mut self, - close: Kind, - separator: Kind, - opening_span: Span, - mut parse_element: F, - ) -> (ArenaVec<'a, T>, Option) - where - F: FnMut(&mut Self) -> T, - { - if self.at(close) || self.has_fatal_error() { - return (ArenaVec::new_in(self), None); - } - let first = parse_element(self); - if self.at(close) || self.has_fatal_error() { - let mut list = ArenaVec::with_capacity_in(1, self); - list.push(first); - return (list, None); - } - let mut list = ArenaVec::with_capacity_in(2, self); - list.push(first); - let trailing_separator = self.parse_delimited_list_rest( - &mut list, - close, - separator, - opening_span, - parse_element, - ); - (list, trailing_separator) - } - - #[expect(clippy::inline_always)] - #[inline(always)] - pub(crate) fn parse_delimited_list_into( - &mut self, - list: &mut ArenaVec<'a, T>, - close: Kind, - separator: Kind, - opening_span: Span, - mut parse_element: F, - ) -> Option - where - F: FnMut(&mut Self) -> T, - { - if self.at(close) || self.has_fatal_error() { - return None; - } - let element = parse_element(self); - list.push(element); - self.parse_delimited_list_rest(list, close, separator, opening_span, parse_element) - } - - pub(crate) fn parse_delimited_list_rest( - &mut self, - list: &mut ArenaVec<'a, T>, - close: Kind, - separator: Kind, - opening_span: Span, - mut parse_element: F, - ) -> Option - where - F: FnMut(&mut Self) -> T, - { - loop { - let kind = self.cur_kind(); - if kind == close || self.has_fatal_error() { - return None; - } - if kind != separator { - self.set_fatal_error(diagnostics::expect_closing_or_separator( - close.to_str(), - separator.to_str(), - kind.to_str(), - self.cur_token().span(), - opening_span, - )); - return None; - } - self.advance(separator); - let kind = self.cur_kind(); - if kind == close { - let trailing_separator = self.prev_token_end - 1; - return Some(trailing_separator); - } - if matches!(kind, Kind::Eof | Kind::Undetermined) { - return None; - } - let element = parse_element(self); - list.push(element); - } - } - - pub(crate) fn parse_delimited_list_with_rest( - &mut self, - close: Kind, - opening_span: Span, - parse_element: E, - parse_rest: R, - rest_last_diagnostic: D, - ) -> (ArenaVec<'a, A>, Option>>) - where - E: Fn(&mut Self) -> A, - R: Fn(&mut Self) -> ArenaBox<'a, BindingRestElement<'a>>, - D: Fn(Span) -> ParserDiagnostic<'a>, - { - let mut list = ArenaVec::new_in(self); - let rest = self.parse_delimited_list_with_rest_into( - &mut list, - close, - opening_span, - parse_element, - parse_rest, - rest_last_diagnostic, - ); - (list, rest) - } - - #[expect(clippy::inline_always)] - #[inline(always)] - fn parse_delimited_list_with_rest_into( - &mut self, - list: &mut ArenaVec<'a, A>, - close: Kind, - opening_span: Span, - parse_element: E, - parse_rest: R, - rest_last_diagnostic: D, - ) -> Option>> - where - E: Fn(&mut Self) -> A, - R: Fn(&mut Self) -> ArenaBox<'a, BindingRestElement<'a>>, - D: Fn(Span) -> ParserDiagnostic<'a>, - { - let mut rest: Option>> = None; - let mut first = true; - loop { - let kind = self.cur_kind(); - if kind == close || self.has_fatal_error() { - break; - } - - if first { - first = false; - } else { - let comma_span = self.cur_token().span(); - if kind != Kind::Comma { - let error = diagnostics::expect_closing_or_separator( - close.to_str(), - Kind::Comma.to_str(), - kind.to_str(), - comma_span, - opening_span, - ); - self.set_fatal_error(error); - break; - } - self.bump_any(); - let kind = self.cur_kind(); - if kind == close { - if rest.is_some() && !self.ctx.has_ambient() { - self.error(diagnostics::rest_element_trailing_comma(comma_span)); - } - break; - } - if matches!(kind, Kind::Eof | Kind::Undetermined) { - break; - } - } - - if let Some(r) = &rest { - self.set_fatal_error(rest_last_diagnostic(r.span())); - break; - } - - // Re-capture kind to get the current token (may have changed after else branch) - let kind = self.cur_kind(); - if kind == Kind::Dot3 { - rest.replace(parse_rest(self)); - } else { - let element = parse_element(self); - list.push(element); - } - } - - rest - } } diff --git a/vendor/oxc_parser/src/diagnostics.rs b/vendor/oxc_parser/src/diagnostics.rs index 624fca8d4..e1bece7f4 100644 --- a/vendor/oxc_parser/src/diagnostics.rs +++ b/vendor/oxc_parser/src/diagnostics.rs @@ -4,7 +4,10 @@ use oxc_ast::ast::REGEXP_FLAGS_LIST; use oxc_diagnostics::OxcDiagnostic; use oxc_span::Span; -use crate::modifiers::{Modifier, ModifierKind, ModifierKinds}; +use crate::{ + MAX_LEN_ERROR, + modifiers::{Modifier, ModifierKind, ModifierKinds}, +}; trait DiagnosticExt { fn with_allowed_modifier_help(self, allowed: Option) -> Self; @@ -88,7 +91,7 @@ macro_rules! parser_diagnostics { parser_diagnostics! { overlong_source() => { - OxcDiagnostic::error("Source length exceeds 4 GiB limit") + OxcDiagnostic::error(MAX_LEN_ERROR) }; stack_exhausted(span: Span) => { @@ -219,6 +222,12 @@ parser_diagnostics! { OxcDiagnostic::error("Invalid Unicode escape sequence").with_label(span) }; + invalid_numeric_separator(span: Span) => { + OxcDiagnostic::error("Numeric separators must appear between digits") + .with_label(span) + .with_help("Remove the separator or place it between two digits") + }; + invalid_character(c: char, span: Span) => { OxcDiagnostic::error(format!("Invalid Character `{c}`")).with_label(span) }; @@ -458,6 +467,12 @@ parser_diagnostics! { .with_label(span) }; + invalid_arrow_function_parameter(span: Span) => { + OxcDiagnostic::error("Invalid arrow function parameter") + .with_help("Expected an identifier or a destructuring pattern.") + .with_label(span) + }; + a_rest_parameter_cannot_be_optional(span: Span) => { ts_error("1047", "A rest parameter cannot be optional") .with_label(span) diff --git a/vendor/oxc_parser/src/error_handler.rs b/vendor/oxc_parser/src/error_handler.rs index cf8dd9282..2cb15e672 100644 --- a/vendor/oxc_parser/src/error_handler.rs +++ b/vendor/oxc_parser/src/error_handler.rs @@ -24,6 +24,7 @@ impl<'a, C: Config> ParserImpl<'a, C> { // The lexer should have reported a more meaningful diagnostic // when it is a undetermined kind. if matches!(self.cur_kind(), Kind::Eof | Kind::Undetermined) + && self.fatal_error.is_none() && let Some(error) = self.lexer.errors.pop() { self.set_fatal_error(error); diff --git a/vendor/oxc_parser/src/js/arrow.rs b/vendor/oxc_parser/src/js/arrow.rs index 02070c988..b4aa6b7a2 100644 --- a/vendor/oxc_parser/src/js/arrow.rs +++ b/vendor/oxc_parser/src/js/arrow.rs @@ -1,10 +1,24 @@ +//! Arrow functions. +//! +//! `( … )` and `async ( … )` are parsed once with the cover grammars in [`super::cover`], +//! and refined to arrow function parameters if `=>` follows. + +use std::{mem, num::NonZeroU32}; + use oxc_allocator::{ArenaBox, ArenaVec}; use oxc_ast::ast::*; -use oxc_span::{FileExtension, GetSpan, Span}; +use oxc_span::{FileExtension, Span}; +use oxc_str::Ident; use oxc_syntax::precedence::Precedence; -use super::{FunctionKind, Tristate, grammar::CoverGrammar}; -use crate::{Context, ParserConfig as Config, ParserImpl, diagnostics, lexer::Kind}; +use super::{ + FunctionKind, Tristate, + cover::{Cover, CoverElement, CoverIdentifier, CoverList}, + operator::kind_to_precedence, +}; +use crate::{ + Context, ParserConfig as Config, ParserImpl, cursor::ParserCheckpoint, diagnostics, lexer::Kind, +}; struct ArrowFunctionHead<'a> { type_parameters: Option>>, @@ -15,69 +29,555 @@ struct ArrowFunctionHead<'a> { } impl<'a, C: Config> ParserImpl<'a, C> { - pub(super) fn try_parse_arrow_function_expression( + /// `CoverParenthesizedExpressionAndArrowParameterList`[Yield, Await] : + /// ( `Expression`[+In, ?Yield, ?Await] ) + /// ( `Expression`[+In, ?Yield, ?Await] , ) + /// ( ) + /// ( ... `BindingIdentifier`[?Yield, ?Await] ) + /// ( ... `BindingPattern`[?Yield, ?Await] ) + /// ( `Expression`[+In, ?Yield, ?Await] , ... `BindingIdentifier`[?Yield, ?Await] ) + /// ( `Expression`[+In, ?Yield, ?Await] , ... `BindingPattern`[?Yield, ?Await] ) + /// + /// Returns the expression, and whether it is an arrow function. + pub(super) fn parse_parenthesized_expression_or_arrow_function( &mut self, allow_return_type_in_arrow_function: bool, - ) -> Option> { - let kind = match self.cur_kind() { - Kind::Async => { - // Both async arrow forms share the token after `async`. Classify them under - // one checkpoint instead of restarting lookahead for a single parameter. - let checkpoint = self.checkpoint(); - self.bump_any(); // bump `async` - if self.cur_token().is_on_new_line() { - self.rewind(checkpoint); - return None; - } - let kind = match self.cur_kind() { - Kind::LParen | Kind::LAngle => { - self.is_parenthesized_arrow_function_expression_worker(true) - } - kind if kind.is_binding_identifier() => { - self.bump_any(); - let is_arrow = self.at(Kind::Arrow); - self.rewind(checkpoint); - return is_arrow.then(|| { - self.parse_async_simple_arrow_function_expression( - allow_return_type_in_arrow_function, - ) - }); + no_side_effects_comments: Option<(u32, NonZeroU32)>, + ) -> (Expression<'a>, bool) { + debug_assert!(self.at(Kind::LParen)); + let start = self.cur_start(); + self.bump_any(); // `(` + let first_start = self.cur_start(); + let mut cover = Cover::new( + start, + start, + self.state.cover_elements.len(), + self.state.cover_parenthesized.len(), + /* is_async */ false, + ); + + let end = 'list: { + let kind = self.cur_kind(); + let mut identifier = None; + if kind == Kind::Ident { + let ident = self.parse_cover_identifier(); + // `(a)` and `(a) => …` + if self.at(Kind::RParen) { + match self.parse_parenthesized_identifier_or_arrow_function( + start, + ident, + allow_return_type_in_arrow_function, + ) { + Ok(result) => return result, + Err(end) => break 'list end, } - _ => Tristate::False, - }; - self.rewind(checkpoint); - kind + } + identifier = Some(ident); } - Kind::LParen => { - // This check only reads lexer tokens. Keep one checkpoint for both the - // literal fast path and the remaining lookahead, so the first token is read once. - let checkpoint = self.lexer.checkpoint(); - let second = self.lexer.next_token().kind(); - let result = if second.is_literal() { - Tristate::False + + // A first element that cannot be a `BindingElement` makes the list + // a parenthesized expression: `(a.b)`, `(a + b)`, `(!a)`, `(function () {})`, + // `(
)`. + let first_parsed = if identifier.is_some() { + Self::continues_identifier_expression(self.cur_kind()) + } else { + Self::cannot_start_binding_element(kind) + }; + if first_parsed { + match self.parse_parenthesized_expression_first_element( + cover, + identifier.take(), + no_side_effects_comments, + ) { + Ok(expression) => return (expression, false), + Err(Some(end)) => break 'list end, + Err(None) => {} + } + } + + match self.parse_cover_list(start, cover.base, false, first_parsed, identifier) { + CoverList::Parameters(params) => { + let arrow = self.parse_cover_parameters_arrow_function( + cover, + params, + allow_return_type_in_arrow_function, + ); + return (arrow, true); + } + CoverList::Undecided { trailing_comma, end } => { + cover.trailing_comma = trailing_comma; + end + } + } + }; + + if self.fatal_error.is_some() { + return (self.abandon_cover(cover), false); + } + if let Some(arrow) = + self.try_parse_cover_arrow_function(cover, allow_return_type_in_arrow_function) + { + return (arrow, true); + } + let expression = self.cover_elements_to_parenthesized_expression( + cover, + first_start, + end, + no_side_effects_comments, + ); + (expression, false) + } + + /// Whether `kind` after an identifier continues an expression that is not a `BindingElement`. + #[inline] + fn continues_identifier_expression(kind: Kind) -> bool { + matches!(kind, Kind::Dot | Kind::QuestionDot | Kind::LParen | Kind::LBrack) + || kind.is_template_start_of_tagged_template() + || kind_to_precedence(kind).is_some() + } + + /// Parse `(a)` or `(a) => …` after `a`. + /// + /// Returns `Err` with the end of `a`, pushed as a cover element, if a TypeScript `:` follows, + /// which may start a return type or end the consequent of a conditional expression. + #[expect(clippy::inline_always)] + #[inline(always)] + fn parse_parenthesized_identifier_or_arrow_function( + &mut self, + start: u32, + identifier: CoverIdentifier<'a>, + allow_return_type_in_arrow_function: bool, + ) -> Result<(Expression<'a>, bool), u32> { + let CoverIdentifier { span, name, .. } = identifier; + self.bump_any(); // `)` + + match self.cur_kind() { + // `(a) => …` + Kind::Arrow => { + let pattern = BindingPattern::new_binding_identifier(span, name, self); + let param = FormalParameter::new_plain(span, pattern, self); + let params = FormalParameters::boxed( + self.end_span(start), + FormalParameterKind::ArrowFormalParameters, + ArenaVec::from_value_in(param, self), + None, + self, + ); + let arrow = self.parse_arrow_function_rest( + start, + false, + params, + None, + allow_return_type_in_arrow_function, + ); + Ok((arrow, true)) + } + // `(a): T => …` or `c ? (a) : b` + Kind::Colon if self.is_ts => { + self.state.cover_elements.push(CoverElement::Identifier { span, name }); + Err(span.end) + } + // `(a)` + _ => { + // An enclosing cover list cannot become a binding pattern with `(a)` in it. + if self.state.cover_depth > 0 { + self.state.cover_parenthesized.push(span.start); + } + let expression = Expression::new_identifier(span, name, self); + let expression = if self.options.preserve_parens { + Expression::new_parenthesized_expression(self.end_span(start), expression, self) } else { - self.is_parenthesized_arrow_function_expression_after_lparen(second, false) + expression }; - self.lexer.rewind(checkpoint); - result - } - Kind::LAngle => { - self.lookahead(|p| p.is_parenthesized_arrow_function_expression_worker(false)) + Ok((expression, false)) } - _ => Tristate::False, + } + } + + /// Whether an element that starts with `kind` cannot be a `BindingElement`. + /// + /// `<` starts a JSX element, a type assertion, or an arrow function with type parameters. + /// Most JSX elements which start an expression are directly inside parentheses. + #[inline] + fn cannot_start_binding_element(kind: Kind) -> bool { + kind.is_literal() + || kind.is_unary_operator() + || kind.is_update_operator() + || kind.is_template_start_of_tagged_template() + || matches!( + kind, + Kind::Function + | Kind::Class + | Kind::New + | Kind::LParen + | Kind::Slash + | Kind::LAngle + ) + } + + /// Parse the first element of a list that cannot be arrow function parameters, and + /// `( Expression )` if it is the only element. + /// + /// Otherwise the element is pushed as a cover element, and returns `Err` with its end if + /// `)` follows it, or `Err(None)` if more elements follow. + fn parse_parenthesized_expression_first_element( + &mut self, + cover: Cover, + identifier: Option>, + no_side_effects_comments: Option<(u32, NonZeroU32)>, + ) -> Result, Option> { + let ctx = self.ctx; + self.ctx = ctx.and_in(true).and_decorator(false); + // Record parentheses in it, as in `((a)) => {}`. + self.state.cover_depth += 1; + let expression = match identifier { + Some(identifier) => self.parse_cover_identifier_expression(identifier), + None => self.parse_assignment_expression_or_higher(), }; - match kind { - Tristate::False => None, - Tristate::True => Some(self.parse_parenthesized_arrow_function_expression( - allow_return_type_in_arrow_function, - )), - Tristate::Maybe if REUSE_JS_HEAD => { - self.parse_possible_js_parenthesized_expression(allow_return_type_in_arrow_function) + self.state.cover_depth -= 1; + self.ctx = ctx; + + if !self.at(Kind::RParen) || self.fatal_error.is_some() { + self.state.cover_elements.push(CoverElement::Expression(expression)); + return Err(None); + } + let end = self.prev_token_end; + self.bump_any(); // `)` + + // `(1) => {}` is reported by refining the list to parameters. + if self.at(Kind::Arrow) { + self.state.cover_elements.push(CoverElement::Expression(expression)); + return Err(Some(end)); + } + Ok(self.finish_parenthesized_expression( + cover.start, + cover.parenthesized_base, + expression, + no_side_effects_comments, + )) + } + + /// `AsyncArrowFunction`[In, Yield, Await] : + /// async [no `LineTerminator` here] `AsyncArrowBindingIdentifier`[?Yield] [no `LineTerminator` here] => `AsyncConciseBody`[?In] + /// `CoverCallExpressionAndAsyncArrowHead`[?Yield, ?Await] [no `LineTerminator` here] => `AsyncConciseBody`[?In] + /// + /// Returns the expression, and whether it is an arrow function. If it is not, it is the + /// call `async(…)`. Returns `None` with the cursor at `async` if `async` is an identifier. + pub(super) fn try_parse_async_arrow_function_or_call( + &mut self, + allow_return_type_in_arrow_function: bool, + ) -> Option<(Expression<'a>, bool)> { + debug_assert!(self.at(Kind::Async)); + if self.fatal_error.is_some() { + return None; + } + let start = self.cur_start(); + let checkpoint = self.checkpoint(); + // An escaped `async` is only an error in an arrow function. + let is_escaped = self.cur_token().escaped(); + let (async_span, async_name) = self.parse_identifier_kind(Kind::Ident); + + let token = self.cur_token(); + if !token.is_on_new_line() { + let kind = token.kind(); + if kind == Kind::LParen { + return self.parse_async_call_or_arrow_function( + checkpoint, + async_span, + async_name, + is_escaped, + allow_return_type_in_arrow_function, + ); } - Tristate::Maybe => self.parse_possible_parenthesized_arrow_function_expression( + if kind == Kind::Ident { + // `async a => …` + let ident = self.parse_plain_binding_identifier(); + if self.at(Kind::Arrow) { + if is_escaped { + self.error(diagnostics::escaped_keyword(async_span)); + } + let arrow = self.parse_simple_arrow_function_expression( + start, + ident, + /* async */ true, + allow_return_type_in_arrow_function, + ); + return Some((arrow, true)); + } + } else if kind == Kind::LAngle && self.is_ts { + // `async (x) => ...`. + // `is_ts` check above because in JS/JSX, `async <` is a comparison + // (`f(async < b, c)`). + self.rewind(checkpoint); + return self + .try_parse_generic_arrow_function_expression( + allow_return_type_in_arrow_function, + ) + .map(|arrow| (arrow, true)); + } else if kind.is_binding_identifier() { + // `async yield => …` + self.bump_any(); + if self.at(Kind::Arrow) { + self.rewind(checkpoint); + let arrow = self.parse_async_simple_arrow_function_expression( + allow_return_type_in_arrow_function, + ); + return Some((arrow, true)); + } + } + } + self.rewind(checkpoint); + None + } + + /// `CoverCallExpressionAndAsyncArrowHead`[Yield, Await] : + /// `MemberExpression`[?Yield, ?Await] `Arguments`[?Yield, ?Await] + /// + /// The cursor is at `(`, and `checkpoint` is at `async`. + fn parse_async_call_or_arrow_function( + &mut self, + checkpoint: ParserCheckpoint<'a>, + async_span: Span, + async_name: Ident<'a>, + is_escaped: bool, + allow_return_type_in_arrow_function: bool, + ) -> Option<(Expression<'a>, bool)> { + let start = async_span.start; + // `await` is reserved in the parameters of an async arrow function, but not in the + // arguments of a call outside of async code: the list may have to be parsed again. + let may_parse_again = !self.ctx.has_await(); + let had_module_syntax = self.module_record_builder.has_module_syntax(); + let deferred_script_errors_len = self.deferred_script_errors.len(); + let lparen = self.cur_start(); + self.bump_any(); // `(` + let mut cover = Cover::new( + start, + lparen, + self.state.cover_elements.len(), + self.state.cover_parenthesized.len(), + /* is_async */ true, + ); + let base = cover.base; + + let outer_mentions_await = mem::replace(&mut self.state.mentions_await, false); + let list = self.parse_cover_list(lparen, base, true, false, None); + let mentions_await = self.state.mentions_await; + self.state.mentions_await |= outer_mentions_await; + + if may_parse_again + && mentions_await + && (matches!(list, CoverList::Parameters(_)) + || self.fatal_error.is_some() + || self.at(Kind::Arrow) + || (self.is_ts && self.at(Kind::Colon))) + { + // Discard what `rewind` does not restore, and parse the list as parameters. + self.state.cover_elements.truncate(base); + self.state.cover_initialized_name.retain(|&start, _| start < lparen); + self.state.trailing_commas.retain(|&start, _| start < lparen); + self.deferred_script_errors.truncate(deferred_script_errors_len); + if !had_module_syntax { + self.module_record_builder.unset_module_syntax(); + } + self.rewind(checkpoint); + return self + .parse_possible_parenthesized_arrow_function_expression( + allow_return_type_in_arrow_function, + ) + .map(|arrow| (arrow, true)); + } + + match list { + CoverList::Parameters(params) => { + if is_escaped { + self.error(diagnostics::escaped_keyword(async_span)); + } + let arrow = self.parse_cover_parameters_arrow_function( + cover, + params, + allow_return_type_in_arrow_function, + ); + return Some((arrow, true)); + } + CoverList::Undecided { trailing_comma, .. } => cover.trailing_comma = trailing_comma, + } + + if self.fatal_error.is_some() { + return Some((self.abandon_cover(cover), false)); + } + if let Some(arrow) = + self.try_parse_cover_arrow_function(cover, allow_return_type_in_arrow_function) + { + if is_escaped { + self.error(diagnostics::escaped_keyword(async_span)); + } + return Some((arrow, true)); + } + let callee = Expression::new_identifier(async_span, async_name, self); + Some((self.cover_elements_to_call_expression(cover, callee), false)) + } + + /// Parse the rest of an arrow function after an undecided cover list, if `=>` or + /// a TypeScript return type follows. + #[expect(clippy::inline_always)] + #[inline(always)] + fn try_parse_cover_arrow_function( + &mut self, + cover: Cover, + allow_return_type_in_arrow_function: bool, + ) -> Option> { + let kind = self.cur_kind(); + if kind == Kind::Arrow { + let params = self.cover_elements_to_parameters(cover, self.end_span(cover.lparen)); + return Some(self.parse_arrow_function_rest( + cover.start, + cover.is_async, + params, + None, allow_return_type_in_arrow_function, - ), + )); + } + if kind == Kind::Colon && self.is_ts { + return self.try_parse_cover_arrow_function_with_return_type( + cover, + allow_return_type_in_arrow_function, + ); } + None + } + + /// Parse `: Type => body` after an undecided cover list, if it is not the `:` of + /// a conditional expression. + fn try_parse_cover_arrow_function_with_return_type( + &mut self, + cover: Cover, + allow_return_type_in_arrow_function: bool, + ) -> Option> { + let params_span = self.end_span(cover.lparen); + + if !cover.is_async && self.state.cover_elements.len() == cover.base { + // `(): T => …`: `()` is not an expression, so `:` starts a return type. + let params = self.cover_elements_to_parameters(cover, params_span); + let return_type = self.parse_ts_return_type_annotation(); + return Some(self.parse_arrow_function_rest( + cover.start, + false, + params, + return_type, + allow_return_type_in_arrow_function, + )); + } + + // `case (a.b): c => d` and `a ? (b + 1) : c => d` are not arrow functions. + if self.state.not_parenthesized_arrow.contains(&cover.start) + || !self.is_cover_parameter_list(cover) + { + return None; + } + + let checkpoint = self.checkpoint(); + let return_type = self.parse_cover_return_type(cover.is_async); + 'reject: { + if self.fatal_error.is_some() || !self.at(Kind::Arrow) { + break 'reject; + } + self.expect_arrow(); + + if allow_return_type_in_arrow_function { + let params = self.cover_elements_to_parameters(cover, params_span); + let head = ArrowFunctionHead { + type_parameters: None, + params, + return_type, + r#async: cover.is_async, + start: cover.start, + }; + return Some(self.parse_arrow_function_expression_body( + head, + allow_return_type_in_arrow_function, + )); + } + + // In the consequent of a conditional expression, a return type needs another `:` + // after the body, see `parse_possible_parenthesized_arrow_function_expression`. + let body = + self.parse_arrow_function_body(cover.is_async, allow_return_type_in_arrow_function); + if !self.at(Kind::Colon) { + break 'reject; + } + let params = self.cover_elements_to_parameters(cover, params_span); + return Some(Expression::new_arrow_function_expression( + self.end_span(cover.start), + cover.is_async, + None, + params, + return_type, + body, + self, + )); + } + + self.state.not_parenthesized_arrow.insert(cover.start); + self.rewind(checkpoint); + None + } + + /// Parse the rest of an arrow function whose parameters were decided inside `( … )`. + fn parse_cover_parameters_arrow_function( + &mut self, + cover: Cover, + params: ArenaBox<'a, FormalParameters<'a>>, + allow_return_type_in_arrow_function: bool, + ) -> Expression<'a> { + self.state.cover_parenthesized.truncate(cover.parenthesized_base); + let return_type = + if self.is_ts { self.parse_cover_return_type(cover.is_async) } else { None }; + self.parse_arrow_function_rest( + cover.start, + cover.is_async, + params, + return_type, + allow_return_type_in_arrow_function, + ) + } + + /// Parse the return type of an arrow function at `:`. + fn parse_cover_return_type( + &mut self, + is_async: bool, + ) -> Option>> { + let has_await = self.ctx.has_await(); + self.ctx = self.ctx.union_await_if(is_async); + let return_type = self.parse_ts_return_type_annotation(); + self.ctx = self.ctx.and_await(has_await); + return_type + } + + pub(crate) fn parse_simple_arrow_function_expression( + &mut self, + start: u32, + ident: BindingIdentifier<'a>, + r#async: bool, + allow_return_type_in_arrow_function: bool, + ) -> Expression<'a> { + let span = ident.span; + let pattern = BindingPattern::BindingIdentifier(self.alloc(ident)); + let formal_parameter = FormalParameter::new_plain(span, pattern, self); + let params = FormalParameters::boxed( + span, + FormalParameterKind::ArrowFormalParameters, + [formal_parameter], + None, + self, + ); + + self.parse_arrow_function_rest( + start, + r#async, + params, + None, + allow_return_type_in_arrow_function, + ) } fn parse_async_simple_arrow_function_expression( @@ -111,179 +611,143 @@ impl<'a, C: Config> ParserImpl<'a, C> { ) } - // `second` follows `(` and the lexer is positioned after it. Only lexer state changes; - // callers must rewind their checkpoint before parsing the expression. - fn is_parenthesized_arrow_function_expression_after_lparen( + /// Parse an arrow function with type parameters, if `<` starts one: `(a: T) => a`. + /// + /// The cursor is at `<`, or at an `async` that is followed by `<` on the same line. + /// + /// In JS/JSX this always returns `None`, as type parameters are a TS-only thing. + /// This function is only called in a JS file for a `<` at the start of an expression, + /// which is a syntax error. Checking `is_ts` here, or before calling this function, + /// would add a branch to valid TS/TSX, just to bail out sooner on invalid JS (rare). + pub(super) fn try_parse_generic_arrow_function_expression( &mut self, - second: Kind, - is_async: bool, - ) -> Tristate { - match second { - // Simple cases: "() =>", "(): ", and "() {". - // This is an arrow function with no parameters. - // The last one is not actually an arrow function, - // but this is probably what the user intended. - Kind::RParen => { - let third = self.lexer.next_token().kind(); - match third { - // `async()` can be a call on the true side of a conditional. - Kind::Colon if self.is_ts && is_async => Tristate::Maybe, - // Bare `()` cannot be a parenthesized expression, so the colon - // must start a return type, even inside a conditional expression. - Kind::Colon if self.is_ts => Tristate::True, - Kind::Arrow | Kind::LCurly => Tristate::True, - _ => Tristate::False, - } - } - // If encounter "([" or "({", this could be the start of a binding pattern. - // Examples: - // ([ x ]) => { } - // ({ x }) => { } - // ([ x ]) - // ({ x }) - Kind::LBrack | Kind::LCurly => Tristate::Maybe, - // Simple case: "(..." - // This is an arrow function with a rest parameter. - Kind::Dot3 => { - let third = self.lexer.next_token().kind(); - match third { - // '(...ident' is a lambda - Kind::Ident => Tristate::True, - // '(...null' is not a lambda - kind if kind.is_literal() => Tristate::False, - _ => Tristate::Maybe, - } - } - _ => { - let third = self.lexer.next_token().kind(); - - // Check for "(xxx yyy", where xxx is a modifier and yyy is an identifier. This - // isn't actually allowed, but we want to treat it as a lambda so we can provide - // a good error message. - if second.is_modifier_kind() - && second != Kind::Async - && third.is_binding_identifier() - { - if third == Kind::As { - return Tristate::False; // https://github.com/microsoft/TypeScript/issues/44466 - } - return Tristate::True; - } - - // If we had "(" followed by something that's not an identifier, - // then this definitely doesn't look like a lambda. "this" is not - // valid, but we want to parse it and then give a semantic error. - if !second.is_binding_identifier() && second != Kind::This { - return Tristate::False; - } + allow_return_type_in_arrow_function: bool, + ) -> Option> { + let kind = self.lookahead(|p| { + p.bump(Kind::Async); + p.is_generic_arrow_function_expression() + }); + // Most `<` do not start type parameters. Decide that here, without a call. + if kind == Tristate::False { + return None; + } + self.parse_generic_arrow_function_expression(kind, allow_return_type_in_arrow_function) + } - match third { - // If we have something like "(a:", then we must have a - // type-annotated parameter in an arrow function expression. - Kind::Colon => Tristate::True, - // If we have "(a?:" or "(a?," or "(a?=" or "(a?)" then it is definitely a lambda. - Kind::Question => { - let fourth = self.lexer.next_token().kind(); - if matches!(fourth, Kind::Colon | Kind::Comma | Kind::Eq | Kind::RParen) { - return Tristate::True; - } - Tristate::False - } - // A single identifier needs no speculative parameter parse. Keep `await`, - // `yield`, and `this` on the existing contextual/error-recovery paths. - // A TS return type can still be ambiguous with a conditional's colon. - Kind::RParen if second.is_identifier() => { - match self.lexer.next_token().kind() { - Kind::Arrow => Tristate::True, - Kind::Colon if self.is_ts => Tristate::Maybe, - _ => Tristate::False, - } - } - // If we have "(a," or "(a=" or a context-sensitive keyword in "(a)", - // this *could* be an arrow function. - Kind::Comma | Kind::Eq | Kind::RParen => Tristate::Maybe, - // It is definitely not an arrow function - _ => Tristate::False, - } - } + /// Parse an arrow function with type parameters, given whether the tokens at the cursor + /// start one. + /// + /// The cursor is at `<`, or at an `async` that is followed by `<` on the same line. + pub(crate) fn parse_generic_arrow_function_expression( + &mut self, + kind: Tristate, + allow_return_type_in_arrow_function: bool, + ) -> Option> { + match kind { + Tristate::False => None, + Tristate::True => Some(self.parse_parenthesized_arrow_function_expression( + allow_return_type_in_arrow_function, + )), + Tristate::Maybe => self.parse_possible_parenthesized_arrow_function_expression( + allow_return_type_in_arrow_function, + ), } } - fn is_parenthesized_arrow_function_expression_worker(&mut self, is_async: bool) -> Tristate { - let first = self.cur_kind(); - self.bump_any(); + /// Whether the `<` at the cursor starts the type parameters of an arrow function. + /// + /// Called in TS, in TSX only after `async`, and in JS only for invalid code. + /// Never called in JSX. + fn is_generic_arrow_function_expression(&mut self) -> Tristate { + debug_assert!(self.at(Kind::LAngle)); + self.bump_any(); // `<` let second = self.cur_kind(); - match first { - Kind::LParen => { - self.is_parenthesized_arrow_function_expression_after_lparen(second, is_async) - } - Kind::LAngle => { - // If we have "<" not followed by an identifier, - // then this definitely is not an arrow function. - if !second.is_binding_identifier() && second != Kind::Const { - return Tristate::False; - } + // If we have "<" not followed by an identifier, + // then this definitely is not an arrow function. + if !second.is_binding_identifier() && second != Kind::Const { + return Tristate::False; + } - // JSX overrides - if self.source_type.is_jsx() { - // - // ^^^^^ Optional - self.bump(Kind::Const); - self.bump_any(); - let third = self.cur_kind(); - return match third { - Kind::Extends => { - self.bump_any(); - let fourth = self.cur_kind(); - if matches!(fourth, Kind::Eq | Kind::RAngle | Kind::Slash) { - Tristate::False - } else if fourth.is_binding_identifier() { - Tristate::Maybe - } else { - Tristate::True - } - } - Kind::Eq | Kind::Comma => Tristate::True, - _ => Tristate::False, - }; + // TSX overrides. Only `async <` gets here in TSX. + if self.source_type.is_jsx() { + debug_assert!(self.is_ts); + // + // ^^^^^ Optional + self.bump(Kind::Const); + self.bump_any(); // the name + return self.is_generic_arrow_function_expression_after_jsx_name(); + } + + // `` may start an arrow function, which is then tried first. The exception is + // a type assertion that the next tokens give away, because trying to parse them as + // type parameters and parameters is certain to fail: the name of a type parameter is + // followed by `,`, `=`, `extends` or `>`, not by the rest of a type as in `a`, + // `a`, `a` and `>a`, and the `>` of type parameters is followed by + // `(`, not by an operand as in `a` and `{}`. + // JS only gets here for invalid code. `Maybe` gives it a better error for ``. + if !self.is_ts || second == Kind::Const { + return Tristate::Maybe; + } + self.bump_any(); // the name + match self.cur_kind() { + // ` Tristate::True, + Kind::Dot | Kind::LBrack | Kind::Pipe | Kind::Amp | Kind::LAngle => Tristate::False, + Kind::RAngle => { + self.bump_any(); // `>` + let operand = self.cur_kind(); + if operand.is_identifier_name() + || operand.is_literal() + || operand.is_template_start_of_tagged_template() + || matches!(operand, Kind::LCurly | Kind::LBrack) + { + Tristate::False + } else { + Tristate::Maybe } - Tristate::Maybe } - _ => unreachable!(), + _ => Tristate::Maybe, } } - pub(crate) fn parse_simple_arrow_function_expression( - &mut self, - start: u32, - ident: BindingIdentifier<'a>, - r#async: bool, - allow_return_type_in_arrow_function: bool, - ) -> Expression<'a> { - let span = ident.span; - let pattern = BindingPattern::BindingIdentifier(self.alloc(ident)); - let formal_parameter = FormalParameter::new_plain(span, pattern, self); - let params = FormalParameters::boxed( - span, - FormalParameterKind::ArrowFormalParameters, - [formal_parameter], - None, - self, - ); - - self.expect_arrow(); - self.parse_arrow_function_expression_body( - ArrowFunctionHead { type_parameters: None, params, return_type: None, r#async, start }, - allow_return_type_in_arrow_function, - ) - } - - fn expect_arrow(&mut self) { - if self.cur_token().is_on_new_line() { - self.error(diagnostics::lineterminator_before_arrow(self.cur_token().span())); + /// Whether `<` and a name start the type parameters of an arrow function in a TSX file, + /// where they can also start a JSX element. The cursor is at the token after the name, + /// and moves past an `extends`. + /// + /// ```text + /// TypeParameter : `const`? BindingIdentifier (`extends` Type)? (`=` Type)? + /// JSXOpeningElement : `<` JSXElementName TypeArguments? JSXAttributes? `/`? `>` + /// JSXElementName : JSXIdentifier ((`:` | `.`) JSXIdentifier)* + /// JSXAttributes : (JSXAttributeName (`=` JSXAttributeValue)? | `{` `...` Expression `}`)* + /// ``` + /// + /// The name of a type parameter is followed by `,`, `=`, `extends` or `>`. The name of + /// a JSX element is followed by `.`, `:`, `<`, `{`, `/`, `>` or an attribute name, which may + /// be `extends`. So `,` and `=` are type parameters, `extends` is decided by the token + /// after it, and everything else is a JSX element. That includes ``, which is why + /// the type parameters of an arrow function are written `` in a TSX file. + #[expect(clippy::inline_always)] + #[inline(always)] // Keep `is_generic_arrow_function_expression` in one piece. + pub(crate) fn is_generic_arrow_function_expression_after_jsx_name(&mut self) -> Tristate { + debug_assert!(self.is_ts); + match self.cur_kind() { + Kind::Extends => { + self.bump_any(); + let next = self.cur_kind(); + if matches!(next, Kind::Eq | Kind::RAngle | Kind::Slash) { + // An attribute: ``, ``, ``. + Tristate::False + } else { + // A constraint: `(a) => a`. `(a)` is a syntax error. + Tristate::True + } + } + Kind::Eq | Kind::Comma => Tristate::True, + _ => Tristate::False, } - self.expect(Kind::Arrow); } fn parse_parenthesized_arrow_function_head(&mut self) -> ArrowFunctionHead<'a> { @@ -322,46 +786,6 @@ impl<'a, C: Config> ParserImpl<'a, C> { ArrowFunctionHead { type_parameters, params, return_type, r#async, start } } - /// [ConciseBody](https://tc39.es/ecma262/#prod-ConciseBody) - /// [lookahead ≠ {] `ExpressionBody`[?In, ~Await] - /// { `FunctionBody`[~Yield, ~Await] } - /// `ExpressionBody`[In, Await] : - /// `AssignmentExpression`[?In, ~Yield, ?Await] - fn parse_arrow_function_expression_body( - &mut self, - arrow_function_head: ArrowFunctionHead<'a>, - allow_return_type_in_arrow_function: bool, - ) -> Expression<'a> { - let ArrowFunctionHead { type_parameters, params, return_type, r#async, start } = - arrow_function_head; - let has_await = self.ctx.has_await(); - let has_yield = self.ctx.has_yield(); - self.ctx = self.ctx.and_await(r#async).and_yield(false); - - let body = if self.at(Kind::LCurly) { - ArrowFunctionBody::FunctionBody( - self.context_add(Context::In, Self::parse_function_body), - ) - } else { - let expr = self.context_remove(Context::TopLevel, |p| { - p.parse_assignment_expression_or_higher_impl(allow_return_type_in_arrow_function) - }); - ArrowFunctionBody::from(expr) - }; - - self.ctx = self.ctx.and_await(has_await).and_yield(has_yield); - - Expression::new_arrow_function_expression( - self.end_span(start), - r#async, - type_parameters, - params, - return_type, - body, - self, - ) - } - /// Section [Arrow Function](https://tc39.es/ecma262/#sec-arrow-function-definitions) /// `ArrowFunction`[In, Yield, Await] : /// `ArrowParameters`[?Yield, ?Await] [no `LineTerminator` here] => `ConciseBody`[?In] @@ -374,13 +798,6 @@ impl<'a, C: Config> ParserImpl<'a, C> { self.parse_arrow_function_expression_body(head, allow_return_type_in_arrow_function) } - fn expect_arrow_after_head(&mut self) { - if self.cur_token().is_on_new_line() { - self.error(diagnostics::lineterminator_before_arrow(self.cur_token().span())); - } - self.expect(Kind::Arrow); - } - fn parse_possible_parenthesized_arrow_function_expression( &mut self, allow_return_type_in_arrow_function: bool, @@ -390,7 +807,7 @@ impl<'a, C: Config> ParserImpl<'a, C> { return None; } - let checkpoint = self.checkpoint_with_error_recovery(); + let checkpoint = self.checkpoint(); let head = self.parse_parenthesized_arrow_function_head(); // Rejected heads are rewound, so do not construct an error for the missing arrow. @@ -443,188 +860,73 @@ impl<'a, C: Config> ParserImpl<'a, C> { Some(body) } - #[inline(never)] - fn parse_possible_js_parenthesized_expression( - &mut self, - allow_return_type_in_arrow_function: bool, - ) -> Option> { - let pos = self.cur_token().start(); - if self.state.not_parenthesized_arrow.contains(&pos) { - return None; - } - let checkpoint = self.checkpoint_with_error_recovery(); - let errors_len = self.errors.len(); - let (params, has_trailing_comma) = self.parse_cover_arrow_parameters(); - let head = ArrowFunctionHead { - type_parameters: None, - params, - return_type: None, - r#async: false, - start: pos, - }; - if !self.at(Kind::Arrow) { - // Reuse the successful parameter parse, including its initializers and property - // keys, when it also represents an ordinary parenthesized expression. - if !self.has_fatal_error() - && self.errors.len() == errors_len - && !has_trailing_comma - && head.params.rest.is_none() - && !head.params.items.is_empty() - && let Some(expression) = self.cover_arrow_head_as_expression(head) - { - return Some(expression); - } - self.state.not_parenthesized_arrow.insert(pos); - self.rewind(checkpoint); - return None; - } - self.expect_arrow_after_head(); - if self.has_fatal_error() { - self.state.not_parenthesized_arrow.insert(pos); - self.rewind(checkpoint); - return None; + fn expect_arrow(&mut self) { + if self.at(Kind::Arrow) && self.cur_token().is_on_new_line() { + self.error(diagnostics::lineterminator_before_arrow(self.cur_token().span())); } - Some(self.parse_arrow_function_expression_body(head, allow_return_type_in_arrow_function)) + self.expect(Kind::Arrow); } - #[inline(never)] - fn cover_arrow_head_as_expression( + /// [ConciseBody](https://tc39.es/ecma262/#prod-ConciseBody) + /// [lookahead ≠ {] `ExpressionBody`[?In, ~Await] + /// { `FunctionBody`[~Yield, ~Await] } + /// `ExpressionBody`[In, Await] : + /// `AssignmentExpression`[?In, ~Yield, ?Await] + #[inline] + fn parse_arrow_function_body( &mut self, - head: ArrowFunctionHead<'a>, - ) -> Option> { - let span = head.params.span; - let params = head.params.unbox(); - let len = params.items.len(); - let mut items = params.items.into_iter(); - let first = self.cover_parameter_as_expression(items.next().unwrap())?; - let expression = if len == 1 { - first + r#async: bool, + allow_return_type_in_arrow_function: bool, + ) -> ArrowFunctionBody<'a> { + let has_await = self.ctx.has_await(); + let has_yield = self.ctx.has_yield(); + self.ctx = self.ctx.and_await(r#async).and_yield(false); + + let body = if self.at(Kind::LCurly) { + ArrowFunctionBody::FunctionBody( + self.context_add(Context::In, Self::parse_function_body), + ) } else { - let start = first.span().start; - let mut expressions = ArenaVec::with_capacity_in(len, self); - expressions.push(first); - for item in items { - expressions.push(self.cover_parameter_as_expression(item)?); - } - let end = expressions.last().unwrap().span().end; - Expression::new_sequence_expression(Span::new(start, end), expressions, self) + let expr = self.context_remove(Context::TopLevel, |p| { + p.parse_assignment_expression_or_higher_impl(allow_return_type_in_arrow_function) + }); + ArrowFunctionBody::from(expr) }; - // Keep the wrapper until the caller distinguishes this from an arrow. The caller - // removes it when `preserve_parens` is disabled. - Some(Expression::new_parenthesized_expression(span, expression, self)) + + self.ctx = self.ctx.and_await(has_await).and_yield(has_yield); + body } - fn cover_parameter_as_expression( + /// Parse `=> ConciseBody` after the parameters and return type. + fn parse_arrow_function_rest( &mut self, - param: FormalParameter<'a>, - ) -> Option> { - let left = self.cover_binding_as_expression(param.pattern)?; - Some(if let Some(initializer) = param.initializer { - let left = AssignmentTarget::cover(left, self); - Expression::new_assignment_expression( - param.span, - AssignmentOperator::Assign, - left, - initializer.unbox(), - self, - ) - } else { - left - }) + start: u32, + r#async: bool, + params: ArenaBox<'a, FormalParameters<'a>>, + return_type: Option>>, + allow_return_type_in_arrow_function: bool, + ) -> Expression<'a> { + self.expect_arrow(); + let head = ArrowFunctionHead { type_parameters: None, params, return_type, r#async, start }; + self.parse_arrow_function_expression_body(head, allow_return_type_in_arrow_function) } - fn cover_binding_as_expression( + fn parse_arrow_function_expression_body( &mut self, - pattern: BindingPattern<'a>, - ) -> Option> { - // This reads no token, so it checks the stack floor itself. Below it, - // the caller parses the source again as an expression, which checks - // the floor per token. - if self.below_stack_floor() { - return None; - } - Some(match pattern { - BindingPattern::BindingIdentifier(ident) => { - if ident.name == "await" && !self.ctx.has_await() { - self.state.encountered_await_identifier = true; - } - Expression::new_identifier(ident.span, ident.name, self) - } - BindingPattern::AssignmentPattern(pattern) => { - let pattern = pattern.unbox(); - let left = self.cover_binding_as_expression(pattern.left)?; - let left = AssignmentTarget::cover(left, self); - Expression::new_assignment_expression( - pattern.span, - AssignmentOperator::Assign, - left, - pattern.right, - self, - ) - } - BindingPattern::ArrayPattern(pattern) => { - let pattern = pattern.unbox(); - let mut elements = ArenaVec::with_capacity_in( - pattern.elements.len() + usize::from(pattern.rest.is_some()), - self, - ); - for element in pattern.elements { - // Binding elisions do not retain their token spans. Reparse those arrays. - let expression = self.cover_binding_as_expression(element?)?; - elements.push(ArrayExpressionElement::from(expression)); - } - if let Some(rest) = pattern.rest { - let rest = rest.unbox(); - let argument = self.cover_binding_as_expression(rest.argument)?; - elements.push(ArrayExpressionElement::SpreadElement(SpreadElement::boxed( - rest.span, argument, self, - ))); - } - Expression::new_array_expression(pattern.span, elements, self) - } - BindingPattern::ObjectPattern(pattern) => { - let pattern = pattern.unbox(); - let mut properties = ArenaVec::with_capacity_in( - pattern.properties.len() + usize::from(pattern.rest.is_some()), - self, - ); - for property in pattern.properties { - if property.shorthand - && matches!(property.value, BindingPattern::AssignmentPattern(_)) - { - // Preserve deferred CoverInitializedName validation on the ordinary path. - return None; - } - let value = if property.shorthand { - let BindingPattern::BindingIdentifier(ident) = property.value else { - return None; - }; - // As in object-literal parsing, an `await` shorthand does not mark - // this statement for unambiguous top-level-await reparsing. - Expression::new_identifier(ident.span, ident.name, self) - } else { - self.cover_binding_as_expression(property.value)? - }; - properties.push(ObjectPropertyKind::ObjectProperty(ObjectProperty::boxed( - property.span, - PropertyKind::Init, - property.key, - value, - false, - property.shorthand, - property.computed, - self, - ))); - } - if let Some(rest) = pattern.rest { - let rest = rest.unbox(); - let argument = self.cover_binding_as_expression(rest.argument)?; - properties.push(ObjectPropertyKind::SpreadProperty(SpreadElement::boxed( - rest.span, argument, self, - ))); - } - Expression::new_object_expression(pattern.span, properties, self) - } - }) + arrow_function_head: ArrowFunctionHead<'a>, + allow_return_type_in_arrow_function: bool, + ) -> Expression<'a> { + let ArrowFunctionHead { type_parameters, params, return_type, r#async, start } = + arrow_function_head; + let body = self.parse_arrow_function_body(r#async, allow_return_type_in_arrow_function); + Expression::new_arrow_function_expression( + self.end_span(start), + r#async, + type_parameters, + params, + return_type, + body, + self, + ) } } diff --git a/vendor/oxc_parser/src/js/binding.rs b/vendor/oxc_parser/src/js/binding.rs index a6d7566e3..5a0d67b5e 100644 --- a/vendor/oxc_parser/src/js/binding.rs +++ b/vendor/oxc_parser/src/js/binding.rs @@ -159,7 +159,7 @@ impl<'a, C: Config> ParserImpl<'a, C> { let mut shorthand = false; let is_binding_identifier = self.cur_kind().is_binding_identifier(); let key_cur_kind = self.cur_kind(); - let (key, computed) = self.parse_property_name(); + let key = self.parse_property_name(); let value = if is_binding_identifier && !self.at(Kind::Colon) { // let { a = b } = c @@ -181,7 +181,7 @@ impl<'a, C: Config> ParserImpl<'a, C> { self.parse_binding_pattern_with_initializer() }; - BindingProperty::new(self.end_span(start), key, value, shorthand, computed, self) + BindingProperty::new(self.end_span(start), key, value, shorthand, self) } /// Initializer[In, Yield, Await] : diff --git a/vendor/oxc_parser/src/js/class.rs b/vendor/oxc_parser/src/js/class.rs index 679318af2..329c4ee21 100644 --- a/vendor/oxc_parser/src/js/class.rs +++ b/vendor/oxc_parser/src/js/class.rs @@ -1,5 +1,6 @@ use oxc_allocator::{ArenaBox, ArenaVec, GetAllocator}; use oxc_ast::ast::*; +use oxc_data_structures::buffered_vec::BufferedVec; use oxc_ecmascript::PropName; use oxc_span::{GetSpan, Span}; @@ -9,7 +10,7 @@ use crate::{ modifiers::{ModifierKind, ModifierKinds, Modifiers}, }; -use super::FunctionKind; +use super::{FunctionKind, expression::split_unparenthesized_instantiation}; type ImplementsWithKeywordSpan<'a> = (Span, ArenaVec<'a, TSClassImplements<'a>>); @@ -63,7 +64,7 @@ impl<'a, C: Config> ParserImpl<'a, C> { modifiers: &Modifiers, decorators: ArenaVec<'a, Decorator<'a>>, ) -> ArenaBox<'a, Class<'a>> { - self.bump_any(); // advance `class` + self.expect(Kind::Class); // Move span start to decorator position if this is a class expression. let mut start = start; @@ -91,20 +92,17 @@ impl<'a, C: Config> ParserImpl<'a, C> { let type_parameters = if self.is_ts { self.parse_ts_type_parameters_with_variance() } else { None }; - let (extends, implements) = self.parse_class_heritage_clause(); - let mut heritage = None; - if let Some(mut extends) = extends - && !extends.is_empty() - { - let (expression, type_arguments) = extends.remove(0); - heritage = Some(ClassHeritage::new(expression, type_arguments, self)); - for (expression, type_arguments) in extends { - let expression_span = expression.span(); - let span = type_arguments.map_or(expression_span, |type_arguments| { - expression_span.merge(type_arguments.span) - }); - self.error(diagnostics::classes_can_only_extend_single_class(span)); - } + let (extends, implements) = self.parse_heritage_clause(Self::parse_class_extends_clause); + let mut extends = extends.into_iter().flatten(); + let heritage = extends.next().map(|(expression, type_arguments)| { + ClassHeritage::new(expression, type_arguments, self) + }); + for (expression, type_arguments) in extends { + let expression_span = expression.span(); + let span = type_arguments.map_or(expression_span, |type_arguments| { + expression_span.merge(type_arguments.span) + }); + self.error(diagnostics::classes_can_only_extend_single_class(span)); } let body = self.parse_class_body(); @@ -133,11 +131,11 @@ impl<'a, C: Config> ParserImpl<'a, C> { pub(crate) fn parse_heritage_clause( &mut self, mut parse_extends_clause: F, - ) -> (Option>, Option>) + ) -> (Option, Option>) where - F: FnMut(&mut Self) -> ArenaVec<'a, T>, + F: FnMut(&mut Self) -> T, { - let mut extends: Option> = None; + let mut extends = None; let mut implements: Option = None; loop { @@ -183,40 +181,27 @@ impl<'a, C: Config> ParserImpl<'a, C> { (extends, implements) } - #[expect(clippy::type_complexity)] - fn parse_class_heritage_clause( - &mut self, - ) -> ( - Option< - ArenaVec<'a, (Expression<'a>, Option>>)>, - >, - Option>, - ) { - self.parse_heritage_clause(Self::parse_class_extends_clause) - } - /// `ClassHeritage` /// extends `LeftHandSideExpression`[?Yield, ?Await] fn parse_class_extends_clause( &mut self, - ) -> ArenaVec<'a, (Expression<'a>, Option>>)> - { + ) -> BufferedVec< + ArenaVec<'a, (Expression<'a>, Option>>)>, + 1, + > { self.bump_any(); // bump `extends` - let mut extends = ArenaVec::with_capacity_in(1, self); + // A class has only one superclass. Keep it on the stack while preserving any + // additional entries for the existing multiple-superclass diagnostics. + let mut extends = BufferedVec::new(ArenaVec::new_in(self)); loop { - let mut extend = self.parse_lhs_expression_or_higher(); + let start = self.cur_start(); + let extend = self.parse_lhs_expression_or_higher(); if self.fatal_error.is_some() { break; } - let type_argument; - if let Expression::TSInstantiationExpression(expr) = extend { - let expr = expr.unbox(); - extend = expr.expression; - type_argument = Some(expr.type_arguments); - } else { - type_argument = self.try_parse_type_arguments(); - } + let (extend, type_argument) = split_unparenthesized_instantiation(extend, start); + let type_argument = type_argument.or_else(|| self.try_parse_type_arguments()); extends.push((extend, type_argument)); @@ -377,7 +362,7 @@ impl<'a, C: Config> ParserImpl<'a, C> { self.unexpected() } - fn parse_class_element_name(&mut self, modifiers: &Modifiers) -> (PropertyKey<'a>, bool) { + fn parse_class_element_name(&mut self, modifiers: &Modifiers) -> PropertyKey<'a> { self.verify_modifiers( modifiers, ModifierKinds::all_except([ModifierKind::Const, ModifierKind::In, ModifierKind::Out]), @@ -412,7 +397,7 @@ impl<'a, C: Config> ParserImpl<'a, C> { if private_ident.name == "constructor" { self.error(diagnostics::private_name_constructor(private_ident.span)); } - (PropertyKey::PrivateIdentifier(self.alloc(private_ident)), false) + PropertyKey::PrivateIdentifier(self.alloc(private_ident)) } _ => self.parse_property_name(), } @@ -427,7 +412,7 @@ impl<'a, C: Config> ParserImpl<'a, C> { Context::Yield | Context::Return, Self::parse_block, ); - ClassElement::new_static_block(self.end_span(start), block.unbox().body, self) + ClassElement::new_static_block(self.end_span(start), block.body, self) } /// @@ -435,7 +420,6 @@ impl<'a, C: Config> ParserImpl<'a, C> { &mut self, start: u32, key: PropertyKey<'a>, - computed: bool, definite: Option, modifiers: &Modifiers, decorators: ArenaVec<'a, Decorator<'a>>, @@ -444,7 +428,7 @@ impl<'a, C: Config> ParserImpl<'a, C> { let value = self.eat(Kind::Eq).then(|| { self.context( Context::In | Context::NewTarget, - Context::Yield | Context::Await, + Context::Yield | Context::Await | Context::TopLevel, Self::parse_assignment_expression_or_higher, ) }); @@ -490,7 +474,6 @@ impl<'a, C: Config> ParserImpl<'a, C> { key, type_annotation, value, - computed, modifiers.contains(ModifierKind::Static), modifiers.contains(ModifierKind::Override), definite.is_some(), @@ -507,7 +490,7 @@ impl<'a, C: Config> ParserImpl<'a, C> { modifiers: &Modifiers, decorators: ArenaVec<'a, Decorator<'a>>, ) -> ClassElement<'a> { - let (name, computed) = self.parse_class_element_name(modifiers); + let name = self.parse_class_element_name(modifiers); let value = self.parse_method( modifiers.contains(ModifierKind::Async), None, @@ -520,7 +503,6 @@ impl<'a, C: Config> ParserImpl<'a, C> { name, value, kind, - computed, modifiers.contains(ModifierKind::Static), modifiers.contains(ModifierKind::Override), false, @@ -589,7 +571,6 @@ impl<'a, C: Config> ParserImpl<'a, C> { name, value, MethodDefinitionKind::Constructor, - false, modifiers.contains(ModifierKind::Static), modifiers.contains(ModifierKind::Override), false, @@ -610,7 +591,7 @@ impl<'a, C: Config> ParserImpl<'a, C> { && self.lexer.peek_token().kind() == Kind::LParen { let string_literal = self.parse_known_literal_string(); - return Some(PropertyKey::StringLiteral(self.alloc(string_literal))); + return Some(PropertyKey::StaticStringLiteral(self.alloc(string_literal))); } None } @@ -623,7 +604,7 @@ impl<'a, C: Config> ParserImpl<'a, C> { decorators: ArenaVec<'a, Decorator<'a>>, ) -> ClassElement<'a> { let generator = self.eat(Kind::Star).then_some(self.prev_token_end - 1); - let (name, computed) = self.parse_class_element_name(modifiers); + let name = self.parse_class_element_name(modifiers); let cur_token = self.cur_token(); let optional_span = (cur_token.kind() == Kind::Question).then(|| { @@ -678,7 +659,7 @@ impl<'a, C: Config> ParserImpl<'a, C> { }, ); return self.parse_method_declaration( - start, r#type, generator, name, computed, optional, modifiers, decorators, + start, r#type, generator, name, optional, modifiers, decorators, ); } @@ -693,23 +674,15 @@ impl<'a, C: Config> ParserImpl<'a, C> { if let Some(optional_span) = optional_span { self.error(diagnostics::optional_accessor_property(optional_span)); } - if name.is_specific_string_literal("constructor") && !computed { + if matches!(&name, PropertyKey::StaticStringLiteral(lit) if lit.value == "constructor") + { self.error(diagnostics::constructor_accessor(name.span())); } - return self.parse_class_accessor_property( - start, name, computed, definite, modifiers, decorators, - ); + return self + .parse_class_accessor_property(start, name, definite, modifiers, decorators); } - self.parse_property_declaration( - start, - name, - computed, - optional_span, - definite, - modifiers, - decorators, - ) + self.parse_property_declaration(start, name, optional_span, definite, modifiers, decorators) } fn parse_method_declaration( @@ -718,7 +691,6 @@ impl<'a, C: Config> ParserImpl<'a, C> { r#type: MethodDefinitionType, generator: Option, name: PropertyKey<'a>, - computed: bool, optional: bool, modifiers: &Modifiers, decorators: ArenaVec<'a, Decorator<'a>>, @@ -735,7 +707,6 @@ impl<'a, C: Config> ParserImpl<'a, C> { name, value, MethodDefinitionKind::Method, - computed, modifiers.contains(ModifierKind::Static), modifiers.contains(ModifierKind::Override), optional, @@ -750,7 +721,6 @@ impl<'a, C: Config> ParserImpl<'a, C> { &mut self, start: u32, name: PropertyKey<'a>, - computed: bool, optional_span: Option, definite: Option, modifiers: &Modifiers, @@ -758,11 +728,12 @@ impl<'a, C: Config> ParserImpl<'a, C> { ) -> ClassElement<'a> { let type_annotation = if self.is_ts { self.parse_ts_type_annotation() } else { None }; // Initializer[+In, ?Yield, ?Await]opt - // `new.target` is allowed in a class field initializer. + // `new.target` is allowed in a class field initializer, and `await` in it is not + // top-level `await`. let initializer = self.eat(Kind::Eq).then(|| { self.context( Context::In | Context::NewTarget, - Context::Yield | Context::Await, + Context::Yield | Context::Await | Context::TopLevel, Self::parse_assignment_expression_or_higher, ) }); @@ -791,7 +762,9 @@ impl<'a, C: Config> ParserImpl<'a, C> { PropertyDefinitionType::PropertyDefinition }; let r#static = modifiers.contains(ModifierKind::Static); - if !computed && let Some((name, span)) = name.prop_name() { + if !name.is_computed() + && let Some((name, span)) = name.prop_name() + { if name == "constructor" { self.error(diagnostics::field_constructor(span)); } @@ -832,7 +805,6 @@ impl<'a, C: Config> ParserImpl<'a, C> { name, type_annotation, initializer, - computed, r#static, modifiers.contains(ModifierKind::Declare), modifiers.contains(ModifierKind::Override), @@ -894,7 +866,7 @@ impl<'a, C: Config> ParserImpl<'a, C> { self.error(diagnostics::abstract_with_private_identifier(method.key.span())); } - if !method.computed + if !method.key.is_computed() && let Some((name, span)) = method.key.prop_name() { if method.r#static { diff --git a/vendor/oxc_parser/src/js/cover.rs b/vendor/oxc_parser/src/js/cover.rs new file mode 100644 index 000000000..ed42b8c99 --- /dev/null +++ b/vendor/oxc_parser/src/js/cover.rs @@ -0,0 +1,919 @@ +//! [`CoverParenthesizedExpressionAndArrowParameterList`] and [`CoverCallExpressionAndAsyncArrowHead`]. +//! +//! The elements between the parentheses are parsed once, and refined to parameters or +//! expressions once the token after `)` is known. In TypeScript, the first construct only a +//! parameter can have (`a: T`, `a?`, modifiers) decides the list as parameters. +//! +//! [`CoverParenthesizedExpressionAndArrowParameterList`]: https://tc39.es/ecma262/#prod-CoverParenthesizedExpressionAndArrowParameterList +//! [`CoverCallExpressionAndAsyncArrowHead`]: https://tc39.es/ecma262/#prod-CoverCallExpressionAndAsyncArrowHead + +use std::{mem, num::NonZeroU32}; + +use oxc_allocator::{ArenaBox, ArenaVec, Dummy, GetAllocator}; +use oxc_ast::ast::*; +use oxc_span::{GetSpan, SPAN, Span}; +use oxc_str::Ident; + +use super::{FunctionKind, grammar::CoverGrammar}; +use crate::{ + Context, ParserConfig as Config, ParserImpl, + diagnostics::{self, ParserDiagnostic}, + lexer::Kind, +}; + +/// An element of a cover list whose meaning is not decided yet. +/// +/// Identifiers are by far the most common element. They are kept as their span and name, so +/// that the single node they become is only allocated once it is known which node that is. +pub enum CoverElement<'a> { + /// `a`: a `BindingIdentifier`, or an `IdentifierReference`. + Identifier { span: Span, name: Ident<'a> }, + /// `a = b`: a parameter with an initializer, or an assignment. `end` is the end of `b`. + IdentifierWithInitializer { span: Span, name: Ident<'a>, end: u32, initializer: Expression<'a> }, + /// `{ a } = b`, `[a] = b`: a destructuring parameter with an initializer, or a destructuring + /// assignment. `literal` is the object or array literal, and `end` is the end of `b`. + LiteralWithInitializer { literal: Expression<'a>, end: u32, initializer: Expression<'a> }, + /// Any other `AssignmentExpression`. + Expression(Expression<'a>), + /// `...a` in `async(…)`: an argument, or the rest parameter of an async arrow function. + Spread(ArenaBox<'a, SpreadElement<'a>>), +} + +/// An identifier that starts a cover list element, consumed before the element is known. +#[derive(Clone, Copy)] +pub(super) struct CoverIdentifier<'a> { + pub(super) span: Span, + pub(super) name: Ident<'a>, + pure_comments: Option<(u32, NonZeroU32)>, + no_side_effects_comments: Option<(u32, NonZeroU32)>, +} + +/// A construct that only a parameter can have, found while parsing a cover list. +pub(super) enum CoverParameter<'a> { + /// At the first token of a parameter: `(...a)`, `(public a)`. + Start, + /// After the binding of a parameter that has a type annotation or is optional: + /// `(a: T)`, `(a?)`, `({ a }: T)`. + Binding { start: u32, pattern: BindingPattern<'a>, optional: bool }, + /// After the rest parameter of an async arrow function: `async (...a: T[])`. + Rest(ArenaBox<'a, FormalParameterRest<'a>>), +} + +/// How a cover list ended. Its `)` has been consumed. +pub(super) enum CoverList<'a> { + /// Nothing between the parentheses decided what the elements are. + /// `end` is the end of the last token before `)`. + Undecided { trailing_comma: Option, end: u32 }, + /// The list could only be the parameters of an arrow function. + Parameters(ArenaBox<'a, FormalParameters<'a>>), +} + +/// An undecided cover list, whose elements are in [`ParserState::cover_elements`]. +/// +/// [`ParserState::cover_elements`]: crate::state::ParserState::cover_elements +#[derive(Clone, Copy)] +pub(super) struct Cover { + /// Start of the expression: `(`, or `async`. + pub(super) start: u32, + /// Start of `(`. + pub(super) lparen: u32, + /// Length of `ParserState::cover_elements` before this list. + pub(super) base: usize, + /// Length of `ParserState::cover_parenthesized` before this list. + pub(super) parenthesized_base: usize, + /// Start of the `,` before `)`, if there is one. + pub(super) trailing_comma: Option, + pub(super) is_async: bool, +} + +impl Cover { + pub(super) fn new( + start: u32, + lparen: u32, + base: usize, + parenthesized_base: usize, + is_async: bool, + ) -> Self { + Self { start, lparen, base, parenthesized_base, trailing_comma: None, is_async } + } +} + +pub(super) type CoverCheck<'a> = Result<(), ParserDiagnostic<'a>>; + +impl<'a, C: Config> ParserImpl<'a, C> { + /// Parse the elements of a cover list up to and including its `)`. + /// + /// `CoverParenthesizedExpressionAndArrowParameterList`[Yield, Await] : + /// ( `Expression`[+In, ?Yield, ?Await] ) + /// ( `Expression`[+In, ?Yield, ?Await] , ) + /// ( ) + /// ( ... `BindingIdentifier`[?Yield, ?Await] ) + /// ( ... `BindingPattern`[?Yield, ?Await] ) + /// ( `Expression`[+In, ?Yield, ?Await] , ... `BindingIdentifier`[?Yield, ?Await] ) + /// ( `Expression`[+In, ?Yield, ?Await] , ... `BindingPattern`[?Yield, ?Await] ) + /// + /// The elements are pushed to `ParserState::cover_elements`, unless the list turns out to + /// be a parameter list, which is then completed. + /// + /// If `first_parsed`, the first element is already on the stack and the cursor is after it. + /// If `first_identifier`, the identifier that starts the first element has been consumed. + pub(super) fn parse_cover_list( + &mut self, + lparen: u32, + base: usize, + is_async: bool, + first_parsed: bool, + mut first_identifier: Option>, + ) -> CoverList<'a> { + let ctx = self.ctx; + self.ctx = ctx.and_in(true).and_decorator(false); + self.state.cover_depth += 1; + + let mut trailing_comma = None; + let parameter = 'list: { + if !first_parsed && first_identifier.is_none() && self.at(Kind::RParen) { + break 'list None; + } + let mut is_first = !first_parsed; + let mut parse_element = !first_parsed; + loop { + if parse_element { + let parameter = if let Some(identifier) = first_identifier.take() { + self.parse_cover_identifier_element_rest(identifier) + } else if self.at(Kind::Ident) { + let identifier = self.parse_cover_identifier(); + self.parse_cover_identifier_element_rest(identifier) + } else { + self.parse_cover_element(is_async, is_first) + }; + if parameter.is_some() { + break 'list parameter; + } + } + parse_element = true; + if !self.at(Kind::Comma) || self.fatal_error.is_some() { + break 'list None; + } + let comma = self.cur_start(); + self.bump_any(); // `,` + if self.at(Kind::RParen) { + trailing_comma = Some(comma); + break 'list None; + } + is_first = false; + } + }; + + self.state.cover_depth -= 1; + let list = if let Some(parameter) = parameter { + CoverList::Parameters(self.parse_cover_parameters(lparen, base, parameter)) + } else { + let end = self.prev_token_end; + if self.at(Kind::RParen) { + self.bump_any(); + } else { + self.expect_cover_closing(lparen); + } + CoverList::Undecided { trailing_comma, end } + }; + self.ctx = ctx; + list + } + + #[cold] + #[inline(never)] + fn expect_cover_closing(&mut self, lparen: u32) { + let error = diagnostics::expect_closing_or_separator( + Kind::RParen.to_str(), + Kind::Comma.to_str(), + self.cur_kind().to_str(), + self.cur_token().span(), + Span::sized(lparen, 1), + ); + self.set_fatal_error(error); + // Like `expect`, leave the cursor at the end of the file after a fatal error. + self.bump_any(); + } + + /// Parse a cover list element that starts with an identifier which is not a keyword in + /// any context. + /// + /// The token after the identifier usually decides what the element is, without looking + /// ahead: `,` and `)` end it, `=` starts an initializer or assignment, `=>` makes it the + /// parameter of a nested arrow function, and in TypeScript `:` and `?` can only follow + /// a parameter. + #[expect(clippy::inline_always)] + #[inline(always)] + fn parse_cover_identifier_element_rest( + &mut self, + identifier: CoverIdentifier<'a>, + ) -> Option> { + let CoverIdentifier { span, name, pure_comments, no_side_effects_comments } = identifier; + let start = span.start; + + let element = match self.cur_kind() { + Kind::Comma | Kind::RParen => CoverElement::Identifier { span, name }, + Kind::Eq => { + self.bump_any(); // `=` + let initializer = self.parse_assignment_expression_or_higher(); + let end = self.prev_token_end; + CoverElement::IdentifierWithInitializer { span, name, end, initializer } + } + Kind::Arrow => { + let binding = BindingIdentifier::new(span, name, self); + let mut arrow = self.parse_simple_arrow_function_expression( + start, binding, /* async */ false, + /* allow_return_type_in_arrow_function */ true, + ); + if let Some(comments) = no_side_effects_comments + && let Expression::ArrowFunctionExpression(function) = &mut arrow + { + function.pure = true; + self.lexer.trivia_builder.mark_no_side_effects_comments_applied(comments); + } + CoverElement::Expression(arrow) + } + Kind::Colon if self.is_ts => { + let pattern = BindingPattern::new_binding_identifier(span, name, self); + return Some(CoverParameter::Binding { start, pattern, optional: false }); + } + Kind::Question if self.is_ts => { + let question_span = self.cur_token().span(); + self.bump_any(); // `?` + // `(a?: T)`, `(a?, b)`, `(a?)`, `(a? = b)`. A conditional expression cannot + // continue with any of these tokens. + if matches!(self.cur_kind(), Kind::Colon | Kind::Comma | Kind::RParen | Kind::Eq) { + let pattern = BindingPattern::new_binding_identifier(span, name, self); + return Some(CoverParameter::Binding { start, pattern, optional: true }); + } + let test = Expression::new_identifier(span, name, self); + CoverElement::Expression(self.parse_cover_conditional_expression( + start, + test, + question_span, + )) + } + _ => { + let primary = Expression::new_identifier(span, name, self); + CoverElement::Expression(self.parse_assignment_expression_rest( + start, + primary, + pure_comments, + )) + } + }; + self.state.cover_elements.push(element); + None + } + + /// Consume the current identifier, which is not a keyword in any context. + #[expect(clippy::inline_always)] + #[inline(always)] + pub(super) fn parse_cover_identifier(&mut self) -> CoverIdentifier<'a> { + // Read the annotations before consuming the identifier, which resets them. + let pure_comments = self.lexer.trivia_builder.previous_token_pure_comments(); + let no_side_effects_comments = + self.lexer.trivia_builder.previous_token_no_side_effects_comments(); + let (span, name) = self.parse_identifier_kind(Kind::Ident); + CoverIdentifier { span, name, pure_comments, no_side_effects_comments } + } + + /// Parse the rest of the expression that starts with `identifier`, which cannot be + /// a `BindingElement`: `(a.b)`, `(a + b)`, `(a(b), c)`. + pub(super) fn parse_cover_identifier_expression( + &mut self, + identifier: CoverIdentifier<'a>, + ) -> Expression<'a> { + let primary = Expression::new_identifier(identifier.span, identifier.name, self); + self.parse_assignment_expression_rest( + identifier.span.start, + primary, + identifier.pure_comments, + ) + } + + #[inline(never)] + fn parse_cover_conditional_expression( + &mut self, + start: u32, + test: Expression<'a>, + question_span: Span, + ) -> Expression<'a> { + self.parse_conditional_expression_after_question( + start, + test, + question_span, + /* allow_return_type_in_arrow_function */ true, + ) + } + + /// Parse a cover list element that does not start with a plain identifier. + fn parse_cover_element( + &mut self, + is_async: bool, + is_first: bool, + ) -> Option> { + let kind = self.cur_kind(); + match kind { + Kind::LCurly | Kind::LBrack => return self.parse_cover_literal_element(), + Kind::Dot3 => return self.parse_cover_spread_element(is_async), + // `async`, `await` and `yield` start expressions that the code below does not + // parse, but they can also name a parameter. Only an optional parameter has to + // be recognized up front: `(async?: T) => …`. + Kind::Async | Kind::Await | Kind::Yield => { + if self.is_ts + && self.lexer.peek_token().kind() == Kind::Question + && self.lookahead(|p| { + p.bump_any(); // the identifier + p.bump_any(); // `?` + matches!(p.cur_kind(), Kind::Colon | Kind::Comma | Kind::RParen | Kind::Eq) + }) + { + let start = self.cur_start(); + let ident = self.parse_binding_identifier(); + self.bump_any(); // `?` + let pattern = BindingPattern::BindingIdentifier(self.alloc(ident)); + return Some(CoverParameter::Binding { start, pattern, optional: true }); + } + } + _ => { + // `(public a) => …`. Arrow function parameters cannot have modifiers, but two + // adjacent identifiers are not an expression either, and the modifier is what + // an error should be about. `as` and `satisfies` are the only identifiers that + // may follow another one in an expression. + if kind.is_modifier_kind() { + let next = self.lexer.peek_token().kind(); + if next.is_binding_identifier() && !matches!(next, Kind::As | Kind::Satisfies) { + return Some(CoverParameter::Start); + } + } + if kind.is_identifier() { + let identifier = self.parse_cover_identifier(); + return self.parse_cover_identifier_element_rest(identifier); + } + } + } + + let start = self.cur_start(); + let expression = self.parse_assignment_expression_or_higher(); + if self.is_ts && self.at(Kind::Colon) { + match &expression { + // `(this: T) => …`. Arrow functions cannot have a `this` parameter. + Expression::ThisExpression(this) if is_first && this.span.start == start => { + self.parse_ts_type_annotation(); + self.error(diagnostics::ts_arrow_function_this_parameter(self.end_span(start))); + if !self.at(Kind::RParen) { + self.expect(Kind::Comma); + } + return Some(CoverParameter::Start); + } + // `(async: T) => …` + Expression::Identifier(ident) if ident.span.start == start => { + let pattern = + BindingPattern::new_binding_identifier(ident.span, ident.name, self); + return Some(CoverParameter::Binding { start, pattern, optional: false }); + } + _ => {} + } + } + self.state.cover_elements.push(CoverElement::Expression(expression)); + None + } + + /// Parse a cover list element that starts with an object or array literal, which is + /// a destructuring parameter if a type annotation or `?` follows it. + fn parse_cover_literal_element(&mut self) -> Option> { + let pure_comments = self.lexer.trivia_builder.previous_token_pure_comments(); + let start = self.cur_start(); + let literal = if self.at(Kind::LCurly) { + Expression::ObjectExpression(self.parse_object_expression()) + } else { + self.parse_array_expression() + }; + + let expression = match self.cur_kind() { + Kind::Comma | Kind::RParen => literal, + Kind::Eq => { + // `({ a } = b)`. The literal is only refined once it is known whether this is + // a parameter or an assignment, instead of to an assignment target first. + self.bump_any(); // `=` + let initializer = self.parse_assignment_expression_or_higher(); + let end = self.prev_token_end; + let element = CoverElement::LiteralWithInitializer { literal, end, initializer }; + self.state.cover_elements.push(element); + return None; + } + Kind::Colon if self.is_ts => { + // `({ a }: T) => …` + let pattern = self.cover_literal_to_binding_pattern(literal); + return Some(CoverParameter::Binding { start, pattern, optional: false }); + } + Kind::Question if self.is_ts => { + let question_span = self.cur_token().span(); + self.bump_any(); // `?` + if matches!(self.cur_kind(), Kind::Colon | Kind::Comma | Kind::RParen | Kind::Eq) { + // `({ a }?: T) => …` + let pattern = self.cover_literal_to_binding_pattern(literal); + return Some(CoverParameter::Binding { start, pattern, optional: true }); + } + self.parse_cover_conditional_expression(start, literal, question_span) + } + _ => self.parse_assignment_expression_rest(start, literal, pure_comments), + }; + self.state.cover_elements.push(CoverElement::Expression(expression)); + None + } + + fn cover_literal_to_binding_pattern(&mut self, literal: Expression<'a>) -> BindingPattern<'a> { + if let Err(error) = self.check_cover_binding(&literal) { + return self.fatal_error(error); + } + self.cover_expression_to_binding_pattern(literal) + } + + /// Parse a cover list element that starts with `...`. + fn parse_cover_spread_element(&mut self, is_async: bool) -> Option> { + if !is_async { + // A parenthesized expression has no spread elements: this is a rest parameter. + return Some(CoverParameter::Start); + } + if self.is_ts && self.lookahead(Self::is_optional_rest_parameter) { + // `async (...a?: T[]) => …` is an error, reported on the rest parameter. + return Some(CoverParameter::Start); + } + let spread = self.parse_spread_element(); + if self.is_ts && self.at(Kind::Colon) && self.fatal_error.is_none() { + // `async (...a: T[]) => …` + return Some(CoverParameter::Rest(self.cover_spread_to_parameter_rest(spread, true))); + } + self.state.cover_elements.push(CoverElement::Spread(spread)); + None + } + + /// Whether the tokens from `...` on are `...a?` followed by `:`, `,` or `)`. + fn is_optional_rest_parameter(&mut self) -> bool { + self.bump_any(); // `...` + if !self.cur_kind().is_binding_identifier() { + return false; + } + self.bump_any(); + if !self.at(Kind::Question) { + return false; + } + self.bump_any(); + matches!(self.cur_kind(), Kind::Colon | Kind::Comma | Kind::RParen) + } + + /// Complete a cover list as the parameters of an arrow function, up to and including `)`. + /// + /// The elements before `parameter` are converted to parameters. + fn parse_cover_parameters( + &mut self, + lparen: u32, + base: usize, + parameter: CoverParameter<'a>, + ) -> ArenaBox<'a, FormalParameters<'a>> { + let (mut current, rest, at_parameter_start) = match parameter { + CoverParameter::Start => (None, None, true), + CoverParameter::Binding { start, pattern, optional } => { + (Some(self.parse_cover_parameter_rest(start, pattern, optional)), None, false) + } + CoverParameter::Rest(rest) => (None, Some(rest), false), + }; + + // Nothing is parsed while the elements are converted, so they stay where they are. + let mut index = base; + let (items, rest) = self.parse_formal_parameters_list_after::( + FunctionKind::Expression, + Span::sized(lparen, 1), + at_parameter_start, + rest, + |p| { + while index < p.state.cover_elements.len() { + let element = p.take_cover_element(index); + let is_first = index == base; + index += 1; + if let Some(param) = p.cover_element_to_parameter(element, is_first) { + return Some(param); + } + } + current.take() + }, + ); + self.state.cover_elements.truncate(base); + self.expect(Kind::RParen); + FormalParameters::boxed( + self.end_span(lparen), + FormalParameterKind::ArrowFormalParameters, + items, + rest, + self, + ) + } + + /// Parse the type annotation and initializer of a parameter whose binding has been parsed. + fn parse_cover_parameter_rest( + &mut self, + start: u32, + pattern: BindingPattern<'a>, + optional: bool, + ) -> FormalParameter<'a> { + let type_annotation = self.parse_ts_type_annotation(); + let initializer = if self.eat(Kind::Eq) { + let initializer = + self.context_add(Context::In, Self::parse_assignment_expression_or_higher); + if optional { + self.error(diagnostics::a_parameter_cannot_have_question_mark_and_initializer( + pattern.span(), + )); + } + Some(ArenaBox::new_in(initializer, self)) + } else { + None + }; + FormalParameter::new( + self.end_span(start), + [], + pattern, + type_annotation, + initializer, + optional, + None, + false, + false, + self, + ) + } + + /// Drop the elements of a cover list after a fatal error. + #[cold] + #[inline(never)] + pub(super) fn abandon_cover(&mut self, cover: Cover) -> Expression<'a> { + self.state.cover_elements.truncate(cover.base); + self.state.cover_parenthesized.truncate(cover.parenthesized_base); + Dummy::dummy(self.allocator()) + } + + /// Take an element of a cover list to convert it. Nothing is parsed during a conversion, + /// so the elements stay on the stack until the list is truncated. + #[inline] + fn take_cover_element(&mut self, index: usize) -> CoverElement<'a> { + let placeholder = CoverElement::Identifier { span: SPAN, name: Ident::empty() }; + mem::replace(&mut self.state.cover_elements[index], placeholder) + } + + /// Whether the expression that starts at `start` was directly inside parentheses. + #[inline] + pub(super) fn is_cover_parenthesized(&self, start: u32) -> bool { + // Entries below this list's are before its `(`, so they cannot match. + let parenthesized = &self.state.cover_parenthesized; + !parenthesized.is_empty() && parenthesized.binary_search(&start).is_ok() + } + + /// Refine the elements of a cover list to `ArrowFormalParameters`. + #[expect(clippy::inline_always)] + #[inline(always)] + pub(super) fn cover_elements_to_parameters( + &mut self, + cover: Cover, + span: Span, + ) -> ArenaBox<'a, FormalParameters<'a>> { + // `() => …` and `(a) => …` are the common cases. Keep them out of the general + // conversion, which needs a much larger stack frame. + let (items, rest) = match &self.state.cover_elements[cover.base..] { + [] => (ArenaVec::new_in(self), None), + &[CoverElement::Identifier { span, name }] => { + self.state.cover_elements.truncate(cover.base); + let pattern = BindingPattern::new_binding_identifier(span, name, self); + let param = FormalParameter::new_plain(span, pattern, self); + (ArenaVec::from_value_in(param, self), None) + } + _ => self.cover_elements_to_parameter_list(cover), + }; + self.state.cover_parenthesized.truncate(cover.parenthesized_base); + FormalParameters::boxed(span, FormalParameterKind::ArrowFormalParameters, items, rest, self) + } + + /// Refine the elements of a cover list that is not empty to parameters. + #[inline(never)] + fn cover_elements_to_parameter_list( + &mut self, + cover: Cover, + ) -> (ArenaVec<'a, FormalParameter<'a>>, Option>>) { + let mut rest = None; + if matches!(self.state.cover_elements.last(), Some(CoverElement::Spread(_))) + && let Some(CoverElement::Spread(spread)) = self.state.cover_elements.pop() + { + rest = Some(self.cover_spread_to_parameter_rest(spread, false)); + if let Some(comma) = cover.trailing_comma + && !self.ctx.has_ambient() + { + self.error(diagnostics::rest_element_trailing_comma(Span::sized(comma, 1))); + } + } + + let end = self.state.cover_elements.len(); + let mut items = ArenaVec::with_capacity_in(end - cover.base, self); + for index in cover.base..end { + // `(a, b) => …` is the common case. + if let CoverElement::Identifier { span, name } = self.state.cover_elements[index] { + let pattern = BindingPattern::new_binding_identifier(span, name, self); + items.push(FormalParameter::new_plain(span, pattern, self)); + continue; + } + let element = self.take_cover_element(index); + if let Some(param) = self.cover_element_to_parameter(element, index == cover.base) { + items.push(param); + } + } + self.state.cover_elements.truncate(cover.base); + (items, rest) + } + + /// Refine an element of a cover list to a parameter. + /// + /// Returns `None` for a TypeScript `this` parameter, which arrow functions cannot have. + fn cover_element_to_parameter( + &mut self, + element: CoverElement<'a>, + is_first: bool, + ) -> Option> { + let param = match element { + CoverElement::Identifier { span, name } => { + let pattern = BindingPattern::new_binding_identifier(span, name, self); + FormalParameter::new_plain(span, pattern, self) + } + CoverElement::IdentifierWithInitializer { span, name, end, initializer } => { + let pattern = BindingPattern::new_binding_identifier(span, name, self); + self.cover_parameter_with_initializer( + Span::new(span.start, end), + pattern, + initializer, + ) + } + CoverElement::LiteralWithInitializer { literal, end, initializer } => { + if let Err(error) = self.check_cover_binding(&literal) { + return Some(self.fatal_error(error)); + } + let span = Span::new(literal.span().start, end); + let pattern = self.cover_expression_to_binding_pattern(literal); + self.cover_parameter_with_initializer(span, pattern, initializer) + } + CoverElement::Expression(expression) => { + if let Err(error) = self.check_cover_binding_element(&expression) { + if self.is_ts + && is_first + && let Expression::ThisExpression(this) = &expression + { + // `(this) => …` + self.error(diagnostics::ts_arrow_function_this_parameter(this.span)); + return None; + } + return Some(self.fatal_error(error)); + } + match expression { + Expression::AssignmentExpression(assignment) => { + let AssignmentExpression { span, left, right, .. } = assignment.unbox(); + let pattern = self.cover_assignment_target_to_binding_pattern(left); + self.cover_parameter_with_initializer(span, pattern, right) + } + expression => { + let span = expression.span(); + let pattern = self.cover_expression_to_binding_pattern(expression); + FormalParameter::new_plain(span, pattern, self) + } + } + } + CoverElement::Spread(spread) => { + return Some(self.fatal_error(diagnostics::rest_parameter_last(spread.span))); + } + }; + Some(param) + } + + fn cover_parameter_with_initializer( + &self, + span: Span, + pattern: BindingPattern<'a>, + initializer: Expression<'a>, + ) -> FormalParameter<'a> { + let initializer = Some(ArenaBox::new_in(initializer, self)); + FormalParameter::new(span, [], pattern, None, initializer, false, None, false, false, self) + } + + /// Refine `...a` in the arguments of `async(…)` to the rest parameter of an arrow function, + /// and parse its type annotation if `typed`. + fn cover_spread_to_parameter_rest( + &mut self, + spread: ArenaBox<'a, SpreadElement<'a>>, + typed: bool, + ) -> ArenaBox<'a, FormalParameterRest<'a>> { + let SpreadElement { span, argument, .. } = spread.unbox(); + if let Err(error) = self.check_cover_binding_element(&argument) { + return self.fatal_error(error); + } + let argument = self.cover_expression_to_binding_element(argument); + if let BindingPattern::AssignmentPattern(pattern) = &argument { + self.error(diagnostics::a_rest_parameter_cannot_have_an_initializer(pattern.span)); + } + let rest = BindingRestElement::new(span, argument, self); + let type_annotation = if typed { self.parse_ts_type_annotation() } else { None }; + let span = if typed { self.end_span(span.start) } else { span }; + FormalParameterRest::boxed(span, [], rest, type_annotation, self) + } + + /// Refine the elements of a cover list to a parenthesized expression. + /// + /// `first_start` is the start of the first token after `(`, and `end` is the end of the + /// last token before `)`. + #[inline] + pub(super) fn cover_elements_to_parenthesized_expression( + &mut self, + cover: Cover, + first_start: u32, + end: u32, + no_side_effects_comments: Option<(u32, NonZeroU32)>, + ) -> Expression<'a> { + let len = self.state.cover_elements.len() - cover.base; + let expression = match self.state.cover_elements.pop() { + // `(a)` and `(a + b)` are the common cases. Keep them out of the general + // conversion, which needs a much larger stack frame. + Some(element) if len == 1 && cover.trailing_comma.is_none() => match element { + CoverElement::Identifier { span, name } => { + Expression::new_identifier(span, name, self) + } + CoverElement::Expression(expression) => expression, + element => self.cover_element_to_expression(element), + }, + Some(element) if len > 1 && cover.trailing_comma.is_none() => { + self.state.cover_elements.push(element); + self.cover_elements_to_sequence_expression(cover, Span::new(first_start, end)) + } + element => { + if let Some(element) = element { + self.state.cover_elements.push(element); + } + return self.invalid_parenthesized_expression(cover); + } + }; + + self.finish_parenthesized_expression( + cover.start, + cover.parenthesized_base, + expression, + no_side_effects_comments, + ) + } + + /// Complete `( expression )`, whose `)` has been consumed. + #[inline] + pub(super) fn finish_parenthesized_expression( + &mut self, + start: u32, + parenthesized_base: usize, + mut expression: Expression<'a>, + no_side_effects_comments: Option<(u32, NonZeroU32)>, + ) -> Expression<'a> { + match &mut expression { + Expression::ArrowFunctionExpression(arrow_expr) => { + arrow_expr.pife = true; + if let Some(comments) = no_side_effects_comments { + arrow_expr.pure = true; + self.lexer.trivia_builder.mark_no_side_effects_comments_applied(comments); + } + } + Expression::FunctionExpression(func_expr) => { + func_expr.pife = true; + if let Some(comments) = no_side_effects_comments { + func_expr.pure = true; + self.lexer.trivia_builder.mark_no_side_effects_comments_applied(comments); + } + } + _ => {} + } + + // An enclosing cover list may become a binding pattern, which cannot contain + // parentheses. What is inside these parentheses no longer matters to it. + // Record where the innermost expression starts, which is what an enclosing check + // finds: inner parentheses leave no node without `preserve_parens`, and an assignment + // target drops them in `((a)) = b`. + self.state.cover_parenthesized.truncate(parenthesized_base); + if self.state.cover_depth > 0 { + self.state.cover_parenthesized.push(expression.without_parentheses().span().start); + } + + if self.options.preserve_parens { + Expression::new_parenthesized_expression(self.end_span(start), expression, self) + } else { + expression + } + } + + /// Refine the elements of a cover list to the sequence expression `a, b`. + #[inline(never)] + fn cover_elements_to_sequence_expression( + &mut self, + cover: Cover, + span: Span, + ) -> Expression<'a> { + let end = self.state.cover_elements.len(); + let mut expressions = ArenaVec::with_capacity_in(end - cover.base, self); + for index in cover.base..end { + if let CoverElement::Identifier { span, name } = self.state.cover_elements[index] { + expressions.push(Expression::new_identifier(span, name, self)); + continue; + } + expressions.push(match self.take_cover_element(index) { + CoverElement::Expression(expression) => expression, + element => self.cover_element_to_expression(element), + }); + } + self.state.cover_elements.truncate(cover.base); + Expression::new_sequence_expression(span, expressions, self) + } + + /// Report `()` and `(a,)`, which are only valid as arrow function parameters. + #[cold] + #[inline(never)] + fn invalid_parenthesized_expression(&mut self, cover: Cover) -> Expression<'a> { + let is_empty = self.state.cover_elements.len() == cover.base; + self.state.cover_elements.truncate(cover.base); + self.state.cover_parenthesized.truncate(cover.parenthesized_base); + if let Some(comma) = cover.trailing_comma { + let error = diagnostics::unexpected_trailing_comma( + "Parenthesized expressions", + Span::sized(comma, 1), + ); + return self.fatal_error(error); + } + debug_assert!(is_empty); + if self.at(Kind::LCurly) { + // `() {}`: most likely an arrow function that is missing its `=>`. + self.expect(Kind::Arrow); + return Dummy::dummy(self.allocator()); + } + self.fatal_error(diagnostics::empty_parenthesized_expression(self.end_span(cover.start))) + } + + /// Refine the elements of a cover list to the arguments of a call to `async`. + pub(super) fn cover_elements_to_call_expression( + &mut self, + cover: Cover, + callee: Expression<'a>, + ) -> Expression<'a> { + let end = self.state.cover_elements.len(); + let mut arguments = ArenaVec::with_capacity_in(end - cover.base, self); + for index in cover.base..end { + arguments.push(match self.take_cover_element(index) { + CoverElement::Spread(spread) => Argument::SpreadElement(spread), + element => Argument::from(self.cover_element_to_expression(element)), + }); + } + self.state.cover_elements.truncate(cover.base); + self.state.cover_parenthesized.truncate(cover.parenthesized_base); + Expression::new_call_expression( + self.end_span(cover.start), + callee, + None::>>, + arguments, + false, + self, + ) + } + + /// Refine an element of a cover list to an expression. + #[inline(never)] + fn cover_element_to_expression(&mut self, element: CoverElement<'a>) -> Expression<'a> { + match element { + CoverElement::Identifier { span, name } => Expression::new_identifier(span, name, self), + CoverElement::IdentifierWithInitializer { span, name, end, initializer } => { + let left = AssignmentTarget::AssignmentTargetIdentifier( + IdentifierReference::boxed(span, name, self), + ); + Expression::new_assignment_expression( + Span::new(span.start, end), + AssignmentOperator::Assign, + left, + initializer, + self, + ) + } + CoverElement::LiteralWithInitializer { literal, end, initializer } => { + let span = Span::new(literal.span().start, end); + let left = AssignmentTarget::cover(literal, self); + Expression::new_assignment_expression( + span, + AssignmentOperator::Assign, + left, + initializer, + self, + ) + } + CoverElement::Expression(expression) => expression, + // Only the arguments of `async(…)` have spread elements, and they keep them. + CoverElement::Spread(spread) => { + self.fatal_error(diagnostics::spread_last_element(spread.span)) + } + } + } +} diff --git a/vendor/oxc_parser/src/js/declaration.rs b/vendor/oxc_parser/src/js/declaration.rs index 58901dab9..a670c694f 100644 --- a/vendor/oxc_parser/src/js/declaration.rs +++ b/vendor/oxc_parser/src/js/declaration.rs @@ -8,19 +8,19 @@ use crate::{ParserConfig as Config, ParserImpl, StatementContext, diagnostics, l impl<'a, C: Config> ParserImpl<'a, C> { pub(crate) fn parse_let(&mut self, stmt_ctx: StatementContext) -> Statement<'a> { let start = self.cur_start(); - - let next = self.lexer.peek_token(); - let peeked = next.kind(); + let is_single_statement = stmt_ctx.is_single_statement(); // `let [` cannot start an expression statement, even in a single-statement // position. Otherwise, a declaration needs a binding after `let`. - if peeked == Kind::LBrack - || (!stmt_ctx.is_single_statement() - && (peeked == Kind::LCurly - || peeked.is_binding_identifier() - || (!next.is_on_new_line() && peeked.is_after_let()))) - { - self.bump_any(); // bump `let` + let is_declaration = self.eat_if_next(|next| { + let kind = next.kind(); + kind == Kind::LBrack + || (!is_single_statement + && (kind == Kind::LCurly + || kind.is_binding_identifier() + || (!next.is_on_new_line() && kind.is_after_let()))) + }); + if is_declaration { return self.parse_variable_statement(start, VariableDeclarationKind::Let, stmt_ctx); } @@ -68,11 +68,7 @@ impl<'a, C: Config> ParserImpl<'a, C> { decl_parent: VariableDeclarationParent, declare: bool, ) -> ArenaBox<'a, VariableDeclaration<'a>> { - let first = self.parse_variable_declarator(decl_parent, kind); - let mut declarations = ArenaVec::from_value_in(first, self); - while self.eat(Kind::Comma) { - declarations.push(self.parse_variable_declarator(decl_parent, kind)); - } + let declarations = self.parse_variable_declarators(decl_parent, kind); if matches!(decl_parent, VariableDeclarationParent::Statement) { self.asi(); @@ -80,6 +76,27 @@ impl<'a, C: Config> ParserImpl<'a, C> { VariableDeclaration::boxed(self.end_span(start), kind, declarations, declare, self) } + fn parse_variable_declarators( + &mut self, + decl_parent: VariableDeclarationParent, + kind: VariableDeclarationKind, + ) -> ArenaVec<'a, VariableDeclarator<'a>> { + let mut first = true; + self.collect_list(|p| { + if !first && !p.eat(Kind::Comma) { + return None; + } + first = false; + let declaration = p.parse_variable_declarator(decl_parent, kind); + if kind.is_using() && !declaration.id.is_binding_identifier() { + p.error(diagnostics::invalid_identifier_in_using_declaration( + declaration.id.span(), + )); + } + Some(declaration) + }) + } + fn parse_variable_declarator( &mut self, decl_parent: VariableDeclarationParent, @@ -197,26 +214,12 @@ impl<'a, C: Config> ParserImpl<'a, C> { } // BindingList[?In, ?Yield, ?Await, ~Pattern] - let mut declarations = ArenaVec::new_in(self); - loop { - let decl_parent = if matches!(statement_ctx, StatementContext::For) { - VariableDeclarationParent::For - } else { - VariableDeclarationParent::Statement - }; - let declaration = self.parse_variable_declarator(decl_parent, kind); - - if !matches!(declaration.id, BindingPattern::BindingIdentifier(_)) { - self.error(diagnostics::invalid_identifier_in_using_declaration( - declaration.id.span(), - )); - } - - declarations.push(declaration); - if !self.eat(Kind::Comma) { - break; - } - } + let decl_parent = if matches!(statement_ctx, StatementContext::For) { + VariableDeclarationParent::For + } else { + VariableDeclarationParent::Statement + }; + let declarations = self.parse_variable_declarators(decl_parent, kind); VariableDeclaration::boxed(self.end_span(start), kind, declarations, false, self) } diff --git a/vendor/oxc_parser/src/js/expression.rs b/vendor/oxc_parser/src/js/expression.rs index 8214c21c4..f0d5f7715 100644 --- a/vendor/oxc_parser/src/js/expression.rs +++ b/vendor/oxc_parser/src/js/expression.rs @@ -3,14 +3,12 @@ use std::num::NonZeroU32; use cow_utils::CowUtils; use oxc_allocator::{ArenaBox, ArenaVec, GetAllocator, ReplaceWith}; use oxc_ast::ast::*; +use oxc_data_structures::buffered_vec::BufferedVec; #[cfg(feature = "regular_expression")] use oxc_regular_expression::ast::Pattern; use oxc_span::{GetSpan, Span}; -use oxc_str::{Ident, Str}; -use oxc_syntax::{ - number::{BigintBase, NumberBase}, - precedence::Precedence, -}; +use oxc_str::{Ident, JSStr, Str}; +use oxc_syntax::precedence::Precedence; use super::{ grammar::CoverGrammar, @@ -43,6 +41,28 @@ fn is_import_expression_or_member_access_on_import_expression(callee: &Expressio } } +/// Whether `expr`, parsed from `start`, is an instantiation without its own parentheses: +/// under `preserve_parens: false` a parenthesized one (`(a)`) starts after its `(`. +fn is_unparenthesized_instantiation(expr: &Expression<'_>, start: u32) -> bool { + matches!(expr, Expression::TSInstantiationExpression(expr) if expr.span.start == start) +} + +/// Splits an unparenthesized instantiation into its expression and type arguments +/// for the enclosing `new` or `extends` (`new A;`, `extends B,`). +/// A parenthesized one stays whole (`new (A)`, `extends (B)`), as in TypeScript. +pub(super) fn split_unparenthesized_instantiation( + expr: Expression<'_>, + start: u32, +) -> (Expression<'_>, Option>>) { + if is_unparenthesized_instantiation(&expr, start) + && let Expression::TSInstantiationExpression(instantiation) = expr + { + let instantiation = instantiation.unbox(); + return (instantiation.expression, Some(instantiation.type_arguments)); + } + (expr, None) +} + impl<'a, C: Config> ParserImpl<'a, C> { pub(crate) fn parse_paren_expression(&mut self) -> Expression<'a> { let opening_span = self.cur_token().span(); @@ -209,6 +229,7 @@ impl<'a, C: Config> ParserImpl<'a, C> { Kind::Await if ctx.has_await() => { self.error(diagnostics::identifier_async("await", span)); } + Kind::Await => self.state.mentions_await = true, // It is a Syntax Error if this production has a [Yield] parameter. Kind::Yield if ctx.has_yield() => { let next_token = self.lexer.peek_token(); @@ -340,15 +361,11 @@ impl<'a, C: Config> ParserImpl<'a, C> { if p.at(Kind::RParen) || p.has_fatal_error() { return (Some(first), None); } - let mut expressions = ArenaVec::with_capacity_in(2, p); - expressions.push(first); - let comma_start = p.parse_delimited_list_rest( - &mut expressions, - Kind::RParen, - Kind::Comma, - opening_span, - Self::parse_assignment_expression_or_higher, - ); + let mut first = Some(first); + let (mut expressions, comma_start) = + p.parse_delimited_list(Kind::RParen, Kind::Comma, opening_span, |p| { + first.take().unwrap_or_else(|| p.parse_assignment_expression_or_higher()) + }); let expression = if expressions.len() == 1 { expressions.remove(0) } else { @@ -457,43 +474,21 @@ impl<'a, C: Config> ParserImpl<'a, C> { self.set_fatal_error(diagnostics::invalid_number(err, span)); 0.0 // Dummy value }); - let base = match kind { - Kind::Decimal => NumberBase::Decimal, - Kind::Float => NumberBase::Float, - Kind::Binary => NumberBase::Binary, - Kind::Octal => NumberBase::Octal, - Kind::Hex => NumberBase::Hex, - Kind::PositiveExponential | Kind::NegativeExponential => { - if value.fract() == 0.0 { - NumberBase::Decimal - } else { - NumberBase::Float - } - } - _ => return self.unexpected(), - }; self.bump_any(); - NumericLiteral::boxed(span, value, Some(Str::from(src)), base, self) + NumericLiteral::boxed(span, value, Some(Str::from(src)), self) } pub(crate) fn parse_literal_bigint(&mut self) -> ArenaBox<'a, BigIntLiteral<'a>> { let token = self.cur_token(); let kind = token.kind(); let has_separator = token.has_separator(); - let (base, number_kind) = match kind { - Kind::DecimalBigInt => (BigintBase::Decimal, Kind::Decimal), - Kind::BinaryBigInt => (BigintBase::Binary, Kind::Binary), - Kind::OctalBigInt => (BigintBase::Octal, Kind::Octal), - Kind::HexBigInt => (BigintBase::Hex, Kind::Hex), - _ => return self.unexpected(), - }; let span = token.span(); let raw = self.cur_src(); let src = raw.strip_suffix('n').unwrap(); - let value = parse_big_int(src, number_kind, has_separator, self.allocator()); + let value = parse_big_int(src, kind, has_separator, self.allocator()); self.bump_any(); - BigIntLiteral::boxed(span, value, Some(Str::from(raw)), base, self) + BigIntLiteral::boxed(span, value, Some(Str::from(raw)), self) } pub(crate) fn parse_literal_regexp(&mut self) -> ArenaBox<'a, RegExpLiteral<'a>> { @@ -567,11 +562,17 @@ impl<'a, C: Config> ParserImpl<'a, C> { #[inline] pub(crate) fn parse_known_literal_string(&mut self) -> StringLiteral<'a> { debug_assert!(self.at(Kind::Str)); - let span = self.cur_token().span(); - let raw = Str::from(self.cur_src()); - let value = self.cur_js_string(); + let token = self.cur_token(); + let span = token.span(); + let raw = self.cur_src(); + // Most strings have no escapes. Their value is the source text between the quotes. + let value = if token.escaped() { + self.cur_js_string() + } else { + JSStr::from(&raw[1..raw.len() - 1]) + }; self.bump_any(); - StringLiteral::new(span, value, Some(raw), self) + StringLiteral::new(span, value, Some(Str::from(raw)), self) } /// Section [Array Expression](https://tc39.es/ecma262/#prod-ArrayLiteral) @@ -629,35 +630,42 @@ impl<'a, C: Config> ParserImpl<'a, C> { (quasis, ArenaVec::new_in(self)) } Kind::TemplateHead => { - let mut expressions = ArenaVec::with_capacity_in(1, self); - let mut quasis = ArenaVec::with_capacity_in(2, self); - - quasis.push(self.parse_template_element(tagged)); + let mut expressions = BufferedVec::<_, 4>::new(ArenaVec::new_in(self)); + let mut first = Some(self.parse_template_element(tagged)); // TemplateHead Expression[+In, ?Yield, ?Await] let expr = self.context_add(Context::In, Self::parse_expr); expressions.push(expr); self.re_lex_template_substitution_tail(); - while self.fatal_error.is_none() { - match self.cur_kind() { + let mut finished = false; + let quasis = self.collect_list(|p| { + if let Some(first) = first.take() { + return Some(first); + } + if finished || p.fatal_error.is_some() { + return None; + } + match p.cur_kind() { Kind::TemplateTail => { - quasis.push(self.parse_template_element(tagged)); - break; + let quasi = p.parse_template_element(tagged); + finished = true; + Some(quasi) } Kind::TemplateMiddle => { - quasis.push(self.parse_template_element(tagged)); + let quasi = p.parse_template_element(tagged); // TemplateMiddle Expression[+In, ?Yield, ?Await] - let expr = self.context_add(Context::In, Self::parse_expr); + let expr = p.context_add(Context::In, Self::parse_expr); expressions.push(expr); - self.re_lex_template_substitution_tail(); + p.re_lex_template_substitution_tail(); + Some(quasi) } _ => { - self.expect(Kind::TemplateTail); - break; + p.expect(Kind::TemplateTail); + None } } - } + }); - (quasis, expressions) + (quasis, expressions.into_vec()) } _ => unreachable!("parse_template_literal"), }; @@ -713,8 +721,13 @@ impl<'a, C: Config> ParserImpl<'a, C> { let cooked = self.cur_template_string(); // TRV normalizes line endings even when an invalid escape makes TV undefined. if raw.contains('\r') { - raw = - Str::from_str_in(&raw.cow_replace("\r\n", "\n").cow_replace('\r', "\n"), self); + raw = if raw.contains('\\') { + Str::from_str_in(&raw.cow_replace("\r\n", "\n").cow_replace('\r', "\n"), self) + } else { + // Without escapes, TV and TRV only normalize line endings, so reuse + // the cooked string instead of allocating the same text twice. + Str::from(cooked.unwrap().as_str().unwrap()) + }; } cooked } else { @@ -823,7 +836,7 @@ impl<'a, C: Config> ParserImpl<'a, C> { #[inline] fn parse_lhs_expression_rest(&mut self, start: u32, primary: Expression<'a>) -> Expression<'a> { let mut in_optional_chain = false; - let member_expression = self.parse_member_expression_rest( + let (member_expression, type_arguments) = self.parse_member_expression_rest( start, primary, &mut in_optional_chain, @@ -833,7 +846,12 @@ impl<'a, C: Config> ParserImpl<'a, C> { // `Arguments` (`(`) or an `OptionalChain` (`?.`); see . // So skip `parse_call_expression_rest` (and its redundant member-rest re-scan) otherwise. let lhs = if matches!(self.cur_kind(), Kind::LParen | Kind::QuestionDot) { - self.parse_call_expression_rest(start, member_expression, &mut in_optional_chain) + self.parse_call_expression_rest( + start, + member_expression, + type_arguments, + &mut in_optional_chain, + ) } else { member_expression }; @@ -915,7 +933,7 @@ impl<'a, C: Config> ParserImpl<'a, C> { lhs: &Expression<'a>, lhs_start: u32, ) { - if matches!(lhs, Expression::TSInstantiationExpression(e) if e.span.start == lhs_start) { + if is_unparenthesized_instantiation(lhs, lhs_start) { self.error( diagnostics::ts_instantiation_expression_cannot_be_followed_by_property_access( self.end_span(lhs_start), @@ -925,6 +943,8 @@ impl<'a, C: Config> ParserImpl<'a, C> { } /// parse rhs of a member expression, starting from lhs + /// + /// Return type arguments followed by `(` separately for the call or `new` expression. #[expect(clippy::inline_always)] #[inline(always)] fn parse_member_expression_rest( @@ -933,11 +953,11 @@ impl<'a, C: Config> ParserImpl<'a, C> { lhs: Expression<'a>, in_optional_chain: &mut bool, allow_optional_chain: bool, - ) -> Expression<'a> { + ) -> (Expression<'a>, Option>>) { let mut lhs = lhs; loop { if self.fatal_error.is_some() { - return lhs; + return (lhs, None); } match self.cur_kind() { @@ -947,14 +967,14 @@ impl<'a, C: Config> ParserImpl<'a, C> { lhs = self.parse_static_member_expression(lhs_start, lhs, false); } Kind::QuestionDot if allow_optional_chain => { - // Fast check to avoid checkpoint/rewind in common cases - let next_kind = self.lexer.peek_token().kind(); - if next_kind == Kind::LBrack - || next_kind.is_identifier_or_keyword() - || next_kind.is_template_start_of_tagged_template() - { - // This is likely a valid optional chain, proceed with normal parsing - self.bump_any(); // consume ?. + // Consume `?.` when a member or a template follows it, which is nearly always. + let is_member = self.eat_if_next(|next| { + let next_kind = next.kind(); + next_kind == Kind::LBrack + || next_kind.is_identifier_or_keyword() + || next_kind.is_template_start_of_tagged_template() + }); + if is_member { *in_optional_chain = true; if self.cur_kind().is_identifier_or_keyword() { // ?.something @@ -966,14 +986,18 @@ impl<'a, C: Config> ParserImpl<'a, C> { lhs = self.parse_computed_member_expression(lhs_start, lhs, true); } else { // ?.template`...` - lhs = - self.parse_tagged_template_rest(lhs_start, lhs, *in_optional_chain); + lhs = self.parse_tagged_template( + lhs_start, + lhs, + *in_optional_chain, + None, + ); } } else { // This is not a valid optional chain pattern, don't consume ?. // Should be a cold branch here, as most real-world optional chaining will look like // `?.something` or `?.[expr]` - return lhs; + return (lhs, None); } } Kind::LBrack if !self.ctx.has_decorator() => { @@ -981,7 +1005,7 @@ impl<'a, C: Config> ParserImpl<'a, C> { lhs = self.parse_computed_member_expression(lhs_start, lhs, false); } kind if kind.is_template_start_of_tagged_template() => { - lhs = self.parse_tagged_template_rest(lhs_start, lhs, *in_optional_chain); + lhs = self.parse_tagged_template(lhs_start, lhs, *in_optional_chain, None); } Kind::Bang if self.is_ts && !self.cur_token().is_on_new_line() => { self.bump_any(); @@ -990,44 +1014,44 @@ impl<'a, C: Config> ParserImpl<'a, C> { } Kind::LAngle | Kind::ShiftLeft if self.is_ts => { if let Some(arguments) = self.parse_type_arguments_in_expression() { - lhs = Expression::new_ts_instantiation_expression( + let instantiation = TSInstantiationExpression::new( self.end_span(lhs_start), lhs, arguments, self, ); + if !self.has_fatal_error() { + if self.at(Kind::LParen) { + return ( + instantiation.expression, + Some(instantiation.type_arguments), + ); + } + if self.cur_kind().is_template_start_of_tagged_template() { + lhs = self.parse_tagged_template( + lhs_start, + instantiation.expression, + *in_optional_chain, + Some(instantiation.type_arguments), + ); + continue; + } + } + lhs = Expression::TSInstantiationExpression(self.alloc(instantiation)); } else { // `re_lex_as_typescript_l_angle` may have overwritten the original `<<` // in the collected token stream with the single `<` it re-lexed. // Rewind restored the parser's current token, so write it back over that `<`. // This is a no-op when tokens are statically disabled (`NoTokensLexerConfig`). self.lexer.rewrite_last_collected_token(self.token); - return lhs; + return (lhs, None); } } - _ => return lhs, + _ => return (lhs, None), } } } - /// Parse the tagged template continuation of a member expression, - /// unwrapping a `TSInstantiationExpression` lhs (`` foo`...` ``) into its type arguments. - fn parse_tagged_template_rest( - &mut self, - lhs_start: u32, - lhs: Expression<'a>, - in_optional_chain: bool, - ) -> Expression<'a> { - let (expr, type_arguments) = - if let Expression::TSInstantiationExpression(instantiation_expr) = lhs { - let expr = instantiation_expr.unbox(); - (expr.expression, Some(expr.type_arguments)) - } else { - (lhs, None) - }; - self.parse_tagged_template(lhs_start, expr, in_optional_chain, type_arguments) - } - /// Section 13.3 `MemberExpression` /// static member `a.b` #[expect(clippy::inline_always)] @@ -1101,7 +1125,7 @@ impl<'a, C: Config> ParserImpl<'a, C> { let rhs_start = self.cur_start(); let is_import = self.at(Kind::Import); // Syntax Error for `new import('mod')` but not `new (import('mod'))`. let mut optional = false; - let mut callee = { + let (callee, type_arguments) = { let lhs = self.parse_primary_expression(); self.parse_member_expression_rest( rhs_start, @@ -1111,12 +1135,11 @@ impl<'a, C: Config> ParserImpl<'a, C> { ) }; - let mut type_arguments = None; - if let Expression::TSInstantiationExpression(instantiation_expr) = callee { - let instantiation_expr = instantiation_expr.unbox(); - type_arguments.replace(instantiation_expr.type_arguments); - callee = instantiation_expr.expression; - } + // `new A;` has no `(` for `parse_member_expression_rest` to split the type arguments at + let (callee, type_arguments) = match type_arguments { + None => split_unparenthesized_instantiation(callee, rhs_start), + type_arguments => (callee, type_arguments), + }; if self.at(Kind::QuestionDot) { let error = diagnostics::invalid_new_optional_chain(self.cur_token().span()); @@ -1164,6 +1187,7 @@ impl<'a, C: Config> ParserImpl<'a, C> { &mut self, lhs_start: u32, lhs: Expression<'a>, + mut type_arguments: Option>>, in_optional_chain: &mut bool, ) -> Expression<'a> { let mut lhs = lhs; @@ -1177,7 +1201,7 @@ impl<'a, C: Config> ParserImpl<'a, C> { let mut rescan_members = false; while self.fatal_error.is_none() { if rescan_members { - lhs = self.parse_member_expression_rest( + (lhs, type_arguments) = self.parse_member_expression_rest( lhs_start, lhs, in_optional_chain, @@ -1192,7 +1216,6 @@ impl<'a, C: Config> ParserImpl<'a, C> { *in_optional_chain = true; } - let mut type_arguments = None; if question_dot { if self.is_ts { if let Some(args) = self.parse_type_arguments_in_expression() { @@ -1206,18 +1229,17 @@ impl<'a, C: Config> ParserImpl<'a, C> { } } if self.cur_kind().is_template_start_of_tagged_template() { - lhs = self.parse_tagged_template(lhs_start, lhs, question_dot, type_arguments); + lhs = self.parse_tagged_template( + lhs_start, + lhs, + question_dot, + type_arguments.take(), + ); continue; } } if type_arguments.is_some() || self.at(Kind::LParen) { - if !question_dot && let Expression::TSInstantiationExpression(expr) = lhs { - let expr = expr.unbox(); - type_arguments.replace(expr.type_arguments); - lhs = expr.expression; - } - lhs = self.parse_call_arguments(lhs_start, lhs, question_dot, type_arguments.take()); continue; @@ -1521,16 +1543,16 @@ impl<'a, C: Config> ParserImpl<'a, C> { } Expression::new_ts_satisfies_expression(span, lhs, type_annotation, self) }; - // When we have `a ## b as T` or `a ## b satisfies T`, where `##` is some binary - // operator, stop parsing on any following operator with higher precedence than `##` - // because continuing would make it impossible to erase the `as` or `satisfies` - // without changing the meaning of the expression. + // Assertions must be erasable without changing how the surrounding operators bind. // See . - if let Some(last_precedence) = last_operand_precedence - && let Some(next_precedence) = kind_to_precedence(self.re_lex_right_angle()) - && next_precedence > last_precedence - { - break; + if let Some(last_precedence) = last_operand_precedence { + let next_kind = self.re_lex_right_angle(); + if let Some(next_precedence) = kind_to_precedence(next_kind) + && (next_precedence > last_precedence + || (next_kind == Kind::Star2 && next_precedence == last_precedence)) + { + break; + } } continue; } @@ -1563,18 +1585,26 @@ impl<'a, C: Config> ParserImpl<'a, C> { let span = self.end_span(lhs_start); let op = map_binary_operator(kind); if op == BinaryOperator::Exponential && !lhs_parenthesized { - let diagnostic = match &lhs { + let mut operand = &lhs; + loop { + operand = match operand { + Expression::TSAsExpression(expr) => &expr.expression, + Expression::TSSatisfiesExpression(expr) => &expr.expression, + _ => break, + }; + } + let diagnostic = match operand { Expression::AwaitExpression(_) => Some( - diagnostics::unary_exponentiation_left_operand("await", lhs.span()), + diagnostics::unary_exponentiation_left_operand("await", operand.span()), ), Expression::UnaryExpression(unary) => { Some(diagnostics::unary_exponentiation_left_operand( unary.operator.as_str(), - lhs.span(), + operand.span(), )) } Expression::TSTypeAssertion(_) => Some( - diagnostics::type_assertion_exponentiation_left_operand(lhs.span()), + diagnostics::type_assertion_exponentiation_left_operand(operand.span()), ), _ => None, }; @@ -1606,6 +1636,24 @@ impl<'a, C: Config> ParserImpl<'a, C> { if !self.eat(Kind::Question) { return lhs; } + self.parse_conditional_expression_after_question( + lhs_start, + lhs, + question_span, + allow_return_type_in_arrow_function, + ) + } + + /// Parse the rest of a `ConditionalExpression` whose `?` has been consumed. + #[expect(clippy::inline_always)] + #[inline(always)] + pub(super) fn parse_conditional_expression_after_question( + &mut self, + lhs_start: u32, + lhs: Expression<'a>, + question_span: Span, + allow_return_type_in_arrow_function: bool, + ) -> Expression<'a> { let consequent = self.context_add(Context::In, |p| { p.parse_assignment_expression_or_higher_impl( /* allow_return_type_in_arrow_function */ false, @@ -1693,28 +1741,75 @@ impl<'a, C: Config> ParserImpl<'a, C> { return self.parse_yield_expression(); } 'parse_lhs: { - // `() => {}`, `(x) => {}`, `async x => {}` + // `() => {}`, `(x) => {}`, `async x => {}`, `(x) => {}` let arrow_expr = match kind { - Kind::LParen if !self.is_ts && !self.ctx.has_decorator() => { + Kind::LParen => { let pure_comments = self.lexer.trivia_builder.previous_token_pure_comments(); - match self.try_parse_arrow_function_expression::( + let (expression, is_arrow) = self + .parse_parenthesized_expression_or_arrow_function( + allow_return_type_in_arrow_function, + no_side_effects_comments, + ); + if !is_arrow { + break 'parse_lhs self.parse_cover_expression_rest( + start, + expression, + pure_comments, + /* lhs_parenthesized */ true, + ); + } + Some(expression) + } + Kind::Async => { + let pure_comments = + self.lexer.trivia_builder.previous_token_pure_comments(); + match self.try_parse_async_arrow_function_or_call( allow_return_type_in_arrow_function, ) { - Some(Expression::ParenthesizedExpression(parenthesized)) => { - break 'parse_lhs self.parse_reused_parenthesized_expression_rest( + Some((expression, /* is_arrow */ false)) => { + break 'parse_lhs self.parse_cover_expression_rest( start, - parenthesized, + expression, pure_comments, + /* lhs_parenthesized */ false, ); } - arrow => arrow, + Some((expression, _)) => Some(expression), + None => None, } } - Kind::LParen | Kind::LAngle | Kind::Async => self - .try_parse_arrow_function_expression::( - allow_return_type_in_arrow_function, - ), + // `
`, `(x) => {}` + Kind::LAngle if self.source_type.is_jsx() => { + // In a JSX file, `<` can only start JSX. + // Checking here skips the checkpoint which TSX needs. + let (expression, is_arrow) = if self.is_ts { + self.parse_jsx_expression_or_generic_arrow_function( + allow_return_type_in_arrow_function, + ) + } else { + (self.parse_jsx_expression(), false) + }; + if !is_arrow { + // A JSX element is a complete `UpdateExpression`. + break 'parse_lhs if kind_to_precedence(self.cur_kind()).is_none() { + expression + } else { + self.parse_binary_expression_rest( + start, + expression, + /* lhs_parenthesized */ false, + Precedence::Comma, + ) + }; + } + Some(expression) + } + // `(x) => {}` in TS. JSX and TSX files take the branch above. + // In JS, `<` here is a syntax error, so it's not worth checking `is_ts` first. + Kind::LAngle => self.try_parse_generic_arrow_function_expression( + allow_return_type_in_arrow_function, + ), _ => None, }; if let Some(mut arrow_expr) = arrow_expr { @@ -1774,26 +1869,52 @@ impl<'a, C: Config> ParserImpl<'a, C> { expr } + /// Parse what follows the primary expression that a cover grammar produced: + /// a parenthesized expression, or the call `async(…)`. #[inline(never)] - fn parse_reused_parenthesized_expression_rest( + fn parse_cover_expression_rest( &mut self, start: u32, - parenthesized: ArenaBox<'a, ParenthesizedExpression<'a>>, + primary: Expression<'a>, pure_comments: Option<(u32, NonZeroU32)>, + lhs_parenthesized: bool, ) -> Expression<'a> { - let primary = if self.options.preserve_parens { - Expression::ParenthesizedExpression(parenthesized) - } else { - parenthesized.unbox().expression - }; let lhs = self.parse_primary_expression_rest(start, primary, pure_comments); if kind_to_precedence(self.cur_kind()).is_none() { lhs } else { - self.parse_binary_expression_rest(start, lhs, true, Precedence::Comma) + self.parse_binary_expression_rest(start, lhs, lhs_parenthesized, Precedence::Comma) } } + /// Parse the rest of an `AssignmentExpression` that starts with `primary`, which must not + /// be parenthesized and cannot be the parameter of an arrow function. + pub(super) fn parse_assignment_expression_rest( + &mut self, + start: u32, + primary: Expression<'a>, + pure_comments: Option<(u32, NonZeroU32)>, + ) -> Expression<'a> { + let lhs = self.parse_primary_expression_rest(start, primary, pure_comments); + let lhs = if kind_to_precedence(self.cur_kind()).is_none() { + lhs + } else { + self.parse_binary_expression_rest(start, lhs, false, Precedence::Comma) + }; + let kind = self.cur_kind(); + if kind.is_assignment_operator() { + return self.parse_assignment_expression_recursive( + start, lhs, None, /* allow_return_type_in_arrow_function */ true, + ); + } + if kind == Kind::Question { + return self.parse_conditional_expression_rest( + start, lhs, /* allow_return_type_in_arrow_function */ true, + ); + } + lhs + } + #[cold] #[inline(never)] fn apply_pure_comments_to_call( @@ -1902,12 +2023,12 @@ impl<'a, C: Config> ParserImpl<'a, C> { start: u32, first_expression: Expression<'a>, ) -> Expression<'a> { - let mut expressions = ArenaVec::with_capacity_in(2, self); - expressions.push(first_expression); - while self.eat(Kind::Comma) { - let expression = self.parse_assignment_expression_or_higher(); - expressions.push(expression); - } + let mut first = Some(first_expression); + let expressions = self.collect_list(|p| { + first + .take() + .or_else(|| p.eat(Kind::Comma).then(|| p.parse_assignment_expression_or_higher())) + }); Expression::new_sequence_expression(self.end_span(start), expressions, self) } @@ -1961,11 +2082,25 @@ impl<'a, C: Config> ParserImpl<'a, C> { // Always parse as await expression if self.ctx.has_await() { let start = self.cur_start(); + let await_token = self.cur_token(); self.bump_any(); // consume `await` + // In a list that may be the parameters of an arrow function, `(await) => {}`, + // `await` without an operand is the name of a parameter. Report it as such, as + // parsing the list as parameters would, and carry on with the identifier. + if matches!( + self.cur_kind(), + Kind::RParen | Kind::RBrack | Kind::RCurly | Kind::Comma | Kind::Colon | Kind::Eq + ) && self.state.cover_depth > 0 + { + return self.parse_await_as_identifier(await_token); + } let argument = self.parse_unary_expression_or_higher(self.cur_start()); return Expression::new_await_expression(self.end_span(start), argument, self); } + // An async arrow function that this may be a parameter of reserves `await`. + self.state.mentions_await = true; + // Case 2: Not in await context, but unambiguously an await expression // Parse as await expression and report error for better diagnostics // This matches Babel's behavior: report "await only allowed in async" error @@ -2003,6 +2138,19 @@ impl<'a, C: Config> ParserImpl<'a, C> { self.parse_update_expression(lhs_start) } + #[cold] + #[inline(never)] + fn parse_await_as_identifier(&mut self, await_token: crate::lexer::Token) -> Expression<'a> { + let span = await_token.span(); + self.error(diagnostics::identifier_async("await", span)); + let name = if await_token.escaped() { + self.lexer.get_string(await_token) + } else { + self.token_source(&await_token) + }; + Expression::new_identifier(span, self.ident(name), self) + } + fn parse_decorated_expression(&mut self) -> Expression<'a> { let start = self.cur_start(); let decorators = self.parse_decorators(); @@ -2015,15 +2163,7 @@ impl<'a, C: Config> ParserImpl<'a, C> { } pub(crate) fn parse_decorators(&mut self) -> ArenaVec<'a, Decorator<'a>> { - if self.at(Kind::At) { - let mut decorators = ArenaVec::with_capacity_in(1, self); - while self.at(Kind::At) { - decorators.push(self.parse_decorator()); - } - decorators - } else { - ArenaVec::new_in(self) - } + self.collect_list(|p| p.at(Kind::At).then(|| p.parse_decorator())) } /// `Decorator`[Yield, Await]: diff --git a/vendor/oxc_parser/src/js/function.rs b/vendor/oxc_parser/src/js/function.rs index b9af51340..410c41952 100644 --- a/vendor/oxc_parser/src/js/function.rs +++ b/vendor/oxc_parser/src/js/function.rs @@ -33,11 +33,24 @@ impl<'a, C: Config> ParserImpl<'a, C> { let opening_span = self.cur_token().span(); self.expect(Kind::LCurly); + if self.at(Kind::RCurly) { + // `{}`: there are no directives or statements to parse. + self.advance(Kind::RCurly); + let (directives, statements) = (ArenaVec::new_in(self), ArenaVec::new_in(self)); + return FunctionBody::boxed(self.end_span(start), directives, statements, self); + } + + // Statements are never part of the binding pattern an enclosing cover list + // may become. + let cover_depth = std::mem::replace(&mut self.state.cover_depth, 0); + // Add Return context, remove TopLevel context let (directives, statements) = self.context(Context::Return, Context::TopLevel, |p| { p.parse_directives_and_statements(/* in_ts_namespace_body */ false) }); + self.state.cover_depth = cover_depth; + self.expect_closing(Kind::RCurly, opening_span); FunctionBody::boxed(self.end_span(start), directives, statements, self) } @@ -67,30 +80,6 @@ impl<'a, C: Config> ParserImpl<'a, C> { (this_param, formal_parameters) } - /// Parse an ambiguous JS arrow head, retaining whether its final comma prevents it - /// from also being a parenthesized expression. - pub(super) fn parse_cover_arrow_parameters( - &mut self, - ) -> (ArenaBox<'a, FormalParameters<'a>>, bool) { - debug_assert!(!self.is_ts); - let start = self.cur_start(); - let opening_span = self.cur_token().span(); - self.expect(Kind::LParen); - let (list, rest) = - self.parse_formal_parameters_list(FunctionKind::Expression, opening_span); - let has_trailing_comma = - list.last().is_some_and(|param| param.span.end < self.prev_token_end); - self.expect(Kind::RParen); - let params = FormalParameters::boxed( - self.end_span(start), - FormalParameterKind::ArrowFormalParameters, - list, - rest, - self, - ); - (params, has_trailing_comma) - } - #[expect(clippy::inline_always)] #[inline(always)] fn parse_formal_parameters_list( @@ -98,106 +87,166 @@ impl<'a, C: Config> ParserImpl<'a, C> { func_kind: FunctionKind, opening_span: Span, ) -> (ArenaVec<'a, FormalParameter<'a>>, Option>>) { - let mut list = ArenaVec::new_in(self); - let rest = self.parse_formal_parameters_list_into(&mut list, func_kind, opening_span); - (list, rest) + self.parse_formal_parameters_list_after::( + func_kind, + opening_span, + true, + None, + |_| None, + ) } + /// Parse a parameter list whose leading parameters were already parsed as something else. + /// + /// When `PARSED` is `true`, `parsed` yields those parameters in order until it returns `None`. + /// `at_parameter_start` is `false` if the cursor is after a parameter (or after `rest`) + /// instead of at the start of one, so that `,` or `)` comes next. #[expect(clippy::inline_always)] #[inline(always)] - fn parse_formal_parameters_list_into( + pub(super) fn parse_formal_parameters_list_after( &mut self, - list: &mut ArenaVec<'a, FormalParameter<'a>>, func_kind: FunctionKind, opening_span: Span, - ) -> Option>> { - let mut rest: Option>> = None; - let mut first = true; + at_parameter_start: bool, + rest: Option>>, + mut parsed: impl FnMut(&mut Self) -> Option>, + ) -> (ArenaVec<'a, FormalParameter<'a>>, Option>>) { + let mut rest = rest; + let mut first = at_parameter_start; let mut has_optional = false; + let mut has_parsed = PARSED; - loop { - let kind = self.cur_kind(); - if kind == Kind::RParen - || matches!(kind, Kind::Eof | Kind::Undetermined) - || self.fatal_error.is_some() - { - break; + let list = self.collect_list(|p| { + if PARSED && has_parsed { + if let Some(param) = parsed(p) { + has_optional |= param.optional; + return Some(param); + } + has_parsed = false; } - - if first { - first = false; - } else { - let comma_span = self.cur_token().span(); - if kind != Kind::Comma { - let error = diagnostics::expect_closing_or_separator( - Kind::RParen.to_str(), - Kind::Comma.to_str(), - kind.to_str(), - comma_span, - opening_span, - ); - self.set_fatal_error(error); - break; + loop { + let kind = p.cur_kind(); + if kind == Kind::RParen + || matches!(kind, Kind::Eof | Kind::Undetermined) + || p.fatal_error.is_some() + { + return None; } - self.bump_any(); - let kind = self.cur_kind(); - if kind == Kind::RParen { - if rest.is_some() && !self.ctx.has_ambient() { - self.error(diagnostics::rest_element_trailing_comma(comma_span)); + + if first { + first = false; + } else { + let comma_span = p.cur_token().span(); + if kind != Kind::Comma { + let error = diagnostics::expect_closing_or_separator( + Kind::RParen.to_str(), + Kind::Comma.to_str(), + kind.to_str(), + comma_span, + opening_span, + ); + p.set_fatal_error(error); + return None; + } + p.bump_any(); + let kind = p.cur_kind(); + if kind == Kind::RParen { + if rest.is_some() && !p.ctx.has_ambient() { + p.error(diagnostics::rest_element_trailing_comma(comma_span)); + } + return None; } - break; } - } - - if let Some(r) = &rest { - self.set_fatal_error(diagnostics::rest_parameter_last( - r.type_annotation.as_ref().map_or_else( - || r.rest.span, - |type_annotation| r.rest.span.merge(type_annotation.span()), - ), - )); - break; - } - let start = self.cur_start(); - let decorators = self.parse_decorators(); - - if self.at(Kind::Dot3) { - let rest_element = self.parse_rest_element_for_formal_parameter(); - let type_annotation = - if self.is_ts { self.parse_ts_type_annotation() } else { None }; - - let are_decorators_allowed = - matches!(func_kind, FunctionKind::ClassMethod | FunctionKind::Constructor) - && self.is_ts; - if !are_decorators_allowed { - for decorator in &decorators { - self.error(diagnostics::decorators_are_not_valid_here(decorator.span)); - } + if let Some(r) = &rest { + p.set_fatal_error(diagnostics::rest_parameter_last( + r.type_annotation.as_ref().map_or_else( + || r.rest.span, + |type_annotation| r.rest.span.merge(type_annotation.span()), + ), + )); + return None; } - rest = Some(FormalParameterRest::boxed( - self.end_span(start), - decorators, - rest_element, - type_annotation, - self, - )); - } else { - let param = - self.parse_formal_parameter_with_decorators(func_kind, start, decorators); + let start = p.cur_start(); + // A parameter that starts with an identifier or a pattern has no decorators + // or modifiers, which are all keywords or `@`. + let param = if matches!(p.cur_kind(), Kind::Ident | Kind::LCurly | Kind::LBrack) { + p.parse_formal_parameter_without_modifiers(start) + } else { + let decorators = p.parse_decorators(); + + if p.at(Kind::Dot3) { + let rest_element = p.parse_rest_element_for_formal_parameter(); + let type_annotation = + if p.is_ts { p.parse_ts_type_annotation() } else { None }; + + let are_decorators_allowed = matches!( + func_kind, + FunctionKind::ClassMethod | FunctionKind::Constructor + ) && p.is_ts; + if !are_decorators_allowed { + for decorator in &decorators { + p.error(diagnostics::decorators_are_not_valid_here(decorator.span)); + } + } + + rest = Some(FormalParameterRest::boxed( + p.end_span(start), + decorators, + rest_element, + type_annotation, + p, + )); + continue; + } + p.parse_formal_parameter_with_decorators(func_kind, start, decorators) + }; if param.optional { has_optional = true; } else if has_optional && param.initializer.is_none() { - self.error(diagnostics::required_parameter_after_optional_parameter( - param.span, - )); + p.error(diagnostics::required_parameter_after_optional_parameter(param.span)); } - list.push(param); + return Some(param); } + }); + + (list, rest) + } + + /// Parse a parameter that has no decorators or modifiers: `a`, `a: T = b`, `{ a }?: T`. + fn parse_formal_parameter_without_modifiers(&mut self, start: u32) -> FormalParameter<'a> { + let pattern = self.parse_binding_pattern(); + if matches!(self.cur_kind(), Kind::Comma | Kind::RParen) { + return FormalParameter::new_plain(self.end_span(start), pattern, self); } - rest + let optional = self.is_ts && self.eat(Kind::Question); + let type_annotation = self.parse_ts_type_annotation(); + let init = if self.eat(Kind::Eq) { + let init = + self.context_add(Context::In, ParserImpl::parse_assignment_expression_or_higher); + if optional { + self.error(diagnostics::a_parameter_cannot_have_question_mark_and_initializer( + pattern.span(), + )); + } + Some(ArenaBox::new_in(init, self)) + } else { + None + }; + FormalParameter::new( + self.end_span(start), + [], + pattern, + type_annotation, + init, + optional, + None, + false, + false, + self, + ) } fn parse_formal_parameter_with_decorators( @@ -304,13 +353,15 @@ impl<'a, C: Config> ParserImpl<'a, C> { ) -> ArenaBox<'a, Function<'a>> { let ctx = self.ctx; // `new.target` is allowed in a function's parameters and body (but not arrow - // functions, which are parsed via `parse_function_body` directly). + // functions, which are parsed via `parse_function_body` directly). Neither is at + // the top level, so `await` in them is not top-level `await`. self.ctx = self .ctx .and_in(true) .and_await(r#async) .and_yield(generator.is_some()) - .and_new_target(true); + .and_new_target(true) + .and_top_level(false); let type_parameters = self.parse_ts_type_parameters(); let (this_param, params) = self.parse_formal_parameters(func_kind, param_kind); let return_type = if self.is_ts { self.parse_ts_return_type_annotation() } else { None }; @@ -324,7 +375,8 @@ impl<'a, C: Config> ParserImpl<'a, C> { .and_in(ctx.has_in()) .and_await(ctx.has_await()) .and_yield(ctx.has_yield()) - .and_new_target(ctx.has_new_target()); + .and_new_target(ctx.has_new_target()) + .and_top_level(ctx.has_top_level()); if (!self.is_ts || matches!(func_kind, FunctionKind::ObjectMethod)) && body.is_none() { return self.fatal_error(diagnostics::expect_function_body(self.end_span(start))); } diff --git a/vendor/oxc_parser/src/js/grammar.rs b/vendor/oxc_parser/src/js/grammar.rs index 2f1a25a07..d2b418994 100644 --- a/vendor/oxc_parser/src/js/grammar.rs +++ b/vendor/oxc_parser/src/js/grammar.rs @@ -1,9 +1,11 @@ -//! Cover Grammar for Destructuring Assignment +//! Cover grammars for destructuring: an expression that covers an assignment target or a +//! binding pattern. -use oxc_allocator::ArenaVec; +use oxc_allocator::{ArenaBox, ArenaVec, Dummy, GetAllocator}; use oxc_ast::ast::*; use oxc_span::GetSpan; +use super::cover::{Cover, CoverCheck, CoverElement}; use crate::{ParserConfig as Config, ParserImpl, diagnostics}; pub trait CoverGrammar<'a, T, C: Config>: Sized { @@ -255,9 +257,404 @@ impl<'a, C: Config> CoverGrammar<'a, ObjectProperty<'a>, C> for AssignmentTarget property.span, property.key, binding, - property.computed, p, ) } } } + +impl<'a, C: Config> ParserImpl<'a, C> { + // `ObjectLiteral`, `ArrayLiteral` and `IdentifierReference` cover the matching binding + // patterns. A conversion must only be given an expression that passed its check. + + /// Whether the elements of an undecided cover list can all be parameters. + pub(super) fn is_cover_parameter_list(&self, cover: Cover) -> bool { + let elements = &self.state.cover_elements[cover.base..]; + elements.iter().enumerate().all(|(index, element)| match element { + CoverElement::Identifier { .. } | CoverElement::IdentifierWithInitializer { .. } => { + true + } + CoverElement::LiteralWithInitializer { literal, .. } => { + self.check_cover_binding(literal).is_ok() + } + // `(this): T => …` is reported as an arrow function with a `this` parameter. + CoverElement::Expression(Expression::ThisExpression(_)) => self.is_ts && index == 0, + CoverElement::Expression(expression) => { + self.check_cover_binding_element(expression).is_ok() + } + CoverElement::Spread(spread) => { + index == elements.len() - 1 + && self.check_cover_binding_element(&spread.argument).is_ok() + } + }) + } + + /// Check that `expression` covers a `BindingElement`: a binding pattern that may have + /// an initializer. + pub(super) fn check_cover_binding_element( + &self, + expression: &Expression<'a>, + ) -> CoverCheck<'a> { + match expression { + Expression::AssignmentExpression(assignment) + if assignment.operator == AssignmentOperator::Assign + && !self.is_cover_parenthesized(assignment.span.start) => + { + self.check_cover_binding_target(&assignment.left) + } + _ => self.check_cover_binding(expression), + } + } + + /// Check that `expression` covers a `BindingIdentifier` or a `BindingPattern`. + pub(super) fn check_cover_binding(&self, expression: &Expression<'a>) -> CoverCheck<'a> { + // The checks and conversions of binding patterns read no token, so they + // check the stack floor themselves. Nested elements pass through here, + // or through `check_cover_binding_target`, once per level. + if self.below_stack_floor() { + return Err(self.stack_floor_error(expression.span())); + } + match expression { + Expression::Identifier(ident) if !self.is_cover_parenthesized(ident.span.start) => { + Ok(()) + } + // `(yield) => …` in a generator. `yield` is not a valid `BindingIdentifier` there, + // but that error is more useful than one about a `YieldExpression`. + Expression::YieldExpression(expression) + if expression.argument.is_none() + && !expression.delegate + && !self.is_cover_parenthesized(expression.span.start) => + { + Ok(()) + } + Expression::ObjectExpression(object) + if !self.is_cover_parenthesized(object.span.start) => + { + let last = object.properties.len().wrapping_sub(1); + for (index, property) in object.properties.iter().enumerate() { + match property { + ObjectPropertyKind::ObjectProperty(property) => { + // Methods and accessors are not properties of a pattern. + if property.kind != PropertyKind::Init || property.method { + return Err(diagnostics::invalid_arrow_function_parameter( + property.span, + )); + } + if !property.shorthand { + self.check_cover_binding_element(&property.value)?; + } + } + ObjectPropertyKind::SpreadProperty(spread) => { + if index != last { + return Err(diagnostics::binding_rest_element_last(spread.span)); + } + if !matches!( + &spread.argument, + Expression::Identifier(ident) + if !self.is_cover_parenthesized(ident.span.start) + ) { + return Err(diagnostics::invalid_binding_rest_element( + spread.argument.span(), + )); + } + } + } + } + Ok(()) + } + Expression::ArrayExpression(array) + if !self.is_cover_parenthesized(array.span.start) => + { + let last = array.elements.len().wrapping_sub(1); + for (index, element) in array.elements.iter().enumerate() { + match element { + ArrayExpressionElement::Elision(_) => {} + ArrayExpressionElement::SpreadElement(spread) => { + if index != last { + return Err(diagnostics::binding_rest_element_last(spread.span)); + } + self.check_cover_binding_element(&spread.argument)?; + } + element => self.check_cover_binding_element(element.to_expression())?, + } + } + Ok(()) + } + _ => Err(diagnostics::invalid_arrow_function_parameter(expression.span())), + } + } + + /// Check that an assignment target, which an expression was already refined to, covers + /// a `BindingIdentifier` or a `BindingPattern`. + fn check_cover_binding_target(&self, target: &AssignmentTarget<'a>) -> CoverCheck<'a> { + if self.below_stack_floor() { + return Err(self.stack_floor_error(target.span())); + } + match target { + AssignmentTarget::AssignmentTargetIdentifier(ident) + if !self.is_cover_parenthesized(ident.span.start) => + { + Ok(()) + } + AssignmentTarget::ObjectAssignmentTarget(object) + if !self.is_cover_parenthesized(object.span.start) => + { + for property in &object.properties { + if let AssignmentTargetProperty::AssignmentTargetPropertyProperty(property) = + property + { + self.check_cover_binding_target_maybe_default(&property.binding)?; + } + } + match &object.rest { + Some(rest) + if !matches!( + &rest.target, + AssignmentTarget::AssignmentTargetIdentifier(ident) + if !self.is_cover_parenthesized(ident.span.start) + ) => + { + Err(diagnostics::invalid_binding_rest_element(rest.target.span())) + } + _ => Ok(()), + } + } + AssignmentTarget::ArrayAssignmentTarget(array) + if !self.is_cover_parenthesized(array.span.start) => + { + for element in array.elements.iter().flatten() { + self.check_cover_binding_target_maybe_default(element)?; + } + match &array.rest { + Some(rest) => self.check_cover_binding_target(&rest.target), + None => Ok(()), + } + } + _ => Err(diagnostics::invalid_arrow_function_parameter(target.span())), + } + } + + fn check_cover_binding_target_maybe_default( + &self, + target: &AssignmentTargetMaybeDefault<'a>, + ) -> CoverCheck<'a> { + match target { + AssignmentTargetMaybeDefault::AssignmentTargetWithDefault(target) => { + self.check_cover_binding_target(&target.binding) + } + _ => self.check_cover_binding_target(target.to_assignment_target()), + } + } + + /// Convert an expression that covers a `BindingElement`. + pub(super) fn cover_expression_to_binding_element( + &mut self, + expression: Expression<'a>, + ) -> BindingPattern<'a> { + match expression { + Expression::AssignmentExpression(assignment) => { + let AssignmentExpression { span, left, right, .. } = assignment.unbox(); + let left = self.cover_assignment_target_to_binding_pattern(left); + BindingPattern::new_assignment_pattern(span, left, right, self) + } + expression => self.cover_expression_to_binding_pattern(expression), + } + } + + /// Convert an expression that covers a `BindingIdentifier` or a `BindingPattern`. + pub(super) fn cover_expression_to_binding_pattern( + &mut self, + expression: Expression<'a>, + ) -> BindingPattern<'a> { + if self.below_stack_floor() { + return self.stopped_at_stack_floor(); + } + match expression { + Expression::Identifier(ident) => { + BindingPattern::new_binding_identifier(ident.span, ident.name, self) + } + Expression::YieldExpression(expression) => { + let span = expression.span; + self.error(diagnostics::identifier_generator("yield", span, false)); + BindingPattern::new_binding_identifier(span, self.ident("yield"), self) + } + Expression::ObjectExpression(object) => { + let ObjectExpression { span, properties, .. } = object.unbox(); + let has_rest = + matches!(properties.last(), Some(ObjectPropertyKind::SpreadProperty(_))); + let mut list = + ArenaVec::with_capacity_in(properties.len() - usize::from(has_rest), self); + let mut rest = None; + for property in properties { + match property { + ObjectPropertyKind::ObjectProperty(property) => { + let ObjectProperty { span, key, value, shorthand, .. } = + property.unbox(); + let value = if shorthand { + // `{ a }`, or the `CoverInitializedName` `{ a = b }`. + let binding = self.cover_expression_to_binding_pattern(value); + let cover_initialized_name = &mut self.state.cover_initialized_name; + if cover_initialized_name.is_empty() { + binding + } else if let Some(cover) = + cover_initialized_name.remove(&span.start) + { + BindingPattern::new_assignment_pattern( + span, + binding, + cover.initializer, + self, + ) + } else { + binding + } + } else { + self.cover_expression_to_binding_element(value) + }; + list.push(BindingProperty::new(span, key, value, shorthand, self)); + } + ObjectPropertyKind::SpreadProperty(spread) => { + rest = Some(self.cover_spread_to_binding_rest(spread, span.start)); + } + } + } + BindingPattern::new_object_pattern(span, list, rest, self) + } + Expression::ArrayExpression(array) => { + let ArrayExpression { span, elements, .. } = array.unbox(); + let has_rest = + matches!(elements.last(), Some(ArrayExpressionElement::SpreadElement(_))); + let mut list = + ArenaVec::with_capacity_in(elements.len() - usize::from(has_rest), self); + let mut rest = None; + for element in elements { + match element { + ArrayExpressionElement::Elision(_) => list.push(None), + ArrayExpressionElement::SpreadElement(spread) => { + rest = Some(self.cover_spread_to_binding_rest(spread, span.start)); + } + element => { + let element = element.into_expression(); + list.push(Some(self.cover_expression_to_binding_element(element))); + } + } + } + BindingPattern::new_array_pattern(span, list, rest, self) + } + // The check rejects every other expression. + _ => Dummy::dummy(self.allocator()), + } + } + + /// Convert the spread element that ends an object or array literal starting at + /// `literal_start` to the rest element of a pattern. + fn cover_spread_to_binding_rest( + &mut self, + spread: ArenaBox<'a, SpreadElement<'a>>, + literal_start: u32, + ) -> ArenaBox<'a, BindingRestElement<'a>> { + let SpreadElement { span, argument, .. } = spread.unbox(); + let argument = self.cover_expression_to_binding_element(argument); + if let BindingPattern::AssignmentPattern(pattern) = &argument { + self.error(diagnostics::a_rest_element_cannot_have_an_initializer(pattern.span)); + } + if !self.state.trailing_commas.is_empty() + && let Some(comma_span) = self.state.trailing_commas.remove(&literal_start) + && !self.ctx.has_ambient() + { + self.error(diagnostics::rest_element_trailing_comma(comma_span)); + } + BindingRestElement::boxed(span, argument, self) + } + + /// Convert an assignment target that covers a `BindingIdentifier` or a `BindingPattern`. + pub(super) fn cover_assignment_target_to_binding_pattern( + &mut self, + target: AssignmentTarget<'a>, + ) -> BindingPattern<'a> { + if self.below_stack_floor() { + return self.stopped_at_stack_floor(); + } + match target { + AssignmentTarget::AssignmentTargetIdentifier(ident) => { + BindingPattern::new_binding_identifier(ident.span, ident.name, self) + } + AssignmentTarget::ObjectAssignmentTarget(object) => { + let ObjectAssignmentTarget { span, properties, rest, .. } = object.unbox(); + let mut list = ArenaVec::with_capacity_in(properties.len(), self); + for property in properties { + list.push(match property { + AssignmentTargetProperty::AssignmentTargetPropertyIdentifier(property) => { + let AssignmentTargetPropertyIdentifier { span, binding, init, .. } = + property.unbox(); + let key = PropertyKey::StaticIdentifier(IdentifierName::boxed( + binding.span, + binding.name, + self, + )); + let value = BindingPattern::new_binding_identifier( + binding.span, + binding.name, + self, + ); + let value = match init { + Some(init) => { + BindingPattern::new_assignment_pattern(span, value, init, self) + } + None => value, + }; + BindingProperty::new(span, key, value, true, self) + } + AssignmentTargetProperty::AssignmentTargetPropertyProperty(property) => { + let AssignmentTargetPropertyProperty { span, name, binding, .. } = + property.unbox(); + let value = self + .cover_assignment_target_maybe_default_to_binding_element(binding); + BindingProperty::new(span, name, value, false, self) + } + }); + } + let rest = rest.map(|rest| self.cover_assignment_target_rest_to_binding_rest(rest)); + BindingPattern::new_object_pattern(span, list, rest, self) + } + AssignmentTarget::ArrayAssignmentTarget(array) => { + let ArrayAssignmentTarget { span, elements, rest, .. } = array.unbox(); + let mut list = ArenaVec::with_capacity_in(elements.len(), self); + for element in elements { + list.push(element.map(|element| { + self.cover_assignment_target_maybe_default_to_binding_element(element) + })); + } + let rest = rest.map(|rest| self.cover_assignment_target_rest_to_binding_rest(rest)); + BindingPattern::new_array_pattern(span, list, rest, self) + } + // The check rejects every other target. + _ => Dummy::dummy(self.allocator()), + } + } + + fn cover_assignment_target_maybe_default_to_binding_element( + &mut self, + target: AssignmentTargetMaybeDefault<'a>, + ) -> BindingPattern<'a> { + match target { + AssignmentTargetMaybeDefault::AssignmentTargetWithDefault(target) => { + let AssignmentTargetWithDefault { span, binding, init, .. } = target.unbox(); + let left = self.cover_assignment_target_to_binding_pattern(binding); + BindingPattern::new_assignment_pattern(span, left, init, self) + } + target => { + self.cover_assignment_target_to_binding_pattern(target.into_assignment_target()) + } + } + } + + fn cover_assignment_target_rest_to_binding_rest( + &mut self, + rest: ArenaBox<'a, AssignmentTargetRest<'a>>, + ) -> ArenaBox<'a, BindingRestElement<'a>> { + let AssignmentTargetRest { span, target, .. } = rest.unbox(); + let argument = self.cover_assignment_target_to_binding_pattern(target); + BindingRestElement::boxed(span, argument, self) + } +} diff --git a/vendor/oxc_parser/src/js/mod.rs b/vendor/oxc_parser/src/js/mod.rs index 2b4f5099b..05aaace66 100644 --- a/vendor/oxc_parser/src/js/mod.rs +++ b/vendor/oxc_parser/src/js/mod.rs @@ -5,6 +5,7 @@ mod grammar; mod arrow; mod binding; mod class; +mod cover; mod declaration; mod expression; mod function; @@ -13,6 +14,9 @@ mod object; mod operator; mod statement; +pub use cover::CoverElement; +pub use operator::kind_to_precedence; + #[derive(Debug, Clone, Copy, Eq, PartialEq)] pub enum Tristate { True, diff --git a/vendor/oxc_parser/src/js/module.rs b/vendor/oxc_parser/src/js/module.rs index e6b2266a4..6b8ed25b3 100644 --- a/vendor/oxc_parser/src/js/module.rs +++ b/vendor/oxc_parser/src/js/module.rs @@ -280,22 +280,13 @@ impl<'a, C: Config> ParserImpl<'a, C> { default_specifier: Option>, import_kind: ImportOrExportKind, ) -> ArenaVec<'a, ImportDeclarationSpecifier<'a>> { - // If there is a default specifier, create a Vec with the default specifier in it, - // otherwise, create an empty Vec. - let mut specifiers = if default_specifier.is_some() { - ArenaVec::with_capacity_in(1, self) - } else { - ArenaVec::new_in(self) - }; - - if let Some(default_specifier) = default_specifier { + let specifiers = if let Some(default_specifier) = default_specifier { let default_span = default_specifier.span; let specifier = ImportDeclarationSpecifier::new_import_default_specifier( default_specifier.span, default_specifier, self, ); - specifiers.push(specifier); if self.eat(Kind::Comma) { match self.cur_kind() { // import defaultExport, * as name from "module-name"; @@ -305,8 +296,8 @@ impl<'a, C: Config> ParserImpl<'a, C> { default_span, )); } - let specifier = self.parse_import_namespace_specifier(); - specifiers.push(specifier); + let namespace = self.parse_import_namespace_specifier(); + ArenaVec::from_array_in([specifier, namespace], self) } // import defaultExport, { export1 [ , [...] ] } from "module-name"; Kind::LCurly => { @@ -315,19 +306,23 @@ impl<'a, C: Config> ParserImpl<'a, C> { default_span, )); } - self.parse_import_specifiers_into(&mut specifiers, import_kind); + self.parse_import_specifiers(Some(specifier), import_kind) } _ => return self.unexpected(), } + } else { + ArenaVec::from_value_in(specifier, self) } } else if self.at(Kind::Star) { // import * as name from "module-name"; let specifier = self.parse_import_namespace_specifier(); - specifiers.push(specifier); + ArenaVec::from_value_in(specifier, self) } else if self.at(Kind::LCurly) { // import { export1 , export2 as alias2 , [...] } from "module-name"; - self.parse_import_specifiers_into(&mut specifiers, import_kind); - } + self.parse_import_specifiers(None, import_kind) + } else { + ArenaVec::new_in(self) + }; self.expect(Kind::From); specifiers @@ -344,24 +339,25 @@ impl<'a, C: Config> ParserImpl<'a, C> { } // import { export1 , export2 as alias2 , [...] } from "module-name"; - fn parse_import_specifiers_into( + fn parse_import_specifiers( &mut self, - specifiers: &mut ArenaVec<'a, ImportDeclarationSpecifier<'a>>, + default_specifier: Option>, import_kind: ImportOrExportKind, - ) { + ) -> ArenaVec<'a, ImportDeclarationSpecifier<'a>> { debug_assert!(self.at(Kind::LCurly)); let opening_span = self.cur_token().span(); self.advance(Kind::LCurly); - self.context_remove(self.ctx, |p| { - let _ = p.parse_delimited_list_into( - specifiers, + let (specifiers, _) = self.context_remove(self.ctx, |p| { + p.parse_delimited_list_with_prefix( + default_specifier, Kind::RCurly, Kind::Comma, opening_span, |parser| parser.parse_import_specifier(import_kind), - ); + ) }); self.expect(Kind::RCurly); + specifiers } /// [Import Attributes](https://tc39.es/proposal-import-attributes) @@ -456,10 +452,15 @@ impl<'a, C: Config> ParserImpl<'a, C> { } let statement = if self.at(Kind::Import) { "import statement" } else { "export statement" }; let span = self.cur_token().span(); - if self.source_type.is_script() || self.source_type.is_commonjs() { - self.error(diagnostics::module_code(statement, span)); - } else if stmt_ctx != StatementContext::Program { + if stmt_ctx != StatementContext::Program { self.error(diagnostics::top_level(statement, span)); + } else if self.source_type.is_script() || self.source_type.is_commonjs() { + self.error(diagnostics::module_code(statement, span)); + } else if self.source_type.is_unambiguous() + && !self.module_record_builder.has_module_syntax() + { + // Reported if no module syntax makes the source a module, e.g. `import a = b` in JS. + self.error_on_script(diagnostics::module_code(statement, span)); } } diff --git a/vendor/oxc_parser/src/js/object.rs b/vendor/oxc_parser/src/js/object.rs index 1c679ddef..8970c8631 100644 --- a/vendor/oxc_parser/src/js/object.rs +++ b/vendor/oxc_parser/src/js/object.rs @@ -43,11 +43,52 @@ impl<'a, C: Config> ParserImpl<'a, C> { fn parse_object_expression_property(&mut self) -> ObjectPropertyKind<'a> { match self.cur_kind() { + Kind::Ident => ObjectPropertyKind::ObjectProperty( + self.parse_object_literal_element_with_identifier_key(), + ), Kind::Dot3 => ObjectPropertyKind::SpreadProperty(self.parse_spread_element()), _ => ObjectPropertyKind::ObjectProperty(self.parse_object_literal_element()), } } + /// Parse a property whose key is an identifier that is not a keyword in any context, + /// so it is not a modifier, `get` or `set`: `a`, `a: b`, `a = b` or `a() {}`. + fn parse_object_literal_element_with_identifier_key( + &mut self, + ) -> ArenaBox<'a, ObjectProperty<'a>> { + let start = self.cur_start(); + let (span, name) = self.parse_identifier_kind(Kind::Ident); + let key = PropertyKey::StaticIdentifier(IdentifierName::boxed(span, name, self)); + + let kind = self.cur_kind(); + let (value, method, shorthand) = if kind == Kind::Colon { + self.bump_any(); // `:` + (self.parse_assignment_expression_or_higher(), false, false) + } else if matches!(kind, Kind::LParen | Kind::LAngle) { + let method = + self.parse_method(/* async */ false, None, FunctionKind::ObjectMethod); + (Expression::FunctionExpression(method), true, false) + } else { + // CoverInitializedName ({ foo = bar }) + if kind == Kind::Eq { + self.bump_any(); // `=` + let initializer = self.parse_assignment_expression_or_higher(); + let cover = CoverInitializedName { span: self.end_span(start), initializer }; + self.state.cover_initialized_name.insert(start, cover); + } + (Expression::new_identifier(span, name, self), false, true) + }; + ObjectProperty::boxed( + self.end_span(start), + PropertyKind::Init, + key, + value, + method, + shorthand, + self, + ) + } + /// `PropertyDefinition`[Yield, Await] fn parse_object_literal_element(&mut self) -> ArenaBox<'a, ObjectProperty<'a>> { let start = self.cur_start(); @@ -66,9 +107,13 @@ impl<'a, C: Config> ParserImpl<'a, C> { } let asterisk_token = self.eat(Kind::Star).then_some(self.prev_token_end - 1); - let token_is_identifier = - self.cur_kind().is_identifier_reference(self.ctx.has_yield(), self.ctx.has_await()); - let (key, computed) = self.parse_property_name(); + let key_kind = self.cur_kind(); + let token_is_identifier = key_kind + .is_identifier_reference(self.ctx.has_yield(), self.ctx.has_await()) + // In a list that may be the parameters of an arrow function, `({ await }) => {}`, + // a reserved `await` or `yield` is reported as the binding it would be. + || (matches!(key_kind, Kind::Await | Kind::Yield) && self.state.cover_depth > 0); + let key = self.parse_property_name(); if asterisk_token.is_some() || matches!(self.cur_kind(), Kind::LParen | Kind::LAngle) { self.verify_modifiers( @@ -89,7 +134,6 @@ impl<'a, C: Config> ParserImpl<'a, C> { Expression::FunctionExpression(method), /* method */ true, /* shorthand */ false, - computed, self, ); } @@ -106,6 +150,9 @@ impl<'a, C: Config> ParserImpl<'a, C> { let PropertyKey::StaticIdentifier(identifier_name) = &key else { return self.unexpected(); }; + if matches!(key_kind, Kind::Await | Kind::Yield) { + self.check_identifier_with_span(key_kind, self.ctx, identifier_name.span); + } // CoverInitializedName ({ foo = bar }) if self.eat(Kind::Eq) { let initializer = self.parse_assignment_expression_or_higher(); @@ -124,7 +171,6 @@ impl<'a, C: Config> ParserImpl<'a, C> { value, /* method */ false, shorthand, - computed, self, ) } @@ -141,23 +187,24 @@ impl<'a, C: Config> ParserImpl<'a, C> { /// `PropertyName`[Yield, Await] : /// `LiteralPropertyName` /// `ComputedPropertyName`[?Yield, ?Await] - pub(crate) fn parse_property_name(&mut self) -> (PropertyKey<'a>, bool) { - let mut computed = false; - let key = match self.cur_kind() { + pub(crate) fn parse_property_name(&mut self) -> PropertyKey<'a> { + match self.cur_kind() { Kind::Ident => { let ident = self.parse_known_identifier_name(); PropertyKey::StaticIdentifier(self.alloc(ident)) } Kind::Str => { let literal = self.parse_known_literal_string(); - PropertyKey::StringLiteral(self.alloc(literal)) + PropertyKey::StaticStringLiteral(self.alloc(literal)) } - kind if kind.is_number() => PropertyKey::from(self.parse_literal_expression()), - // { [foo]() {} } - Kind::LBrack => { - computed = true; - PropertyKey::from(self.parse_computed_property_name()) + Kind::DecimalBigInt | Kind::BinaryBigInt | Kind::OctalBigInt | Kind::HexBigInt => { + PropertyKey::StaticBigIntLiteral(self.parse_literal_bigint()) + } + kind if kind.is_number() => { + PropertyKey::StaticNumericLiteral(self.parse_literal_number()) } + // { [foo]() {} } + Kind::LBrack => PropertyKey::from(self.parse_computed_property_name()), Kind::PrivateIdentifier => { let private_ident = self.parse_private_identifier(); self.error(diagnostics::private_identifier_in_property_name( @@ -170,8 +217,7 @@ impl<'a, C: Config> ParserImpl<'a, C> { let ident = self.parse_identifier_name(); PropertyKey::StaticIdentifier(self.alloc(ident)) } - }; - (key, computed) + } } /// `ComputedPropertyName`[Yield, Await] : [ `AssignmentExpression`[+In, ?Yield, ?Await] ] @@ -193,7 +239,7 @@ impl<'a, C: Config> ParserImpl<'a, C> { kind: PropertyKind, modifiers: &Modifiers, ) -> ArenaBox<'a, ObjectProperty<'a>> { - let (key, computed) = self.parse_property_name(); + let key = self.parse_property_name(); let function = self.parse_method(false, None, FunctionKind::ObjectMethod); match kind { PropertyKind::Get => self.check_getter(&function), @@ -213,7 +259,6 @@ impl<'a, C: Config> ParserImpl<'a, C> { Expression::FunctionExpression(function), /* method */ false, /* shorthand */ false, - /* computed */ computed, self, ) } diff --git a/vendor/oxc_parser/src/js/statement.rs b/vendor/oxc_parser/src/js/statement.rs index a6add9e8d..a2a5476f0 100644 --- a/vendor/oxc_parser/src/js/statement.rs +++ b/vendor/oxc_parser/src/js/statement.rs @@ -37,7 +37,7 @@ impl<'a, C: Config> ParserImpl<'a, C> { in_ts_namespace_body: bool, ) -> (ArenaVec<'a, Directive<'a>>, ArenaVec<'a, Statement<'a>>) { let mut directives = ArenaVec::new_in(self); - let mut statements = ArenaVec::new_in(self); + let mut statement_index = 0; let is_top_level = self.ctx.has_top_level(); let stmt_ctx = @@ -50,80 +50,81 @@ impl<'a, C: Config> ParserImpl<'a, C> { let track_await_reparse = is_top_level && self.source_type.is_unambiguous(); let mut expecting_directives = true; - while !self.has_fatal_error() { - if !is_top_level && self.at(Kind::RCurly) { - break; - } - - // Commit once module syntax is detected (`export` commits eagerly in - // `parse_export_declaration`; `has_module_syntax()` excludes TS's - // script-compatible `import x = ns.foo`). Until committed, checkpoint each - // statement so an `await` identifier in it can be reparsed. - let checkpoint = if track_await_reparse && !self.ctx.has_await() { - if self.module_record_builder.has_module_syntax() { - self.ctx = self.ctx.and_await(true); + let statements = self.collect_list(|p| { + while !p.has_fatal_error() && (is_top_level || !p.at(Kind::RCurly)) { + // Commit once module syntax is detected (`export` commits eagerly in + // `parse_export_declaration`; `has_module_syntax()` excludes TS's + // script-compatible `import x = ns.foo`). Until committed, checkpoint each + // statement so an `await` identifier in it can be reparsed. + let checkpoint = if track_await_reparse && !p.ctx.has_await() { + if p.module_record_builder.has_module_syntax() { + p.ctx = p.ctx.and_await(true); + None + } else { + p.state.encountered_await_identifier = false; + Some(p.checkpoint()) + } + } else { None + }; + + // Section 11.2.1 Directive Prologue + // Parse the complete expression statement before recognizing a directive: + // a string followed by an operator or member access is not a directive. + // See babel's core/categorized/not-directive fixture. + // Starting at a string token also excludes parenthesized strings when + // `preserve_parens = false`. + let stmt = if expecting_directives && p.at(Kind::Str) { + let start = p.cur_start(); + let expression = p.parse_expr(); + p.asi(); + match ExpressionStatement::new(p.end_span(start), expression, p) { + ExpressionStatement { + span, + expression: Expression::StringLiteral(string), + .. + } => { + let string = string.unbox(); + let src = &p.source_text + [string.span.start as usize + 1..string.span.end as usize - 1]; + directives.push(Directive::new(span, string, Str::from(src), p)); + continue; + } + statement => Statement::ExpressionStatement(p.alloc(statement)), + } } else { - self.state.encountered_await_identifier = false; - Some((statements.len(), self.checkpoint())) + p.parse_statement_list_item(stmt_ctx) + }; + + // Don't reparse a module declaration: `export` already committed to the + // Module goal while parsing, so reparsing would record the export twice. + // e.g. `@foo export default class C { x = await + 1 }` + if let Some(checkpoint) = checkpoint + && p.state.encountered_await_identifier + && !stmt.is_module_declaration() + { + p.state.potential_await_reparse.push((statement_index, checkpoint)); } - } else { - None - }; - - let stmt = self.parse_statement_list_item(stmt_ctx); - - // Don't reparse a module declaration: `export` already committed to the - // Module goal while parsing, so reparsing would record the export twice. - // e.g. `@foo export default class C { x = await + 1 }` - if let Some((stmt_index, checkpoint)) = checkpoint - && self.state.encountered_await_identifier - && !stmt.is_module_declaration() - { - self.state.potential_await_reparse.push((stmt_index, checkpoint)); - } - // Section 11.2.1 Directive Prologue - // The only way to get a correct directive is to parse the statement first and check if it is a string literal. - // All other method are flawed, see test cases in [babel](https://github.com/babel/babel/blob/v7.26.2/packages/babel-parser/test/fixtures/core/categorized/not-directive/input.js) - let stmt = if expecting_directives { - match stmt { - // span start will mismatch if they are parenthesized when `preserve_parens = false` - Statement::ExpressionStatement(expr) - if matches!(&expr.expression, Expression::StringLiteral(string) - if expr.span.start == string.span.start) => - { - let ExpressionStatement { span, expression, .. } = expr.unbox(); - let Expression::StringLiteral(string) = expression else { unreachable!() }; - let string = string.unbox(); - let src = &self.source_text - [string.span.start as usize + 1..string.span.end as usize - 1]; - directives.push(Directive::new(span, string, Str::from(src), self)); - continue; - } - stmt => { - expecting_directives = false; - stmt - } + expecting_directives = false; + // In an internal namespace body, module-referencing `import`/`export` statements are + // not permitted. Validated here as each direct statement is parsed (no second pass). + if in_ts_namespace_body { + p.check_namespace_body_statement(&stmt); } - } else { - stmt - }; - // In an internal namespace body, module-referencing `import`/`export` statements are - // not permitted. Validated here as each direct statement is parsed (no second pass). - if in_ts_namespace_body { - self.check_namespace_body_statement(&stmt); - } - if is_ambient_block - && !reported_ambient_statement - && !stmt.is_declaration() - && !stmt.is_module_declaration() - { - self.error(diagnostics::statement_in_ambient_context(stmt.span())); - reported_ambient_statement = true; + if is_ambient_block + && !reported_ambient_statement + && !stmt.is_declaration() + && !stmt.is_module_declaration() + { + p.error(diagnostics::statement_in_ambient_context(stmt.span())); + reported_ambient_statement = true; + } + statement_index += 1; + return Some(stmt); } - statements.push(stmt); - } + None + }); (directives, statements) } @@ -279,17 +280,17 @@ impl<'a, C: Config> ParserImpl<'a, C> { } /// Section 14.2 Block Statement - pub(crate) fn parse_block(&mut self) -> ArenaBox<'a, BlockStatement<'a>> { + pub(crate) fn parse_block(&mut self) -> BlockStatement<'a> { let start = self.cur_start(); let body = self.parse_normal_list(Kind::LCurly, Kind::RCurly, |p| { p.parse_statement_list_item(StatementContext::StatementList) }); - BlockStatement::boxed(self.end_span(start), body, self) + BlockStatement::new(self.end_span(start), body, self) } pub(crate) fn parse_block_statement(&mut self) -> Statement<'a> { let block = self.parse_block(); - Statement::BlockStatement(block) + Statement::BlockStatement(self.alloc(block)) } /// Section 14.3.2 Variable Statement @@ -422,8 +423,7 @@ impl<'a, C: Config> ParserImpl<'a, C> { // `for (let` let decl_start = self.cur_start(); // disallow `for (let in ...` - if self.lexer.peek_token().kind().is_after_let() { - self.bump_any(); // bump `let` + if self.eat_if_next(|next| next.kind().is_after_let()) { return self.parse_variable_declaration_for_statement( for_start, decl_start, @@ -794,23 +794,22 @@ impl<'a, C: Config> ParserImpl<'a, C> { } }; self.expect(Kind::Colon); - let mut consequent = ArenaVec::new_in(self); - loop { - let kind = self.cur_kind(); + let consequent = self.collect_list(|p| { + let kind = p.cur_kind(); if matches!( kind, Kind::Case | Kind::Default | Kind::RCurly | Kind::Eof | Kind::Undetermined - ) || self.fatal_error.is_some() + ) || p.fatal_error.is_some() { - break; + return None; } - let stmt = self.parse_statement_list_item(StatementContext::StatementList); + let stmt = p.parse_statement_list_item(StatementContext::StatementList); if let Statement::VariableDeclaration(var_decl) = &stmt && var_decl.kind.is_using() { // It is a Syntax Error if UsingDeclaration is contained directly within the StatementList of either a CaseClause or DefaultClause. // It is a Syntax Error if AwaitUsingDeclaration is contained directly within the StatementList of either a CaseClause or DefaultClause. - self.error(if var_decl.kind.is_await_using() { + p.error(if var_decl.kind.is_await_using() { diagnostics::await_using_declaration_not_allowed_in_switch_bare_case( stmt.span(), ) @@ -818,8 +817,8 @@ impl<'a, C: Config> ParserImpl<'a, C> { diagnostics::using_declaration_not_allowed_in_switch_bare_case(stmt.span()) }); } - consequent.push(stmt); - } + Some(stmt) + }); SwitchCase::new(self.end_span(start), test, consequent, self) } @@ -845,10 +844,14 @@ impl<'a, C: Config> ParserImpl<'a, C> { self.bump_any(); // bump `try` let block = self.parse_block(); + let block = self.alloc(block); let handler = self.at(Kind::Catch).then(|| self.parse_catch_clause()); - let finalizer = self.eat(Kind::Finally).then(|| self.parse_block()); + let finalizer = self.eat(Kind::Finally).then(|| { + let block = self.parse_block(); + self.alloc(block) + }); if handler.is_none() && finalizer.is_none() { let range = Span::empty(block.span.end); @@ -869,6 +872,7 @@ impl<'a, C: Config> ParserImpl<'a, C> { None }; let body = self.parse_block(); + let body = self.alloc(body); let param = pattern.map(|(pattern, type_annotation)| { CatchParameter::new( Span::new( @@ -906,12 +910,17 @@ impl<'a, C: Config> ParserImpl<'a, C> { /// Parse import statement or import expression. fn parse_import_statement(&mut self, stmt_ctx: StatementContext) -> Statement<'a> { let start = self.cur_start(); - if matches!(self.lexer.peek_token().kind(), Kind::Dot | Kind::LParen) { + // An `import` which starts a statement nearly always starts a declaration. + // Keep the token read after it, instead of reading it again. + let checkpoint = self.lexer.checkpoint(); + let next = self.lexer.next_token(); + if matches!(next.kind(), Kind::Dot | Kind::LParen) { + self.lexer.rewind(checkpoint); // Parse the whole expression `import.meta.url`. self.parse_expression_or_labeled_statement() } else { self.check_module_declaration(stmt_ctx); - self.bump_any(); // bump `import` + self.advance_to(next); // bump `import` self.parse_import_declaration(start, self.ctx.has_top_level()) } } diff --git a/vendor/oxc_parser/src/jsx/mod.rs b/vendor/oxc_parser/src/jsx/mod.rs index 98b20e6ec..b80fd77fa 100644 --- a/vendor/oxc_parser/src/jsx/mod.rs +++ b/vendor/oxc_parser/src/jsx/mod.rs @@ -5,7 +5,10 @@ use oxc_ast::ast::*; use oxc_span::{GetSpan, Span}; use oxc_str::Str; -use crate::{ParserConfig as Config, ParserImpl, diagnostics, lexer::Kind}; +use crate::{ + ParserConfig as Config, ParserImpl, cursor::ParserCheckpoint, diagnostics, js::Tristate, + lexer::Kind, +}; /// Represents either a closing JSX element or fragment. enum JSXClosing<'a> { @@ -25,6 +28,11 @@ impl<'a, C: Config> ParserImpl<'a, C> { pub(crate) fn parse_jsx_expression(&mut self) -> Expression<'a> { let start = self.cur_start(); self.bump_any(); // bump `<` + self.parse_jsx_expression_after_l_angle(start) + } + + /// Parse a JSX element or fragment whose `<` has been consumed. + fn parse_jsx_expression_after_l_angle(&mut self, start: u32) -> Expression<'a> { let kind = self.cur_kind(); let expr = if kind == Kind::RAngle { Expression::JSXFragment(self.parse_jsx_fragment(start, false)) @@ -33,15 +41,99 @@ impl<'a, C: Config> ParserImpl<'a, C> { } else { return self.unexpected(); }; + self.check_adjacent_jsx_elements(); + expr + } - // A top-level JSX element/fragment immediately followed by `<` is a second, - // adjacent JSX element that isn't wrapped in an enclosing tag, e.g. - // `
`. + /// A top-level JSX element/fragment immediately followed by `<` is a second, + /// adjacent JSX element that isn't wrapped in an enclosing tag, e.g. + /// `
`. + #[inline] + fn check_adjacent_jsx_elements(&mut self) { if self.at(Kind::LAngle) && self.fatal_error.is_none() { self.set_fatal_error(diagnostics::adjacent_jsx_elements(self.cur_token().span())); } + } - expr + /// Parse the JSX element or fragment, or the arrow function with type parameters, + /// that the `<` at the start of an `AssignmentExpression` begins in a TSX file. + /// + /// JSX files have no type parameters, so use [`Self::parse_jsx_expression`] instead. + /// + /// ```text + /// JSXFragment : `<` `>` JSXChildren? `<` `/` `>` + /// JSXOpeningElement : `<` JSXElementName TypeArguments? JSXAttributes? `/`? `>` + /// ArrowFunction : `<` TypeParameter (`,` TypeParameter)* `,`? `>` ArrowFormalParameters `=>` ConciseBody + /// TypeParameter : `const`? BindingIdentifier (`extends` Type)? (`=` Type)? + /// ``` + /// + /// The two differ at the token after the name, which a JSX element reads anyway, see + /// [`Self::is_generic_arrow_function_expression_after_jsx_name`]. So parse `<` and the name + /// as JSX, and go back to `<` only if `,`, `=` or `extends` follows the name. Every other + /// JSX element or fragment is parsed without reading a token twice. + /// + /// Returns the expression, and whether it is an arrow function. + pub(crate) fn parse_jsx_expression_or_generic_arrow_function( + &mut self, + allow_return_type_in_arrow_function: bool, + ) -> (Expression<'a>, bool) { + debug_assert!(self.at(Kind::LAngle) && self.source_type.is_jsx() && self.is_ts); + let checkpoint = self.checkpoint(); + let start = self.cur_start(); + self.bump_any(); // `<` + let kind = self.cur_kind(); + + // `() => …`, or an element named `const`. + if kind == Kind::Const { + self.bump_any(); // `const` + self.bump_any(); // the name + let arrow = self.is_generic_arrow_function_expression_after_jsx_name(); + return self.parse_generic_arrow_function_or_jsx_expression( + checkpoint, + arrow, + allow_return_type_in_arrow_function, + ); + } + + // `<>`, or a name which cannot be the name of a type parameter: ``. + (self.parse_jsx_expression_after_l_angle(start), false) + } + + /// Go back to the `<` at `checkpoint`, and parse the arrow function whose type parameters + /// it starts according to `arrow`. If it does not start one, parse a JSX element. + fn parse_generic_arrow_function_or_jsx_expression( + &mut self, + checkpoint: ParserCheckpoint<'a>, + arrow: Tristate, + allow_return_type_in_arrow_function: bool, + ) -> (Expression<'a>, bool) { + self.rewind(checkpoint); + match self + .parse_generic_arrow_function_expression(arrow, allow_return_type_in_arrow_function) + { + Some(arrow) => (arrow, true), + None => (self.parse_jsx_expression(), false), + } } /// `JSXFragment` : @@ -80,7 +172,19 @@ impl<'a, C: Config> ParserImpl<'a, C> { start: u32, in_jsx_child: bool, ) -> ArenaBox<'a, JSXElement<'a>> { - let (opening_element, self_closing) = self.parse_jsx_opening_element(start, in_jsx_child); + let name = self.parse_jsx_element_name(); + self.parse_jsx_element_rest(start, name, in_jsx_child) + } + + /// Parse the rest of a `JSXElement` after the `JSXElementName` of its opening element. + fn parse_jsx_element_rest( + &mut self, + start: u32, + name: JSXElementName<'a>, + in_jsx_child: bool, + ) -> ArenaBox<'a, JSXElement<'a>> { + let (opening_element, self_closing) = + self.parse_jsx_opening_element(start, name, in_jsx_child); let (children, closing_element) = if self_closing { (ArenaVec::new_in(self), None) } else { @@ -112,15 +216,17 @@ impl<'a, C: Config> ParserImpl<'a, C> { /// `JSXOpeningElement` : /// < `JSXElementName` `JSXAttributes_opt` > + /// + /// The cursor is after `name`. fn parse_jsx_opening_element( &mut self, start: u32, + name: JSXElementName<'a>, in_jsx_child: bool, ) -> ( ArenaBox<'a, JSXOpeningElement<'a>>, bool, // `true` if self-closing ) { - let name = self.parse_jsx_element_name(); // for tsx let type_arguments = if self.is_ts { self.try_parse_type_arguments() } else { None }; let attributes = self.parse_jsx_attributes(); @@ -142,7 +248,19 @@ impl<'a, C: Config> ParserImpl<'a, C> { fn parse_jsx_element_name(&mut self) -> JSXElementName<'a> { let start = self.cur_start(); let (identifier, contains_dash) = self.parse_jsx_identifier(); + self.parse_jsx_element_name_rest(start, identifier, contains_dash) + } + /// Parse the rest of a `JSXElementName` after its first `JSXIdentifier`, which starts + /// at `start`. + #[expect(clippy::inline_always)] + #[inline(always)] // One body for the two ways the first identifier is read. + fn parse_jsx_element_name_rest( + &mut self, + start: u32, + identifier: JSXIdentifier<'a>, + contains_dash: bool, + ) -> JSXElementName<'a> { // if self.eat(Kind::Colon) { let (property, _) = self.parse_jsx_identifier(); @@ -252,81 +370,63 @@ impl<'a, C: Config> ParserImpl<'a, C> { &mut self, in_jsx_child: bool, ) -> (ArenaVec<'a, JSXChild<'a>>, JSXClosing<'a>) { - let mut children = ArenaVec::new_in(self); - let closing = self.parse_jsx_children_and_closing_into(&mut children, in_jsx_child); - (children, closing) - } - - #[expect(clippy::inline_always)] - #[inline(always)] - fn parse_jsx_children_and_closing_into( - &mut self, - children: &mut ArenaVec<'a, JSXChild<'a>>, - in_jsx_child: bool, - ) -> JSXClosing<'a> { - loop { - if self.fatal_error.is_some() { + let mut closing = None; + let children = self.collect_list(|p| { + if p.fatal_error.is_some() { // Return dummy closing fragment on fatal error - let closing = JSXClosingFragment::new(self.cur_token().span(), self); - return JSXClosing::Fragment(closing); + let fragment = JSXClosingFragment::new(p.cur_token().span(), p); + closing = Some(JSXClosing::Fragment(fragment)); + return None; } - match self.cur_kind() { + let child = match p.cur_kind() { Kind::LAngle => { - let start = self.cur_start(); - self.bump_any(); // bump `<` - let kind = self.cur_kind(); + let start = p.cur_start(); + p.bump_any(); // bump `<` + let kind = p.cur_kind(); // <> open nested fragment if kind == Kind::RAngle { - let child = JSXChild::Fragment(self.parse_jsx_fragment(start, true)); - children.push(child); - continue; - } - - // { - let start = self.cur_start(); - self.bump_any(); // bump `{` + let start = p.cur_start(); + p.bump_any(); // bump `{` // {...expr} - if self.eat(Kind::Dot3) { - let child = JSXChild::Spread(self.parse_jsx_spread_child(start)); - children.push(child); - continue; + if p.eat(Kind::Dot3) { + JSXChild::Spread(p.parse_jsx_spread_child(start)) + } else { + // {expr} + JSXChild::ExpressionContainer( + p.parse_jsx_expression_container(start, /* in_jsx_child */ true), + ) } - // {expr} - let child = JSXChild::ExpressionContainer( - self.parse_jsx_expression_container(start, /* in_jsx_child */ true), - ); - children.push(child); } // text - Kind::JSXText => { - let child = JSXChild::Text(self.parse_jsx_text()); - children.push(child); - } + Kind::JSXText => JSXChild::Text(p.parse_jsx_text()), _ => { // Unexpected token in JSX children - return self.unexpected(); + closing = Some(p.unexpected()); + return None; } - } - } + }; + Some(child) + }); + (children, closing.unwrap()) } /// Parses the closing element or fragment after ` ParserImpl<'a, C> { /// `JSXSpreadAttribute` `JSXAttributes_opt` /// `JSXAttribute` `JSXAttributes_opt` fn parse_jsx_attributes(&mut self) -> ArenaVec<'a, JSXAttributeItem<'a>> { - let mut attributes = ArenaVec::new_in(self); - loop { - let kind = self.cur_kind(); - if matches!(kind, Kind::LAngle | Kind::RAngle | Kind::Slash) - || self.fatal_error.is_some() + self.collect_list(|p| { + let kind = p.cur_kind(); + if matches!(kind, Kind::LAngle | Kind::RAngle | Kind::Slash) || p.fatal_error.is_some() { - break; + return None; } let attribute = match kind { - Kind::LCurly => { - JSXAttributeItem::SpreadAttribute(self.parse_jsx_spread_attribute()) - } - _ => JSXAttributeItem::Attribute(self.parse_jsx_attribute()), + Kind::LCurly => JSXAttributeItem::SpreadAttribute(p.parse_jsx_spread_attribute()), + _ => JSXAttributeItem::Attribute(p.parse_jsx_attribute()), }; - attributes.push(attribute); - } - attributes + Some(attribute) + }) } /// `JSXAttribute` : @@ -512,7 +607,6 @@ impl<'a, C: Config> ParserImpl<'a, C> { JSXIdentifier<'a>, // JSX identifier bool, // `true` if contains `-`, or if parsing failed (see below) ) { - let start = self.cur_start(); let kind = self.cur_kind(); if kind != Kind::Ident && !kind.is_any_keyword() { // Return `contains_dash = true`, so that `parse_jsx_element_name` does not read the first byte @@ -520,21 +614,31 @@ impl<'a, C: Config> ParserImpl<'a, C> { // but on this path its `fatal_error` call is a no-op, because a fatal error has already been recorded. return (self.unexpected(), true); } + let (span, name, contains_dash) = self.bump_jsx_identifier(); + (JSXIdentifier::new(span, name, self), contains_dash) + } + + /// Consume the `JSXIdentifier` at the cursor, which is at an identifier or keyword. + /// + /// Returns its span and its name, and `true` if it contains `-`. No node is created. + #[expect(clippy::inline_always)] + #[inline(always)] // A piece of `parse_jsx_identifier`, not a call from it. + fn bump_jsx_identifier(&mut self) -> (Span, &'a str, bool) { + debug_assert!(self.at(Kind::Ident) || self.cur_kind().is_any_keyword()); // Currently at a valid normal Ident or Keyword, keep on lexing for `-` in `` let contains_dash = self.continue_lex_jsx_identifier(); + let span = self.cur_token().span(); + let name = self.cur_src(); self.bump_any(); - let span = self.end_span(start); - let name = span.source_text(self.source_text); - let identifier = JSXIdentifier::new(span, name, self); - (identifier, contains_dash) + (span, name, contains_dash) } fn parse_jsx_text(&mut self) -> ArenaBox<'a, JSXText<'a>> { let span = self.cur_token().span(); + // `JSXText` has no escapes, so its value is its source text. let raw = Str::from(self.cur_src()); - let value = Str::from(self.cur_string()); self.bump_any(); - JSXText::boxed(span, value, Some(raw), self) + JSXText::boxed(span, raw, Some(raw), self) } fn jsx_element_name_eq(lhs: &JSXElementName<'a>, rhs: &JSXElementName<'a>) -> bool { diff --git a/vendor/oxc_parser/src/lexer/byte_handlers.rs b/vendor/oxc_parser/src/lexer/byte_handlers.rs index 01dfe7149..84df8e038 100644 --- a/vendor/oxc_parser/src/lexer/byte_handlers.rs +++ b/vendor/oxc_parser/src/lexer/byte_handlers.rs @@ -6,7 +6,7 @@ use crate::{ diagnostics, }; -use super::{Kind, Lexer}; +use super::{FinishTokenMode, Kind, Lexer, SourcePosition, Token, numeric::ends_decimal_integer}; impl Lexer<'_, C> { /// Handle next byte of source. @@ -20,29 +20,49 @@ impl Lexer<'_, C> { #[expect(clippy::inline_always)] #[inline(always)] pub(super) unsafe fn handle_byte(&mut self, byte: u8) -> Kind { - // Bypass indirect dispatch for these common one-byte tokens. - // Keep this match small: adding other handlers regressed ARM64 parser benchmarks - // through extra dispatch work and reduced inlining into parser callers. - // Re-benchmark before extending this set. - let kind = match byte { - b'(' => Kind::LParen, - b')' => Kind::RParen, - b';' => Kind::Semicolon, - _ => { - let byte_handlers = self.config.byte_handlers(); - // SAFETY: Caller guarantees to uphold safety invariants. - return unsafe { byte_handlers[byte as usize](self) }; - } - }; - - // SAFETY: Caller guarantees `byte` is the current source byte, and these are single-byte ASCII characters. - let next = unsafe { self.source.position().add(1) }; - self.source.set_position(next); - kind + if let Some(kind) = single_byte_token(byte) { + // SAFETY: Caller guarantees `byte` is the current source byte, and single-byte tokens are ASCII. + let next = unsafe { self.source.position().add(1) }; + self.source.set_position(next); + return kind; + } + let byte_handlers = self.config.byte_handlers(); + // SAFETY: Caller guarantees to uphold safety invariants. + unsafe { byte_handlers[byte as usize](self, self.source.position()).0 } } } -pub type ByteHandler = unsafe fn(&mut Lexer<'_, C>) -> Kind; +/// `Kind` of a token which is always exactly the single byte `byte`, if there is one. +/// These tokens are completed without an indirect call to a byte handler. +#[expect(clippy::inline_always)] +#[inline(always)] +pub(super) fn single_byte_token(byte: u8) -> Option { + let kind = SINGLE_BYTE_TOKENS[byte as usize]; + if kind == Kind::Eof { None } else { Some(kind) } +} + +/// `>` is included because `>=`, `>>` etc are produced by re-lexing (see `re_lex_right_angle`). +static SINGLE_BYTE_TOKENS: [Kind; 256] = { + let mut table = [Kind::Eof; 256]; + table[b'(' as usize] = Kind::LParen; + table[b')' as usize] = Kind::RParen; + table[b';' as usize] = Kind::Semicolon; + table[b',' as usize] = Kind::Comma; + table[b':' as usize] = Kind::Colon; + table[b'[' as usize] = Kind::LBrack; + table[b']' as usize] = Kind::RBrack; + table[b'{' as usize] = Kind::LCurly; + table[b'}' as usize] = Kind::RCurly; + table[b'~' as usize] = Kind::Tilde; + table[b'@' as usize] = Kind::At; + table[b'>' as usize] = Kind::RAngle; + table +}; + +/// Byte handlers take and return the current position of `lexer.source`, so it stays in a register +/// between tokens instead of being stored and reloaded. +pub type ByteHandler = + for<'a> unsafe fn(&mut Lexer<'a, C>, SourcePosition<'a>) -> (Kind, SourcePosition<'a>); pub type ByteHandlers = [ByteHandler; 256]; /// Macro to create a lookup table mapping any incoming byte to a handler function defined below. @@ -54,12 +74,12 @@ macro_rules! byte_handlers { // 0 1 2 3 4 5 6 7 8 9 A B C D E F // ERR, ERR, ERR, ERR, ERR, ERR, ERR, ERR, ERR, SPS, LIN, ISP, ISP, LIN, ERR, ERR, // 0 ERR, ERR, ERR, ERR, ERR, ERR, ERR, ERR, ERR, ERR, ERR, ERR, ERR, ERR, ERR, ERR, // 1 - SPS, EXL, QOD, HAS, IDT, PRC, AMP, QOS, UER, UER, ATR, PLS, COM, MIN, PRD, SLH, // 2 - ZER, DIG, DIG, DIG, DIG, DIG, DIG, DIG, DIG, DIG, COL, UER, LSS, EQL, GTR, QST, // 3 - AT_, IDT, IDT, IDT, IDT, IDT, IDT, IDT, IDT, IDT, IDT, IDT, IDT, IDT, IDT, IDT, // 4 - IDT, IDT, IDT, IDT, IDT, IDT, IDT, IDT, IDT, IDT, IDT, BTO, ESC, BTC, CRT, IDT, // 5 - TPL, L_A, L_B, L_C, L_D, L_E, L_F, L_G, IDT, L_I, IDT, L_K, L_L, L_M, L_N, L_O, // 6 - L_P, IDT, L_R, L_S, L_T, L_U, L_V, L_W, IDT, L_Y, IDT, BEO, PIP, BEC, TLD, ERR, // 7 + SPS, EXL, QOD, HAS, IDT, PRC, AMP, QOS, UER, UER, ATR, PLS, UER, MIN, PRD, SLH, // 2 + ZER, DIG, DIG, DIG, DIG, DIG, DIG, DIG, DIG, DIG, UER, UER, LSS, EQL, UER, QST, // 3 + UER, IDT, IDT, IDT, IDT, IDT, IDT, IDT, IDT, IDT, IDT, IDT, IDT, IDT, IDT, IDT, // 4 + IDT, IDT, IDT, IDT, IDT, IDT, IDT, IDT, IDT, IDT, IDT, UER, ESC, UER, CRT, IDT, // 5 + TPL, KWD, KWD, KWD, KWD, KWD, KWD, KWD, IDT, KWD, IDT, KWD, KWD, KWD, KWD, KWD, // 6 + KWD, IDT, KWD, KWD, KWD, KWD, KWD, KWD, IDT, KWD, IDT, UER, PIP, UER, UER, ERR, // 7 UER, UER, UER, UER, UER, UER, UER, UER, UER, UER, UER, UER, UER, UER, UER, UER, // 8 UER, UER, UER, UER, UER, UER, UER, UER, UER, UER, UER, UER, UER, UER, UER, UER, // 9 UER, UER, UER, UER, UER, UER, UER, UER, UER, UER, UER, UER, UER, UER, UER, UER, // A @@ -80,6 +100,308 @@ pub mod byte_handler_tables { pub static RUNTIME_TOKENS: ByteHandlers = byte_handlers!(); } +/// Token handlers take the position of the first byte of a token, and return the completed token. +/// +/// # SAFETY +/// All token handlers have the same requirements. `Lexer::next_token_impl` upholds them. +/// * `pos` must be the position of a byte which selects the handler in `Lexer::TOKEN_HANDLERS`. +/// * At least `TOKEN_HANDLER_MIN_BYTES` bytes of source must remain from `pos`. +/// * No whitespace or comments must have been seen since the previous token, other than +/// a single space. +type TokenHandler = for<'a> unsafe fn(&mut Lexer<'a, C>, SourcePosition<'a>) -> Token; + +/// Token handlers, each named after the byte handler for the same byte. +/// See [`TokenHandler`] for what callers must guarantee. +mod token_handlers { + use super::{Config, Kind, Lexer, SourcePosition, Token, ends_decimal_integer}; + + impl Lexer<'_, C> { + /// Lookup table mapping any byte to the token handler for tokens which start with that byte. + /// + /// Token handlers are generic over the lexer's config, and a `static` cannot be generic, + /// so the table is an associated constant. `&Self::TOKEN_HANDLERS` is a reference to + /// static memory, so getting a handler from the table is a single load, as with a `static`. + /// + /// Defined in this module so that the names in `byte_handlers!` refer to the token handlers. + pub(in crate::lexer) const TOKEN_HANDLERS: [super::TokenHandler; 256] = byte_handlers!(); + } + + /// Define token handlers which call the byte handler of the same name, then finish the token. + /// + /// * `fresh` is for byte handlers which only ever produce a token, without flags. + /// They must not return `Kind::Skip`, nor alter `lexer.pending`. + /// * `zero` is for the byte handler for `0`. A lone `0` is the most common number which + /// starts with it, and is finished without calling the byte handler. + /// * `string` is for the byte handlers for quotes. A string which contains no escapes has + /// no flags, and is finished without calling the byte handler. Other strings are uncommon, + /// and are finished from where the first escape in them is found. + /// * `general` is for all other byte handlers. + macro_rules! token_handlers { + (fresh: $($name:ident),+ $(,)?) => { + $( + #[expect(non_snake_case)] + pub unsafe fn $name<'a, C: Config>( + lexer: &mut Lexer<'a, C>, + pos: SourcePosition<'a>, + ) -> Token { + let (kind, end) = super::$name(lexer, pos); + lexer.finish_fresh_token(kind, pos, end) + } + )+ + }; + (zero: $($name:ident),+ $(,)?) => { + $( + #[expect(non_snake_case)] + pub unsafe fn $name<'a, C: Config>( + lexer: &mut Lexer<'a, C>, + pos: SourcePosition<'a>, + ) -> Token { + // SAFETY: Caller guarantees `TOKEN_HANDLER_MIN_BYTES` bytes can be read + // from `pos`. A digit is ASCII, so `pos + 1` is on a UTF-8 char boundary. + let (after_digit, next_byte) = unsafe { + let after_digit = pos.add(1); + (after_digit, after_digit.read()) + }; + if ends_decimal_integer(next_byte) { + lexer.source.set_position(after_digit); + return lexer.finish_fresh_token(Kind::Decimal, pos, after_digit); + } + // Decimal points, other radixes, legacy octal. + // SAFETY: Caller guarantees `pos` is the position of a byte which this handler, + // and so the byte handler of the same name, is for. + unsafe { lexer.token_from_byte_handler(pos, super::$name) } + } + )+ + }; + (string: $($name:ident => $read_plain_string:ident, $string_token_rest:ident);+ $(;)?) => { + $( + #[expect(non_snake_case)] + pub unsafe fn $name<'a, C: Config>( + lexer: &mut Lexer<'a, C>, + pos: SourcePosition<'a>, + ) -> Token { + // SAFETY: Caller guarantees `pos` is the position of the quote + // which this handler, and so `$read_plain_string`, is for + match unsafe { lexer.$read_plain_string(pos) } { + Ok(end) => lexer.finish_fresh_token(Kind::Str, pos, end), + // SAFETY: As above, and position of source has not been altered since + Err(next_byte) => unsafe { lexer.$string_token_rest(pos, next_byte) }, + } + } + )+ + }; + (general: $($name:ident),+ $(,)?) => { + $( + #[expect(non_snake_case)] + pub unsafe fn $name<'a, C: Config>( + lexer: &mut Lexer<'a, C>, + pos: SourcePosition<'a>, + ) -> Token { + // SAFETY: Caller guarantees `pos` is the position of a byte which this handler, + // and so the byte handler of the same name, is for + unsafe { lexer.general_token_handler(pos, super::$name) } + } + )+ + }; + } + + token_handlers!(fresh: AMP, ATR, CRT, EXL, PIP, PLS, PRC, QST); + + token_handlers!(zero: ZER); + + token_handlers!( + string: + QOD => read_plain_string_literal_double_quote, string_token_rest_double_quote; + QOS => read_plain_string_literal_single_quote, string_token_rest_single_quote; + ); + + token_handlers!( + general: ERR, ESC, HAS, ISP, SLH, SPS, TPL, UER, UNI, + ); + + // `A..=Z`, `h`, `j`, `q`, `x`, `z`, `_`, `$`: no keyword starts with these bytes. + #[expect(non_snake_case)] + pub unsafe fn IDT<'a, C: Config>(lexer: &mut Lexer<'a, C>, pos: SourcePosition<'a>) -> Token { + // SAFETY: Caller guarantees `pos` is the position of an ASCII identifier-start byte, + // and that no trivia has been seen, other than one space + unsafe { lexer.identifier_token::(pos) } + } + + // All first letters which can begin a keyword. + #[expect(non_snake_case)] + pub unsafe fn KWD<'a, C: Config>(lexer: &mut Lexer<'a, C>, pos: SourcePosition<'a>) -> Token { + // SAFETY: Caller guarantees `pos` is the position of an ASCII identifier-start byte, + // and that no trivia has been seen, other than one space + unsafe { lexer.identifier_token::(pos) } + } + + // `\r` `\n` + #[expect(non_snake_case)] + pub unsafe fn LIN<'a, C: Config>(lexer: &mut Lexer<'a, C>, pos: SourcePosition<'a>) -> Token { + // SAFETY: Caller guarantees `pos` is the position of a line break byte, + // and that no trivia has been seen, other than one space + unsafe { lexer.line_break_token(pos) } + } + + // `.` + // + // Almost always a property access, where what follows is an identifier. + #[expect(non_snake_case)] + pub unsafe fn PRD<'a, C: Config>(lexer: &mut Lexer<'a, C>, pos: SourcePosition<'a>) -> Token { + // SAFETY: Caller guarantees `TOKEN_HANDLER_MIN_BYTES` bytes can be read from `pos`. + // `.` is ASCII, so `pos + 1` is on a UTF-8 char boundary. + let (after_dot, next_byte) = unsafe { + let after_dot = pos.add(1); + (after_dot, after_dot.read()) + }; + // `.` or a digit means `...` or a number. `/` also takes this branch, which is harmless. + if next_byte.wrapping_sub(b'.') <= b'9' - b'.' { + // SAFETY: Caller guarantees `pos` is the position of `.`, which `PRD` is for + return unsafe { lexer.token_from_byte_handler(pos, super::PRD) }; + } + lexer.source.set_position(after_dot); + lexer.finish_fresh_token(Kind::Dot, pos, after_dot) + } + + // `1` to `9` + // + // Most numbers are integers of a few digits, particularly in minified code. + // They have no flags, and are finished without calling the byte handler. + #[expect(non_snake_case)] + pub unsafe fn DIG<'a, C: Config>(lexer: &mut Lexer<'a, C>, pos: SourcePosition<'a>) -> Token { + // SAFETY: Caller guarantees `TOKEN_HANDLER_MIN_BYTES` bytes can be read from `pos`. + // A digit is ASCII, so `pos + 1` is on a UTF-8 char boundary. + let (mut end, mut byte) = unsafe { + let after_digit = pos.add(1); + (after_digit, after_digit.read()) + }; + while byte.is_ascii_digit() { + // SAFETY: `byte` is the byte at `end`, and it is ASCII, so `end + 1` is in bounds + // and on a UTF-8 char boundary + end = unsafe { end.add(1) }; + if !end.is_not_end_of(&lexer.source) { + // A number at the very end of the source. Any byte which does not end a number. + byte = b'.'; + break; + } + // SAFETY: `end` is not the end of the source + byte = unsafe { end.read() }; + } + if ends_decimal_integer(byte) { + lexer.source.set_position(end); + return lexer.finish_fresh_token(Kind::Decimal, pos, end); + } + // Decimal points, exponents, separators, BigInts + // SAFETY: Caller guarantees `pos` is the position of a digit, which `DIG` is for + unsafe { lexer.token_from_byte_handler(pos, super::DIG) } + } + + // `<` + // + // Usually a comparison, or the start of type arguments or a JSX element. + #[expect(non_snake_case)] + pub unsafe fn LSS<'a, C: Config>(lexer: &mut Lexer<'a, C>, pos: SourcePosition<'a>) -> Token { + // SAFETY: Caller guarantees `TOKEN_HANDLER_MIN_BYTES` bytes can be read from `pos`. + // `<` is ASCII, so `pos + 1` is on a UTF-8 char boundary. + let (after_angle, next_byte) = unsafe { + let after_angle = pos.add(1); + (after_angle, after_angle.read()) + }; + // `<<`, `<=`, or an HTML comment `` + if matches!(next_byte, b'-' | b'=') { + // SAFETY: Caller guarantees `pos` is the position of `-`, which `MIN` is for + return unsafe { lexer.token_from_byte_handler(pos, super::MIN) }; + } + lexer.source.set_position(after_minus); + lexer.finish_fresh_token(Kind::Minus, pos, after_minus) + } + + // `=` + // + // Almost always an assignment, where what follows is a space or the start of an expression. + #[expect(non_snake_case)] + pub unsafe fn EQL<'a, C: Config>(lexer: &mut Lexer<'a, C>, pos: SourcePosition<'a>) -> Token { + // SAFETY: Caller guarantees `TOKEN_HANDLER_MIN_BYTES` bytes can be read from `pos`. + // `=` is ASCII, so `pos + 1` is on a UTF-8 char boundary. + let (after_eq, next_byte) = unsafe { + let after_eq = pos.add(1); + (after_eq, after_eq.read()) + }; + if matches!(next_byte, b'=' | b'>') { + let (kind, end) = super::EQL(lexer, pos); + return lexer.finish_fresh_token(kind, pos, end); + } + lexer.source.set_position(after_eq); + lexer.finish_fresh_token(Kind::Eq, pos, after_eq) + } +} + +impl<'a, C: Config> Lexer<'a, C> { + /// Call a byte handler for the first byte of a token, and finish the token it produces. + /// If it skips trivia instead, continue until a token is found. + /// + /// `pending` must reflect the trivia seen since the previous token. + /// + /// # SAFETY + /// * `pos` must not be the end of the source. + /// * `byte_handler` must be the byte handler for the byte at `pos`. + #[expect(clippy::inline_always)] + #[inline(always)] + unsafe fn general_token_handler( + &mut self, + pos: SourcePosition<'a>, + byte_handler: ByteHandler, + ) -> Token { + // The caller may have skipped a space without updating position of source + self.source.set_position(pos); + self.token_start = self.source.offset_of(pos); + // SAFETY: Caller guarantees `byte_handler` is for the byte at `pos` + let (kind, end) = unsafe { byte_handler(self, pos) }; + if kind == Kind::Skip { + return self.next_token_after_trivia(); + } + self.finish_next_inner(kind, end, FinishTokenMode::Push) + } + + /// Same as `general_token_handler`, but not inlined. + /// + /// For token handlers which finish most tokens themselves. They tail call this for the rest, + /// so the tokens they do finish do not pay for the stack frame which calling a byte handler + /// requires. + /// + /// # SAFETY + /// Same as `general_token_handler`. + #[inline(never)] + unsafe fn token_from_byte_handler( + &mut self, + pos: SourcePosition<'a>, + byte_handler: ByteHandler, + ) -> Token { + // SAFETY: Caller guarantees what `general_token_handler` requires + unsafe { self.general_token_handler(pos, byte_handler) } + } +} + /// Macro for defining byte handler for an ASCII character. /// /// Asserts that lexer is not at end of file, and that next char is ASCII. @@ -107,73 +429,36 @@ pub mod byte_handler_tables { /// /// ```rust,ignore /// #[expect(non_snake_case)] -/// fn SPS(lexer: &mut Lexer<'_, C>) -> Kind { +/// fn SPS<'a, C: Config>(lexer: &mut Lexer<'a, C>, pos: SourcePosition<'a>) -> (Kind, SourcePosition<'a>) { +/// lexer.source.set_position(pos); /// // SAFETY: This macro is only used for ASCII characters /// unsafe { /// assert_unchecked!(!lexer.source.is_eof()); /// assert_unchecked!(lexer.source.peek_byte_unchecked() < 128); /// } -/// { +/// let kind = { /// lexer.consume_char(); /// Kind::WhiteSpace -/// } +/// }; +/// (kind, lexer.source.position()) /// } /// ``` macro_rules! ascii_byte_handler { ($id:ident($lex:ident) $body:expr) => { #[expect(non_snake_case)] - fn $id($lex: &mut Lexer<'_, C>) -> Kind { + fn $id<'a, C: Config>( + $lex: &mut Lexer<'a, C>, + pos: SourcePosition<'a>, + ) -> (Kind, SourcePosition<'a>) { + // No-op store, so the compiler uses `pos` from register instead of reloading it + $lex.source.set_position(pos); // SAFETY: This macro is only used for ASCII characters unsafe { assert_unchecked!(!$lex.source.is_eof()); assert_unchecked!($lex.source.peek_byte_unchecked() < 128); } - $body - } - }; -} - -/// Macro for defining byte handler for an ASCII character which is start of an identifier -/// (`a`-`z`, `A`-`Z`, `$` or `_`). -/// -/// Macro calls `Lexer::identifier_name_handler` to get the text of the identifier, -/// minus its first character. -/// -/// `Lexer::identifier_name_handler` is an unsafe function, but if byte being consumed is ASCII, -/// its requirements are met. -/// -/// # SAFETY -/// Only use this macro to define byte handlers for ASCII characters. -/// -/// ```rust,ignore -/// ascii_identifier_handler!(L_G(id_without_first_char) match id_without_first_char.as_bytes() { -/// b"et" => Kind::Get, -/// b"lobal" => Kind::Global, -/// _ => Kind::Ident, -/// }); -/// ``` -/// -/// expands to: -/// -/// ```rust,ignore -/// #[expect(non_snake_case)] -/// fn L_G(lexer: &mut Lexer<'_, C>) -> Kind { -/// // SAFETY: This macro is only used for ASCII characters -/// let id_without_first_char = unsafe { lexer.identifier_name_handler() }; -/// match id_without_first_char.as_bytes() { -/// b"et" => Kind::Get, -/// b"lobal" => Kind::Global, -/// _ => Kind::Ident, -/// } -/// } -/// ``` -macro_rules! ascii_identifier_handler { - ($id:ident($str:ident) $body:expr) => { - #[expect(non_snake_case)] - fn $id(lexer: &mut Lexer<'_, C>) -> Kind { - // SAFETY: This macro is only used for ASCII characters - let $str = unsafe { lexer.identifier_name_handler() }; - $body + let kind = $body; + (kind, $lex.source.position()) } }; } @@ -193,15 +478,45 @@ ascii_byte_handler!(SPS(lexer) { // Irregular Whitespace ascii_byte_handler!(ISP(lexer) { lexer.consume_char(); - lexer.trivia_builder.add_irregular_whitespace(lexer.token.start(), lexer.offset()); + lexer.trivia_builder.add_irregular_whitespace(lexer.token_start, lexer.offset()); Kind::Skip }); // '\r' '\n' -ascii_byte_handler!(LIN(lexer) { +#[expect(non_snake_case)] +fn LIN<'a, C: Config>( + lexer: &mut Lexer<'a, C>, + pos: SourcePosition<'a>, +) -> (Kind, SourcePosition<'a>) { + lexer.source.set_position(pos); + // SAFETY: The byte-handler table calls this for an in-bounds ASCII line break. + unsafe { + assert_unchecked!(!lexer.source.is_eof()); + assert_unchecked!(lexer.source.peek_byte_unchecked() < 128); + } lexer.consume_char(); - lexer.line_break_handler() -}); + let byte = lexer.line_break_handler(); + + // Read the next token here to avoid restarting the caller's token loop. + let pos = lexer.source.position(); + lexer.token_start = lexer.source.offset_of(pos); + let Some(byte) = byte else { + return (Kind::Eof, pos); + }; + // JSX attribute values scan quotes differently. Leave them for the caller's token loop. + if matches!(byte, b'"' | b'\'') { + return (Kind::Skip, pos); + } + if let Some(kind) = single_byte_token(byte) { + // SAFETY: Single-byte tokens are ASCII and `pos` is in bounds. + let end = unsafe { pos.add(1) }; + lexer.source.set_position(end); + return (kind, end); + } + let byte_handlers = lexer.config.byte_handlers(); + // SAFETY: `byte` is the current source byte at `pos`. + unsafe { byte_handlers[byte as usize](lexer, pos) } +} // ! ascii_byte_handler!(EXL(lexer) { @@ -240,10 +555,25 @@ ascii_byte_handler!(HAS(lexer) { lexer.private_identifier() }); -// `A..=Z`, `a..=z` (except special cases below), `_`, `$` -ascii_identifier_handler!(IDT(_id_without_first_char) { - Kind::Ident -}); +// `A..=Z`, `h`, `j`, `q`, `x`, `z`, `_`, `$`: no keyword starts with these bytes. +#[expect(non_snake_case)] +fn IDT<'a, C: Config>( + lexer: &mut Lexer<'a, C>, + pos: SourcePosition<'a>, +) -> (Kind, SourcePosition<'a>) { + // SAFETY: This handler is only selected for ASCII identifier-start bytes. + unsafe { lexer.identifier_name_handler::(pos) } +} + +// Share one indirect-call target for all first letters which can begin a keyword. +#[expect(non_snake_case)] +fn KWD<'a, C: Config>( + lexer: &mut Lexer<'a, C>, + pos: SourcePosition<'a>, +) -> (Kind, SourcePosition<'a>) { + // SAFETY: This handler is only selected for ASCII identifier-start bytes. + unsafe { lexer.identifier_name_handler::(pos) } +} // % ascii_byte_handler!(PRC(lexer) { @@ -299,12 +629,6 @@ ascii_byte_handler!(PLS(lexer) { } }); -// , -ascii_byte_handler!(COM(lexer) { - lexer.consume_char(); - Kind::Comma -}); - // - ascii_byte_handler!(MIN(lexer) { lexer.consume_char(); @@ -352,12 +676,6 @@ ascii_byte_handler!(DIG(lexer) { lexer.decimal_literal_after_first_digit() }); -// : -ascii_byte_handler!(COL(lexer) { - lexer.consume_char(); - Kind::Colon -}); - // < ascii_byte_handler!(LSS(lexer) { lexer.consume_char(); @@ -380,13 +698,6 @@ ascii_byte_handler!(EQL(lexer) { } }); -// > -ascii_byte_handler!(GTR(lexer) { - lexer.consume_char(); - // `>=` is re-lexed with [Lexer::next_jsx_child] - Kind::RAngle -}); - // ? ascii_byte_handler!(QST(lexer) { lexer.consume_char(); @@ -415,29 +726,11 @@ ascii_byte_handler!(QST(lexer) { } }); -// @ -ascii_byte_handler!(AT_(lexer) { - lexer.consume_char(); - Kind::At -}); - -// [ -ascii_byte_handler!(BTO(lexer) { - lexer.consume_char(); - Kind::LBrack -}); - // \ ascii_byte_handler!(ESC(lexer) { lexer.identifier_backslash_handler() }); -// ] -ascii_byte_handler!(BTC(lexer) { - lexer.consume_char(); - Kind::RBrack -}); - // ^ ascii_byte_handler!(CRT(lexer) { lexer.consume_char(); @@ -454,12 +747,6 @@ ascii_byte_handler!(TPL(lexer) { lexer.read_template_literal(Kind::TemplateHead, Kind::NoSubstitutionTemplate) }); -// { -ascii_byte_handler!(BEO(lexer) { - lexer.consume_char(); - Kind::LCurly -}); - // | ascii_byte_handler!(PIP(lexer) { lexer.consume_char(); @@ -481,200 +768,19 @@ ascii_byte_handler!(PIP(lexer) { } }); -// } -ascii_byte_handler!(BEC(lexer) { - lexer.consume_char(); - Kind::RCurly -}); - -// ~ -ascii_byte_handler!(TLD(lexer) { - lexer.consume_char(); - Kind::Tilde -}); - -// Byte patterns let the compiler compare fixed-size chunks without calling a string comparison -// routine for keyword lengths that are not a power of two. -ascii_identifier_handler!(L_A(id_without_first_char) match id_without_first_char.as_bytes() { - b"wait" => Kind::Await, - b"sync" => Kind::Async, - b"bstract" => Kind::Abstract, - b"ccessor" => Kind::Accessor, - b"ny" => Kind::Any, - b"s" => Kind::As, - b"ssert" => Kind::Assert, - b"sserts" => Kind::Asserts, - _ => Kind::Ident, -}); - -ascii_identifier_handler!(L_B(id_without_first_char) match id_without_first_char.as_bytes() { - b"reak" => Kind::Break, - b"oolean" => Kind::Boolean, - b"igint" => Kind::BigInt, - _ => Kind::Ident, -}); - -ascii_identifier_handler!(L_C(id_without_first_char) match id_without_first_char.as_bytes() { - b"onst" => Kind::Const, - b"lass" => Kind::Class, - b"ontinue" => Kind::Continue, - b"atch" => Kind::Catch, - b"ase" => Kind::Case, - b"onstructor" => Kind::Constructor, - _ => Kind::Ident, -}); - -ascii_identifier_handler!(L_D(id_without_first_char) match id_without_first_char.as_bytes() { - b"o" => Kind::Do, - b"elete" => Kind::Delete, - b"eclare" => Kind::Declare, - b"efault" => Kind::Default, - b"ebugger" => Kind::Debugger, - b"efer" => Kind::Defer, - _ => Kind::Ident, -}); - -ascii_identifier_handler!(L_E(id_without_first_char) match id_without_first_char.as_bytes() { - b"lse" => Kind::Else, - b"num" => Kind::Enum, - b"xport" => Kind::Export, - b"xtends" => Kind::Extends, - _ => Kind::Ident, -}); - -ascii_identifier_handler!(L_F(id_without_first_char) match id_without_first_char.as_bytes() { - b"unction" => Kind::Function, - b"alse" => Kind::False, - b"or" => Kind::For, - b"inally" => Kind::Finally, - b"rom" => Kind::From, - _ => Kind::Ident, -}); - -ascii_identifier_handler!(L_G(id_without_first_char) match id_without_first_char.as_bytes() { - b"et" => Kind::Get, - b"lobal" => Kind::Global, - _ => Kind::Ident, -}); - -ascii_identifier_handler!(L_I(id_without_first_char) match id_without_first_char.as_bytes() { - b"f" => Kind::If, - b"nstanceof" => Kind::Instanceof, - b"n" => Kind::In, - b"mplements" => Kind::Implements, - b"mport" => Kind::Import, - b"nfer" => Kind::Infer, - b"nterface" => Kind::Interface, - b"ntrinsic" => Kind::Intrinsic, - b"s" => Kind::Is, - _ => Kind::Ident, -}); - -ascii_identifier_handler!(L_K(id_without_first_char) match id_without_first_char.as_bytes() { - b"eyof" => Kind::KeyOf, - _ => Kind::Ident, -}); - -ascii_identifier_handler!(L_L(id_without_first_char) match id_without_first_char.as_bytes() { - b"et" => Kind::Let, - _ => Kind::Ident, -}); - -ascii_identifier_handler!(L_M(id_without_first_char) match id_without_first_char.as_bytes() { - b"eta" => Kind::Meta, - b"odule" => Kind::Module, - _ => Kind::Ident, -}); - -ascii_identifier_handler!(L_N(id_without_first_char) match id_without_first_char.as_bytes() { - b"ull" => Kind::Null, - b"ew" => Kind::New, - b"umber" => Kind::Number, - b"amespace" => Kind::Namespace, - b"ever" => Kind::Never, - _ => Kind::Ident, -}); - -ascii_identifier_handler!(L_O(id_without_first_char) match id_without_first_char.as_bytes() { - b"f" => Kind::Of, - b"bject" => Kind::Object, - b"ut" => Kind::Out, - b"verride" => Kind::Override, - _ => Kind::Ident, -}); - -ascii_identifier_handler!(L_P(id_without_first_char) match id_without_first_char.as_bytes() { - b"ackage" => Kind::Package, - b"rivate" => Kind::Private, - b"rotected" => Kind::Protected, - b"ublic" => Kind::Public, - _ => Kind::Ident, -}); - -ascii_identifier_handler!(L_R(id_without_first_char) match id_without_first_char.as_bytes() { - b"eturn" => Kind::Return, - b"equire" => Kind::Require, - b"eadonly" => Kind::Readonly, - _ => Kind::Ident, -}); - -ascii_identifier_handler!(L_S(id_without_first_char) match id_without_first_char.as_bytes() { - b"et" => Kind::Set, - b"uper" => Kind::Super, - b"witch" => Kind::Switch, - b"tatic" => Kind::Static, - b"ymbol" => Kind::Symbol, - b"tring" => Kind::String, - b"atisfies" => Kind::Satisfies, - b"ource" => Kind::Source, - _ => Kind::Ident, -}); - -ascii_identifier_handler!(L_T(id_without_first_char) match id_without_first_char.as_bytes() { - b"his" => Kind::This, - b"rue" => Kind::True, - b"hrow" => Kind::Throw, - b"ry" => Kind::Try, - b"ypeof" => Kind::Typeof, - b"arget" => Kind::Target, - b"ype" => Kind::Type, - _ => Kind::Ident, -}); - -ascii_identifier_handler!(L_U(id_without_first_char) match id_without_first_char.as_bytes() { - b"ndefined" => Kind::Undefined, - b"sing" => Kind::Using, - b"nique" => Kind::Unique, - b"nknown" => Kind::Unknown, - _ => Kind::Ident, -}); - -ascii_identifier_handler!(L_V(id_without_first_char) match id_without_first_char.as_bytes() { - b"ar" => Kind::Var, - b"oid" => Kind::Void, - _ => Kind::Ident, -}); - -ascii_identifier_handler!(L_W(id_without_first_char) match id_without_first_char.as_bytes() { - b"hile" => Kind::While, - b"ith" => Kind::With, - _ => Kind::Ident, -}); - -ascii_identifier_handler!(L_Y(id_without_first_char) match id_without_first_char.as_bytes() { - b"ield" => Kind::Yield, - _ => Kind::Ident, -}); - // Non-ASCII characters. // // Note: Must not use `ascii_byte_handler!` macro, as this handler is for non-ASCII chars. #[expect(non_snake_case)] -fn UNI(lexer: &mut Lexer<'_, C>) -> Kind { - lexer.unicode_char_handler() +fn UNI<'a, C: Config>( + lexer: &mut Lexer<'a, C>, + _pos: SourcePosition<'a>, +) -> (Kind, SourcePosition<'a>) { + let kind = lexer.unicode_char_handler(); + (kind, lexer.source.position()) } -// Punctuation dispatched directly in `handle_byte`, and invalid UTF-8 start bytes. +// Single-byte tokens dispatched via `SINGLE_BYTE_TOKENS`, and invalid UTF-8 start bytes. // // UTF-8 continuation bytes (0x80 - 0xBF) (i.e. middle of a multi-byte UTF-8 sequence) // + and byte values which are not legal in UTF-8 strings (0xC0, 0xC1, 0xF5 - 0xFF). @@ -684,6 +790,9 @@ fn UNI(lexer: &mut Lexer<'_, C>) -> Kind { // // Note: Must not use `ascii_byte_handler!` macro, as this handler also covers non-ASCII bytes. #[expect(non_snake_case)] -fn UER(_lexer: &mut Lexer<'_, C>) -> Kind { +fn UER<'a, C: Config>( + _lexer: &mut Lexer<'a, C>, + _pos: SourcePosition<'a>, +) -> (Kind, SourcePosition<'a>) { unreachable!(); } diff --git a/vendor/oxc_parser/src/lexer/comment.rs b/vendor/oxc_parser/src/lexer/comment.rs index 748affd8f..dcee404e2 100644 --- a/vendor/oxc_parser/src/lexer/comment.rs +++ b/vendor/oxc_parser/src/lexer/comment.rs @@ -1,4 +1,4 @@ -use memchr::memmem::Finder; +use std::ops::Range; use oxc_ast::CommentKind; use oxc_data_structures::branch_hints::cold_path; @@ -6,219 +6,318 @@ use oxc_syntax::line_terminator::is_line_terminator; use crate::{config::LexerConfig as Config, diagnostics}; -use super::{ - Kind, Lexer, - search::{SafeByteMatchTable, byte_search, safe_byte_match_table}, - source::SourcePosition, -}; +use super::{Kind, Lexer}; // Irregular line breaks - '\u{2028}' (LS) and '\u{2029}' (PS) const LS_OR_PS_FIRST: u8 = 0xE2; const LS_BYTES_2_AND_3: [u8; 2] = [0x80, 0xA8]; const PS_BYTES_2_AND_3: [u8; 2] = [0x80, 0xA9]; -static LINE_BREAK_TABLE: SafeByteMatchTable = - safe_byte_match_table!(|b| matches!(b, b'\r' | b'\n' | LS_OR_PS_FIRST)); +/// Returns `true` if `bytes` starts with the 2nd and 3rd bytes of LS or PS. +#[inline] +fn starts_with_ls_or_ps_tail(bytes: &[u8]) -> bool { + bytes.starts_with(&LS_BYTES_2_AND_3) || bytes.starts_with(&PS_BYTES_2_AND_3) +} + +/// Returns `true` if `bytes`, which follow an `@`, start with `license` or `preserve`. +#[inline] +fn starts_with_legal_tag(bytes: &[u8]) -> bool { + bytes.starts_with(b"license") || bytes.starts_with(b"preserve") +} + +/// Looks for the end of a comment, and notes what the comment contains on the way, +/// so that the comment is only read once. +trait CommentScan { + /// Find the bytes of `chunk` which [`is_end`] has to look at. + /// + /// [`is_end`]: CommentScan::is_end + fn find>( + &self, + chunk: &[u8; LEN], + matcher: M, + ) -> M::Matches; + + /// Handle a byte which [`find`] found. `byte` is the byte at `index` of `bytes`. + /// Returns `true` if the comment ends at this byte. + /// + /// [`find`]: CommentScan::find + fn is_end(&mut self, bytes: &[u8], index: usize, byte: u8) -> bool; + + /// Look for the end of the comment in `bytes[range]`, checking `LEN` bytes at a time + /// with `matcher`. `bytes` is the source from the start of the comment's content. + /// + /// Returns the index of the byte which ends the comment, or `None` if it is not in `range`. + // `#[inline(always)]` so the code is compiled with the CPU features of the function it is in + #[expect(clippy::inline_always)] + #[inline(always)] + fn scan( + &mut self, + bytes: &[u8], + range: Range, + matcher: impl ChunkMatcher, + ) -> Option { + let (chunks, tail) = bytes[range.clone()].as_chunks::(); + let mut chunk_start = range.start; + for chunk in chunks { + for index_in_chunk in self.find(chunk, matcher) { + let index = chunk_start + index_in_chunk; + if self.is_end(bytes, index, chunk[index_in_chunk]) { + return Some(index); + } + } + chunk_start += LEN; + } + + // Less than a chunk remains. Pad it to a whole chunk with zeros, which are never searched for. + if !tail.is_empty() { + let mut chunk = [0; LEN]; + chunk[..tail.len()].copy_from_slice(tail); + for index_in_chunk in self.find(&chunk, matcher) { + let index = chunk_start + index_in_chunk; + if self.is_end(bytes, index, chunk[index_in_chunk]) { + return Some(index); + } + } + } + + None + } +} + +/// Looks for the line break which ends a line comment. +struct LineCommentScan { + /// `true` if the comment contains `@license` or `@preserve`. + has_legal_tag: bool, +} + +impl CommentScan for LineCommentScan { + #[expect(clippy::inline_always)] + #[inline(always)] + fn find>( + &self, + chunk: &[u8; LEN], + matcher: M, + ) -> M::Matches { + matcher.find(chunk, [b'\r', b'\n', LS_OR_PS_FIRST, b'@']) + } + + // `#[inline(always)]` because otherwise this is not inlined, and every comment pays for a call + #[expect(clippy::inline_always)] + #[inline(always)] + fn is_end(&mut self, bytes: &[u8], index: usize, byte: u8) -> bool { + match byte { + b'\r' | b'\n' => true, + b'@' => { + self.has_legal_tag = + self.has_legal_tag || starts_with_legal_tag(&bytes[index + 1..]); + false + } + LS_OR_PS_FIRST => { + // Could be first byte of LS/PS, or could be some other Unicode char. + // Either way, Unicode is uncommon, so make this a cold branch. + cold_path(); + starts_with_ls_or_ps_tail(&bytes[index + 1..]) + } + _ => false, + } + } +} + +/// Looks for the `/` of the `*/` which ends a block comment. +struct BlockCommentScan { + /// `true` if the comment contains a line break. + has_line_break: bool, + /// `true` if the comment contains `@license` or `@preserve`. + has_legal_tag: bool, +} + +impl CommentScan for BlockCommentScan { + #[expect(clippy::inline_always)] + #[inline(always)] + fn find>( + &self, + chunk: &[u8; LEN], + matcher: M, + ) -> M::Matches { + // `*` starts every line of a JSDoc comment, whereas `/` is uncommon in comments, + // so look for `/`, then check whether `*` precedes it. + // Once the comment is known to contain a line break, there is no need to look for more. + if self.has_line_break { + matcher.find(chunk, [b'/', b'@']) + } else { + matcher.find(chunk, [b'/', b'@', b'\r', b'\n', LS_OR_PS_FIRST]) + } + } -static MULTILINE_COMMENT_START_TABLE: SafeByteMatchTable = - safe_byte_match_table!(|b| matches!(b, b'*' | b'\r' | b'\n' | LS_OR_PS_FIRST)); + // `#[inline(always)]` because otherwise this is not inlined, and every comment pays for a call + #[expect(clippy::inline_always)] + #[inline(always)] + fn is_end(&mut self, bytes: &[u8], index: usize, byte: u8) -> bool { + match byte { + // The `*` of the opening `/*` is before `bytes`, so `/` at index 0 is not the end + b'/' => index > 0 && bytes[index - 1] == b'*', + b'@' => { + self.has_legal_tag = + self.has_legal_tag || starts_with_legal_tag(&bytes[index + 1..]); + false + } + b'\r' | b'\n' => { + self.has_line_break = true; + false + } + LS_OR_PS_FIRST => { + // Could be first byte of LS/PS, or could be some other Unicode char. + // Either way, Unicode is uncommon, so make this a cold branch. + cold_path(); + self.has_line_break = + self.has_line_break || starts_with_ls_or_ps_tail(&bytes[index + 1..]); + false + } + _ => false, + } + } +} + +/// Look for the end of a comment. `bytes` is the source from the start of the comment's content. +/// +/// Returns the index of the byte which ends the comment, or `None` if the comment continues +/// to the end of the source. +#[inline] +fn scan_comment(scan: &mut impl CommentScan, bytes: &[u8]) -> Option { + #[cfg(not(all(target_arch = "x86_64", not(target_feature = "avx2"))))] + { + scan.scan(bytes, 0..bytes.len(), BASELINE) + } + + // This build does not know whether the CPU supports AVX2. Finding out, and calling + // the code which uses it (which cannot be inlined into code which does not), costs more + // than AVX2 saves on a short comment, and most comments are short. + // So read the start of the comment without it. + #[cfg(all(target_arch = "x86_64", not(target_feature = "avx2")))] + { + /// Number of bytes at the start of a comment which are read without AVX2. + const SHORT_COMMENT_LEN: usize = 32; -impl<'a, C: Config> Lexer<'a, C> { + let start = if bytes.len() >= SHORT_COMMENT_LEN { + let end = scan.scan(bytes, 0..SHORT_COMMENT_LEN, BASELINE); + if end.is_some() { + return end; + } + SHORT_COMMENT_LEN + } else { + 0 + }; + + match Avx2::detect() { + // SAFETY: `Avx2` only exists if the CPU supports AVX2 + Some(avx2) => unsafe { scan_long_comment_avx2(scan, bytes, start, avx2) }, + None => scan_long_comment_baseline(scan, bytes, start), + } + } +} + +/// Look for the end of a comment in `bytes[start..]`, with AVX2 instructions. +#[cfg(all(target_arch = "x86_64", not(target_feature = "avx2")))] +#[target_feature(enable = "avx2")] +fn scan_long_comment_avx2( + scan: &mut impl CommentScan, + bytes: &[u8], + start: usize, + avx2: Avx2, +) -> Option { + scan.scan(bytes, start..bytes.len(), avx2) +} + +/// Look for the end of a comment in `bytes[start..]`, on a CPU which does not support AVX2. +// Nearly all x86-64 CPUs support AVX2 +#[cfg(all(target_arch = "x86_64", not(target_feature = "avx2")))] +#[cold] +#[inline(never)] +fn scan_long_comment_baseline( + scan: &mut impl CommentScan, + bytes: &[u8], + start: usize, +) -> Option { + scan.scan(bytes, start..bytes.len(), BASELINE) +} + +impl Lexer<'_, C> { /// Section 12.4 Single Line Comment pub(super) fn skip_single_line_comment(&mut self, kind: CommentKind) -> Kind { let start = self.source.position(); - let remaining = self.source.remaining().as_bytes(); - let Some(index) = memchr::memchr3(b'\r', b'\n', LS_OR_PS_FIRST, remaining) else { + let bytes = self.source.remaining().as_bytes(); + let mut scan = LineCommentScan { has_legal_tag: false }; + let Some(index) = scan_comment(&mut scan, bytes) else { self.source.advance_to_end(); self.trivia_builder.add_line_comment( - self.token.start(), + self.token_start, self.offset(), kind, + scan.has_legal_tag, self.source.whole(), + &mut self.pending, ); return Kind::Skip; }; - // SAFETY: The match is an in-bounds ASCII byte or a UTF-8 leading byte. + + // SAFETY: `index` is the index of the line break which ends the comment, + // so it is in bounds, and on a UTF-8 char boundary let end = unsafe { start.add(index) }; - if remaining[index] == LS_OR_PS_FIRST { - // Keep the scalar scanner for Unicode, where repeated matches can be very close. - self.source.set_position(end); - return self.skip_single_line_comment_unicode(kind); - } self.trivia_builder.add_line_comment( - self.token.start(), + self.token_start, self.source.offset_of(end), kind, + scan.has_legal_tag, self.source.whole(), + &mut self.pending, ); - // SAFETY: Consume the matching ASCII line break. - self.source.set_position(unsafe { end.add(1) }); - self.token.set_is_on_new_line(true); - Kind::Skip - } - - #[cold] - fn skip_single_line_comment_unicode(&mut self, kind: CommentKind) -> Kind { - byte_search! { - lexer: self, - table: LINE_BREAK_TABLE, - continue_if: (next_byte, pos) { - // Match found. Decide whether to continue searching. - // If this is end of comment, create trivia, and advance `pos` to after line break. - // Do that here rather than in `handle_match`, to avoid branching twice on value of - // the matched byte. - #[expect(clippy::if_not_else)] - if next_byte != LS_OR_PS_FIRST { - // `\r` or `\n` - self.trivia_builder - .add_line_comment(self.token.start(), self.source.offset_of(pos), kind, self.source.whole()); - // SAFETY: Safe to consume `\r` or `\n` as both are ASCII - pos = unsafe { pos.add(1) }; - // We've found the end. Do not continue searching. - false - } else { - // `0xE2`. Could be first byte of LS/PS, or could be some other Unicode char. - // Either way, Unicode is uncommon, so make this a cold branch. - cold_path(); - // SAFETY: Next byte is `0xE2` which is always 1st byte of a 3-byte UTF-8 char. - // So safe to advance `pos` by 1 and read 2 bytes. - let next2 = unsafe { pos.add(1).read2() }; - if matches!(next2, LS_BYTES_2_AND_3 | PS_BYTES_2_AND_3) { - // Irregular line break - self.trivia_builder - .add_line_comment(self.token.start(), self.source.offset_of(pos), kind, self.source.whole()); - // Advance `pos` to after this char. - // SAFETY: `0xE2` is always 1st byte of a 3-byte UTF-8 char, - // so consuming 3 bytes will place `pos` on next UTF-8 char boundary. - pos = unsafe { pos.add(3) }; - // We've found the end. Do not continue searching. - false - } else { - // Some other Unicode char beginning with `0xE2`. - // Skip 3 bytes (macro skips 1 already, so skip 2 here), and continue searching. - // SAFETY: `0xE2` is always 1st byte of a 3-byte UTF-8 char, - // so consuming 3 bytes will place `pos` on next UTF-8 char boundary. - pos = unsafe { pos.add(2) }; - true - } - } - }, - handle_eof: { - self.trivia_builder.add_line_comment(self.token.start(), self.offset(), kind, self.source.whole()); - return Kind::Skip; - }, - }; - - self.token.set_is_on_new_line(true); + // Consume the line break. `\r` and `\n` are 1 byte. LS and PS are 3 bytes. + let line_break_len = if bytes[index] == LS_OR_PS_FIRST { 3 } else { 1 }; + // SAFETY: The whole of the line break is in bounds, and after it is a UTF-8 char boundary + self.source.set_position(unsafe { end.add(line_break_len) }); + self.pending.set_is_on_new_line(); Kind::Skip } /// Section 12.4 Multi Line Comment + /// + /// Position of source must be after the opening `/*`. pub(super) fn skip_multi_line_comment(&mut self) -> Kind { + let start = self.source.position(); + let mut scan = BlockCommentScan { has_line_break: false, has_legal_tag: false }; + let end = scan_comment(&mut scan, self.source.remaining().as_bytes()); + // We need to identify if comment contains line breaks or not - // (`CommentKind::SingleLineBlock` or `CommentKind::MultiLineBlock`). - // So we have to use the loop below for the first line of the comment even if - // `Token`'s `is_on_new_line` flag is already set. - // If the loop finds a line break before end of the comment, we then switch to - // the faster `skip_multi_line_comment_after_line_break` which searches - // for the end of the comment using `memchr`. - - byte_search! { - lexer: self, - table: MULTILINE_COMMENT_START_TABLE, - continue_if: (next_byte, pos) { - // Match found. Decide whether to continue searching. - if next_byte == b'*' { - // SAFETY: Next byte is `*` (ASCII) so after it is UTF-8 char boundary - let after_star = unsafe { pos.add(1) }; - if after_star.is_not_end_of(&self.source) { - // If next byte isn't `/`, continue - // SAFETY: Have checked there's at least 1 further byte to read - if unsafe { after_star.read() } == b'/' { - // Consume `*/` - // SAFETY: Consuming `*/` leaves `pos` on a UTF-8 char boundary - pos = unsafe { pos.add(2) }; - false - } else { - true - } - } else { - // This is last byte in file. Continue to `handle_eof`. - // This is illegal in valid JS, so mark this branch cold. - cold_path(); - true - } - } else if next_byte == LS_OR_PS_FIRST { - // `0xE2`. Could be first byte of LS/PS, or could be some other Unicode char. - // Either way, Unicode is uncommon, so make this a cold branch. - cold_path(); - // SAFETY: Next byte is `0xE2` which is always 1st byte of a 3-byte UTF-8 char. - // So safe to advance `pos` by 1 and read 2 bytes. - let next2 = unsafe { pos.add(1).read2() }; - if matches!(next2, LS_BYTES_2_AND_3 | PS_BYTES_2_AND_3) { - // Irregular line break - self.token.set_is_on_new_line(true); - // SAFETY: Consuming this 3-byte UTF-8 char leaves a UTF-8 char boundary. - let after_line_break = unsafe { pos.add(3) }; - return self.skip_multi_line_comment_after_line_break(after_line_break); - } - // Some other Unicode char beginning with `0xE2`. - // Skip 3 bytes (macro skips 1 already, so skip 2 here), and continue searching. - // SAFETY: `0xE2` is always 1st byte of a 3-byte UTF-8 char, - // so consuming 3 bytes will place `pos` on next UTF-8 char boundary. - pos = unsafe { pos.add(2) }; - true - } else { - // Regular line break. - // No need to look for more line breaks, so switch to faster search just for `*/`. - self.token.set_is_on_new_line(true); - // SAFETY: Regular line breaks are ASCII, so skipping 1 byte is a UTF-8 char boundary. - let after_line_break = unsafe { pos.add(1) }; - return self.skip_multi_line_comment_after_line_break(after_line_break); - } - }, - handle_eof: { - self.error(diagnostics::unterminated_multi_line_comment(self.unterminated_range())); - return Kind::Eof; - }, + // (`CommentKind::SingleLineBlock` or `CommentKind::MultiLineBlock`), + // even if `Token`'s `is_on_new_line` flag is already set. + let kind = if scan.has_line_break { + self.pending.set_is_on_new_line(); + CommentKind::MultiLineBlock + } else { + CommentKind::SingleLineBlock + }; + + let Some(index) = end else { + cold_path(); + self.source.advance_to_end(); + self.error(diagnostics::unterminated_multi_line_comment(self.unterminated_range())); + return Kind::Eof; }; + // SAFETY: `index` is the index of the `/` of the closing `*/`, so `index + 1` is in bounds, + // and on a UTF-8 char boundary + self.source.set_position(unsafe { start.add(index + 1) }); self.trivia_builder.add_block_comment( - self.token.start(), + self.token_start, self.offset(), - CommentKind::SingleLineBlock, + kind, + scan.has_legal_tag, self.source.whole(), + &mut self.pending, ); Kind::Skip } - fn skip_multi_line_comment_after_line_break(&mut self, pos: SourcePosition<'a>) -> Kind { - // Can use `memchr` here as only searching for 1 pattern. - // Cache `Finder` instance on `Lexer` as there's a significant cost to creating it. - // `Finder::new` isn't a const function, so can't make it a `static`, and `lazy_static!` - // has a cost each time it's deref-ed. Creating `Finder` unconditionally in `Lexer::new` - // would be efficient for files containing multi-line comments, but would impose pointless - // cost on files which don't. So this is the fastest solution. - let finder = self.multi_line_comment_end_finder.get_or_insert_with(|| Finder::new("*/")); - - let remaining = self.source.str_from_pos_to_end(pos).as_bytes(); - if let Some(index) = finder.find(remaining) { - // SAFETY: `pos + index + 2` is end of `*/`, so a valid `SourcePosition` - self.source.set_position(unsafe { pos.add(index + 2) }); - self.trivia_builder.add_block_comment( - self.token.start(), - self.offset(), - CommentKind::MultiLineBlock, - self.source.whole(), - ); - Kind::Skip - } else { - self.source.advance_to_end(); - self.error(diagnostics::unterminated_multi_line_comment(self.unterminated_range())); - Kind::Eof - } - } - /// Section 12.5 Hashbang Comments. /// /// # SAFETY @@ -241,3 +340,263 @@ impl<'a, C: Config> Lexer<'a, C> { Kind::HashbangComment } } + +// ---------- Chunk matchers ---------- // + +/// Finds which bytes of a chunk of `LEN` bytes of source are any of a few byte values. +/// +/// All bytes of the chunk are checked at once, so what it costs does not depend on what the chunk +/// contains, or on how many byte values are searched for. Unlike a search for the first matching +/// byte, every match in the chunk is found, so code which wants to look at each of them +/// does not start a new search after each one. +/// +/// Each matcher is only compiled on the platforms which use it. +/// +/// | Matcher | Chunk | Used on | +/// |-----------|----------|---------------------------------------------------------| +/// | `Neon` | 16 bytes | 64-bit ARM | +/// | `Avx2` | 32 bytes | x86-64, if the CPU supports AVX2, after the first bytes | +/// | `Sse2` | 16 bytes | x86-64, otherwise | +/// | `Simd128` | 16 bytes | 32-bit WebAssembly built with `simd128` | +/// | `Swar` | 8 bytes | Everything else | +trait ChunkMatcher: Copy { + /// Indexes of the bytes of a chunk which matched, in ascending order. + type Matches: Iterator; + + /// Find the bytes of `chunk` which are any of `needles`. + fn find(self, chunk: &[u8; LEN], needles: [u8; N]) -> Self::Matches; +} + +/// Indexes of the bytes of a chunk which matched, in ascending order. +/// +/// `mask` has one bit set for each byte which matched. +/// The bit for byte `index` is one of the `1 << SHIFT` bits from `index << SHIFT`. +struct ByteMatches { + mask: u64, +} + +impl Iterator for ByteMatches { + type Item = usize; + + #[inline] + fn next(&mut self) -> Option { + if self.mask == 0 { + return None; + } + let index = (self.mask.trailing_zeros() >> SHIFT) as usize; + // Clear lowest bit + self.mask &= self.mask - 1; + Some(index) + } +} + +/// The matcher which this build can use without checking what the CPU supports. +#[cfg(all(target_arch = "aarch64", target_feature = "neon", target_endian = "little"))] +const BASELINE: Neon = Neon(()); +#[cfg(all(target_arch = "x86_64", target_feature = "avx2"))] +const BASELINE: Avx2 = Avx2(()); +#[cfg(all(target_arch = "x86_64", target_feature = "sse2", not(target_feature = "avx2")))] +const BASELINE: Sse2 = Sse2(()); +#[cfg(all(target_arch = "wasm32", target_feature = "simd128"))] +const BASELINE: Simd128 = Simd128(()); +#[cfg(not(any( + all(target_arch = "aarch64", target_feature = "neon", target_endian = "little"), + all(target_arch = "x86_64", target_feature = "sse2"), + all(target_arch = "wasm32", target_feature = "simd128"), +)))] +const BASELINE: Swar = Swar; + +/// Checks 16 bytes at once with NEON instructions. +#[cfg(all(target_arch = "aarch64", target_feature = "neon", target_endian = "little"))] +#[derive(Clone, Copy)] +struct Neon(()); + +#[cfg(all(target_arch = "aarch64", target_feature = "neon", target_endian = "little"))] +impl ChunkMatcher<16> for Neon { + type Matches = ByteMatches<2>; + + #[inline(always)] + fn find(self, chunk: &[u8; 16], needles: [u8; N]) -> Self::Matches { + use std::arch::aarch64::{ + vceqzq_u8, vdupq_n_u8, veorq_u8, vget_lane_u64, vld1q_u8, vminq_u8, + vreinterpret_u64_u8, vreinterpretq_u16_u8, vshrn_n_u16, + }; + + // SAFETY: `Neon` is only compiled if NEON is enabled, so the intrinsics are available. + // `chunk` is 16 bytes, which is what `vld1q_u8` reads. + let mask = unsafe { + let bytes = vld1q_u8(chunk.as_ptr()); + // XOR of a byte with a needle is 0 if they are equal, so the smallest of the XORs + // is 0 if the byte is any of the needles. + // Comparing with each needle and ORing the results is the obvious way to do this, + // but LLVM compiles that to 2 more instructions per chunk than this + // (it loses track of each byte of the result being `0xFF` or 0, and recomputes that). + let mut smallest_diff = vdupq_n_u8(0xFF); + for needle in needles { + smallest_diff = vminq_u8(smallest_diff, veorq_u8(bytes, vdupq_n_u8(needle))); + } + let matches = vceqzq_u8(smallest_diff); + // Each byte of `matches` is `0xFF` or 0. Narrow each to 4 bits, to fit them all + // in a `u64`, then keep 1 bit of each. + let nibbles = vshrn_n_u16::<4>(vreinterpretq_u16_u8(matches)); + vget_lane_u64::<0>(vreinterpret_u64_u8(nibbles)) & 0x1111_1111_1111_1111 + }; + ByteMatches { mask } + } +} + +/// Checks 16 bytes at once with SSE2 instructions. +#[cfg(all(target_arch = "x86_64", target_feature = "sse2", not(target_feature = "avx2")))] +#[derive(Clone, Copy)] +struct Sse2(()); + +#[cfg(all(target_arch = "x86_64", target_feature = "sse2", not(target_feature = "avx2")))] +impl ChunkMatcher<16> for Sse2 { + type Matches = ByteMatches<0>; + + #[inline(always)] + fn find(self, chunk: &[u8; 16], needles: [u8; N]) -> Self::Matches { + use std::arch::x86_64::{ + __m128i, _mm_cmpeq_epi8, _mm_loadu_si128, _mm_movemask_epi8, _mm_or_si128, + _mm_set1_epi8, _mm_setzero_si128, + }; + + // SAFETY: `Sse2` is only compiled if SSE2 is enabled, so the intrinsics are available. + // `chunk` is 16 bytes, which is what `_mm_loadu_si128` reads. It does not require + // the pointer to be aligned. + let mask = unsafe { + #[expect(clippy::cast_ptr_alignment)] + let bytes = _mm_loadu_si128(chunk.as_ptr().cast::<__m128i>()); + let mut matches = _mm_setzero_si128(); + for needle in needles { + #[expect(clippy::cast_possible_wrap)] + let needle = _mm_set1_epi8(needle as i8); + matches = _mm_or_si128(matches, _mm_cmpeq_epi8(bytes, needle)); + } + // Top bit of each byte of `matches`. The mask is 16 bits, so is not negative. + #[expect(clippy::cast_sign_loss)] + let mask = _mm_movemask_epi8(matches) as u32; + mask + }; + ByteMatches { mask: u64::from(mask) } + } +} + +/// Checks 32 bytes at once with AVX2 instructions. +/// +/// An `Avx2` only exists if the CPU supports AVX2. Code which uses it must be compiled +/// with AVX2 enabled, or it is very slow, as the intrinsics are not inlined. +#[cfg(target_arch = "x86_64")] +#[derive(Clone, Copy)] +struct Avx2(()); + +#[cfg(target_arch = "x86_64")] +impl Avx2 { + /// Returns an `Avx2` if the CPU supports AVX2. + /// What the CPU supports is only looked up once. After that, this is a load and a test. + #[cfg(not(target_feature = "avx2"))] + #[inline] + fn detect() -> Option { + if std::arch::is_x86_feature_detected!("avx2") { Some(Self(())) } else { None } + } +} + +#[cfg(target_arch = "x86_64")] +impl ChunkMatcher<32> for Avx2 { + type Matches = ByteMatches<0>; + + #[inline(always)] + fn find(self, chunk: &[u8; 32], needles: [u8; N]) -> Self::Matches { + use std::arch::x86_64::{ + __m256i, _mm256_cmpeq_epi8, _mm256_loadu_si256, _mm256_movemask_epi8, _mm256_or_si256, + _mm256_set1_epi8, _mm256_setzero_si256, + }; + + // SAFETY: `Avx2` only exists if the CPU supports AVX2, so the intrinsics are available. + // `chunk` is 32 bytes, which is what `_mm256_loadu_si256` reads. It does not require + // the pointer to be aligned. + let mask = unsafe { + #[expect(clippy::cast_ptr_alignment)] + let bytes = _mm256_loadu_si256(chunk.as_ptr().cast::<__m256i>()); + let mut matches = _mm256_setzero_si256(); + for needle in needles { + #[expect(clippy::cast_possible_wrap)] + let needle = _mm256_set1_epi8(needle as i8); + matches = _mm256_or_si256(matches, _mm256_cmpeq_epi8(bytes, needle)); + } + // Top bit of each byte of `matches`. Cast to `u32` keeps all 32 bits. + #[expect(clippy::cast_sign_loss)] + let mask = _mm256_movemask_epi8(matches) as u32; + mask + }; + ByteMatches { mask: u64::from(mask) } + } +} + +/// Checks 16 bytes at once with WebAssembly SIMD instructions. +#[cfg(all(target_arch = "wasm32", target_feature = "simd128"))] +#[derive(Clone, Copy)] +struct Simd128(()); + +#[cfg(all(target_arch = "wasm32", target_feature = "simd128"))] +impl ChunkMatcher<16> for Simd128 { + type Matches = ByteMatches<0>; + + #[inline(always)] + fn find(self, chunk: &[u8; 16], needles: [u8; N]) -> Self::Matches { + use std::arch::wasm32::{u8x16_bitmask, u8x16_eq, u8x16_splat, v128, v128_load, v128_or}; + + // SAFETY: `Simd128` is only compiled if `simd128` is enabled, so the intrinsics + // are available. `chunk` is 16 bytes, which is what `v128_load` reads. It does not + // require the pointer to be aligned. + let mask = unsafe { + #[expect(clippy::cast_ptr_alignment)] + let bytes = v128_load(chunk.as_ptr().cast::()); + let mut matches = u8x16_splat(0); + for needle in needles { + matches = v128_or(matches, u8x16_eq(bytes, u8x16_splat(needle))); + } + // Top bit of each byte of `matches` + u8x16_bitmask(matches) + }; + ByteMatches { mask: u64::from(mask) } + } +} + +/// Checks 8 bytes at once with integer arithmetic. +#[cfg(not(any( + all(target_arch = "aarch64", target_feature = "neon", target_endian = "little"), + all(target_arch = "x86_64", target_feature = "sse2"), + all(target_arch = "wasm32", target_feature = "simd128"), +)))] +#[derive(Clone, Copy)] +struct Swar; + +#[cfg(not(any( + all(target_arch = "aarch64", target_feature = "neon", target_endian = "little"), + all(target_arch = "x86_64", target_feature = "sse2"), + all(target_arch = "wasm32", target_feature = "simd128"), +)))] +impl ChunkMatcher<8> for Swar { + type Matches = ByteMatches<3>; + + #[inline] + fn find(self, chunk: &[u8; 8], needles: [u8; N]) -> Self::Matches { + /// The lower 7 bits of each byte of a chunk. + const LOW_7_BITS: u64 = u64::from_ne_bytes([0x7F; 8]); + /// The top bit of each byte of a chunk. + const TOP_BITS: u64 = u64::from_ne_bytes([0x80; 8]); + + // Little-endian, so that lower bits are for earlier bytes + let bytes = u64::from_le_bytes(*chunk); + // Top bit of each byte is set if that byte of `chunk` is none of `needles` + let mut differs = TOP_BITS; + for needle in needles { + let diff = bytes ^ u64::from_ne_bytes([needle; 8]); + // Adding `0x7F` to the lower 7 bits of a byte sets its top bit if any of them is set, + // and does not carry into the next byte + differs &= ((diff & LOW_7_BITS) + LOW_7_BITS) | diff; + } + ByteMatches { mask: !differs & TOP_BITS } + } +} diff --git a/vendor/oxc_parser/src/lexer/identifier.rs b/vendor/oxc_parser/src/lexer/identifier.rs index 6b32b20a9..31771c528 100644 --- a/vendor/oxc_parser/src/lexer/identifier.rs +++ b/vendor/oxc_parser/src/lexer/identifier.rs @@ -10,7 +10,7 @@ use oxc_syntax::identifier::{ use crate::{config::LexerConfig as Config, diagnostics}; use super::{ - Kind, Lexer, SourcePosition, cold_branch, + FinishTokenMode, Kind, Lexer, PendingToken, SourcePosition, Token, cold_branch, keyword, search::{SafeByteMatchTable, byte_search, safe_byte_match_table}, }; @@ -23,34 +23,31 @@ static NOT_ASCII_ID_CONTINUE_TABLE: SafeByteMatchTable = safe_byte_match_table!(|b| !(b.is_ascii_alphanumeric() || b == b'_' || b == b'$')); #[inline] -fn is_identifier_start_ascii_byte(byte: u8) -> bool { +pub(super) fn is_identifier_start_ascii_byte(byte: u8) -> bool { ASCII_ID_START_TABLE.matches(byte) } impl<'a, C: Config> Lexer<'a, C> { - /// Handle identifier with ASCII start character. - /// Returns text of the identifier, minus its first char. + /// Consume an identifier starting with an ASCII byte and return its kind and end position. + /// `CHECK_KEYWORD` may be false only for starting bytes that cannot begin a keyword. /// - /// Start character should not be consumed from `self.source` prior to calling this. - /// - /// This function is the "fast path" for the most common identifiers in JS code - - /// purely consisting of ASCII characters: `a`-`z`, `A`-`Z`, `0`-`9`, `_`, `$`. - /// JS syntax also allows Unicode identifiers and escapes (e.g. `\u{FF}`) in identifiers, - /// but they are very rare in practice. So this fast path will handle 99% of JS code. - /// - /// When Unicode or an escape is encountered, this function de-opts to paths which handle those - /// cases, but those paths are marked `#[cold]` to keep the ASCII fast path as fast as possible. - /// - /// The fast path uses pointers and unsafe code to minimize bounds checks etc. - /// The functions it delegates to for uncommon cases iterate over characters. + /// Leave the first byte unconsumed. ASCII scanning stays inline; Unicode characters + /// and escapes use the decoding routines below. /// /// # SAFETY /// * `self.source` must not be exhausted (at least 1 char remaining). /// * Next char must be ASCII. - pub(super) unsafe fn identifier_name_handler(&mut self) -> &'a str { + /// * `start_pos` must be the current position of `self.source`. + #[expect(clippy::inline_always)] + #[inline(always)] + pub(super) unsafe fn identifier_name_handler( + &mut self, + start_pos: SourcePosition<'a>, + ) -> (Kind, SourcePosition<'a>) { + debug_assert_eq!(start_pos, self.source.position()); // Advance past 1st byte. // SAFETY: Caller guarantees not at EOF, and next byte is ASCII. - let after_first = unsafe { self.source.position().add(1) }; + let after_first = unsafe { start_pos.add(1) }; // Consume bytes which are part of identifier let next_byte = byte_search! { @@ -58,37 +55,128 @@ impl<'a, C: Config> Lexer<'a, C> { table: NOT_ASCII_ID_CONTINUE_TABLE, start: after_first, handle_eof: { - // Return identifier minus its first char. - // SAFETY: `lexer.source` is positioned at EOF, so there is no valid value - // of `after_first` which could be after current position. - return unsafe { self.source.str_from_pos_to_current_unchecked(after_first) }; + if CHECK_KEYWORD { + // SAFETY: The source is at EOF, after the saved identifier start. + let id = unsafe { self.source.str_from_pos_to_current_unchecked(start_pos) }; + return (keyword::match_keyword(id.as_bytes()), self.source.position()); + } + return (Kind::Ident, self.source.position()); }, }; - // Found a matching byte. - // Either end of identifier found, or a Unicode char, or `\` escape. - // Handle uncommon cases in cold branches to keep the common ASCII path - // as fast as possible. + // Keep decoding and keyword lookup in one cold call so IDT and KWD can both tail-call it. + // For IDT the keyword lookup always gives `Kind::Ident`, but skipping it would make the + // returned `Kind` a constant, which stops the call being a tail call. if !next_byte.is_ascii() { cold_path(); - // SAFETY: `after_first` is position after consuming 1 byte, so subtracting 1 - // makes `start_pos` `source`'s position as it was at start of this function - let start_pos = unsafe { after_first.sub(1) }; - return &self.identifier_tail_unicode(start_pos)[1..]; + return self.identifier_name_uncommon::(start_pos); } if next_byte == b'\\' { cold_path(); - // SAFETY: `after_first` is position after consuming 1 byte, so subtracting 1 - // makes `start_pos` `source`'s position as it was at start of this function - let start_pos = unsafe { after_first.sub(1) }; - return &self.identifier_backslash(start_pos, false)[1..]; + return self.identifier_name_uncommon::(start_pos); } - // Return identifier minus its first char. - // SAFETY: `after_first` was position of `lexer.source` at start of this search. - // Searching only proceeds in forwards direction, so `lexer.source.position()` - // cannot be before `after_first`. - unsafe { self.source.str_from_pos_to_current_unchecked(after_first) } + let kind = if CHECK_KEYWORD { + // SAFETY: The scanner only moves forwards from the saved identifier start. + let id = unsafe { self.source.str_from_pos_to_current_unchecked(start_pos) }; + keyword::match_keyword(id.as_bytes()) + } else { + Kind::Ident + }; + (kind, self.source.position()) + } + + /// Token handler for an identifier starting with an ASCII byte. + /// `CHECK_KEYWORD` may be false only for starting bytes that cannot begin a keyword. + /// + /// Does the same as `identifier_name_handler`, then finishes the token. + /// An identifier has no flags unless it contains an escape, so the common case skips + /// the work which `finish_next_inner` does for flags and trivia. + /// + /// # SAFETY + /// * `start_pos` must be the position of a byte which is not at the end of the source. + /// * That byte must be ASCII. + /// * If `ON_NEW_LINE` is `false`, no trivia must have been seen since the previous token, + /// other than one space. + /// * If `ON_NEW_LINE` is `true`, line breaks and regular whitespace must be the only trivia + /// seen since the previous token, and `pending` must not have been altered. + #[expect(clippy::inline_always)] + #[inline(always)] + pub(super) unsafe fn identifier_token( + &mut self, + start_pos: SourcePosition<'a>, + ) -> Token { + // Advance past 1st byte. + // SAFETY: Caller guarantees not at EOF, and next byte is ASCII. + let after_first = unsafe { start_pos.add(1) }; + + // Consume bytes which are part of identifier + let next_byte = byte_search! { + lexer: self, + table: NOT_ASCII_ID_CONTINUE_TABLE, + start: after_first, + // A byte which ends an identifier, so that EOF takes the common path below + handle_eof: b' ', + }; + + // Unicode characters and escapes are uncommon. Handle both in one cold call. + if !next_byte.is_ascii() || next_byte == b'\\' { + cold_path(); + return self.identifier_token_uncommon(start_pos, next_byte == b'\\', ON_NEW_LINE); + } + + let end = self.source.position(); + let kind = if CHECK_KEYWORD { + // SAFETY: The scanner only moves forwards from the saved identifier start. + let id = unsafe { self.source.str_from_pos_to_current_unchecked(start_pos) }; + keyword::match_keyword(id.as_bytes()) + } else { + Kind::Ident + }; + if ON_NEW_LINE { + self.finish_fresh_token_on_new_line(kind, start_pos, end) + } else { + self.finish_fresh_token(kind, start_pos, end) + } + } + + /// Finish an identifier which contains a Unicode character or an escape. + /// Position of source must be on that character or escape. + #[cold] + #[inline(never)] + fn identifier_token_uncommon( + &mut self, + start_pos: SourcePosition<'a>, + is_escape: bool, + is_on_new_line: bool, + ) -> Token { + if is_on_new_line { + // No trivia was seen before the line break, so this is all that needs to be recorded + debug_assert_eq!(self.pending, PendingToken::NONE); + self.pending = PendingToken::AFTER_LINE_BREAK; + } + // `identifier_backslash` records the unescaped identifier against `token_start` + self.token_start = self.source.offset_of(start_pos); + let (kind, end) = if is_escape { + self.identifier_name_uncommon::(start_pos) + } else { + self.identifier_name_uncommon::(start_pos) + }; + self.finish_next_inner(kind, end, FinishTokenMode::Push) + } + + #[cold] + #[inline(never)] + fn identifier_name_uncommon( + &mut self, + start_pos: SourcePosition<'a>, + ) -> (Kind, SourcePosition<'a>) { + let id = if IS_ESCAPE { + self.identifier_backslash(start_pos, false) + } else { + self.identifier_tail_unicode(start_pos) + }; + (keyword::match_keyword(id.as_bytes()), self.source.position()) } /// Handle rest of identifier after first byte of a multi-byte Unicode char found. diff --git a/vendor/oxc_parser/src/lexer/jsx.rs b/vendor/oxc_parser/src/lexer/jsx.rs index aa305400c..f0e4eec32 100644 --- a/vendor/oxc_parser/src/lexer/jsx.rs +++ b/vendor/oxc_parser/src/lexer/jsx.rs @@ -55,7 +55,7 @@ impl Lexer<'_, C> { } pub(crate) fn next_jsx_child(&mut self) -> Token { - self.token.set_start(self.offset()); + self.token_start = self.offset(); let kind = self.read_jsx_child(); self.finish_next(kind) } @@ -111,11 +111,18 @@ impl Lexer<'_, C> { /// `IdentifierStart` /// `JSXIdentifier` `IdentifierPart` /// `JSXIdentifier` [no `WhiteSpace` or Comment here] - + #[inline] // Every `JSXIdentifier` checks for `-`. Few continue past it. pub(crate) fn continue_lex_jsx_identifier(&mut self, start: u32) -> Option { if self.peek_byte() != Some(b'-') { return None; } - self.token.set_start(start); + Some(self.continue_lex_jsx_identifier_at_dash(start)) + } + + /// Continue the `JSXIdentifier` which starts at `start`, from the `-` at the current position. + fn continue_lex_jsx_identifier_at_dash(&mut self, start: u32) -> Token { + debug_assert_eq!(self.peek_byte(), Some(b'-')); + self.token_start = start; self.consume_char(); // Consume bytes which are part of identifier tail @@ -123,7 +130,7 @@ impl Lexer<'_, C> { lexer: self, table: NOT_ASCII_JSX_ID_CONTINUE_TABLE, handle_eof: { - return Some(self.finish_next_retokenized(Kind::Ident)); + return self.finish_next_retokenized(Kind::Ident); }, }; @@ -142,6 +149,6 @@ impl Lexer<'_, C> { } } - Some(self.finish_next_retokenized(Kind::Ident)) + self.finish_next_retokenized(Kind::Ident) } } diff --git a/vendor/oxc_parser/src/lexer/keyword.rs b/vendor/oxc_parser/src/lexer/keyword.rs new file mode 100644 index 000000000..5c61732fc --- /dev/null +++ b/vendor/oxc_parser/src/lexer/keyword.rs @@ -0,0 +1,113 @@ +//! Classify a scanned identifier as a keyword or [`Kind::Ident`]. +//! +//! This lookup lets all ASCII letters that can start a keyword share one identifier handler, +//! reducing the number of indirect-call targets in byte dispatch. It accepts either a source +//! slice or the decoded spelling of an escaped identifier; scanning and decoding happen elsewhere. +//! +//! Keywords are 2 to 11 bytes long. For those lengths, overlapping, in-bounds loads pack the +//! complete spelling into an eight-byte prefix and a three-byte suffix, with the length stored +//! alongside the suffix. A multiply-and-shift hash selects one entry in a 512-entry (8 KiB) +//! static table. Comparing the full spelling and length rejects non-keywords that hash to the +//! same slot. Lookup needs no allocation, padded input, or collision probing. +//! +//! The table is built at compile time from [`Kind::VARIANTS`], using [`Kind::is_any_keyword`] +//! and [`Kind::to_str`] as the source of keyword spellings. The hash gives each current keyword +//! a distinct slot; compile-time assertions reject collisions or unsupported keyword lengths. +//! Adding a keyword may require a new hash multiplier and an update to the byte-handler table +//! if its first letter currently bypasses keyword lookup. + +use super::Kind; + +#[derive(Clone, Copy)] +struct Entry { + prefix: u64, + suffix_and_len: u32, + kind: Kind, +} + +// Collision-free for the current keywords. Table construction rejects collisions +// when keywords change; choose a new multiplier if needed. Update the byte-handler +// table if a new keyword starts with a letter currently routed to IDT. +const HASH_SEED: u64 = 17_825_894_737_173_976_417; + +// Only nine hash bits are retained, so the result fits usize on every target. +const fn slot(prefix: u64, suffix_and_len: u32) -> usize { + ((prefix ^ ((suffix_and_len as u64) << 21)).wrapping_mul(HASH_SEED) >> 55) as usize +} + +// Each 16-byte entry stores the complete keyword and its length. Hash matches alone +// do not establish equality; non-keywords which share a slot are rejected below. +static TABLE: [Entry; 512] = { + let mut table = [Entry { prefix: 0, suffix_and_len: 0, kind: Kind::Ident }; 512]; + let mut index = 0; + while index < Kind::VARIANTS.len() { + let kind = Kind::VARIANTS[index]; + index += 1; + if !kind.is_any_keyword() { + continue; + } + let bytes = kind.to_str().as_bytes(); + assert!(bytes.len() >= 2 && bytes.len() <= 11); + let mut prefix = [0; 8]; + let mut suffix_and_len = [0; 4]; + // The length check above proves this fits in a byte. + #[expect(clippy::cast_possible_truncation)] + let len = bytes.len() as u8; + suffix_and_len[3] = len; + let mut byte_index = 0; + while byte_index < bytes.len() { + if byte_index < 8 { + prefix[byte_index] = bytes[byte_index]; + } else { + suffix_and_len[byte_index - 8] = bytes[byte_index]; + } + byte_index += 1; + } + let prefix = u64::from_le_bytes(prefix); + let suffix_and_len = u32::from_le_bytes(suffix_and_len); + let slot = slot(prefix, suffix_and_len); + assert!(matches!(table[slot].kind, Kind::Ident), "keyword hash collision"); + table[slot] = Entry { prefix, suffix_and_len, kind }; + } + table +}; + +#[expect(clippy::inline_always)] +#[inline(always)] +pub(super) fn match_keyword(bytes: &[u8]) -> Kind { + let len = bytes.len(); + if !(2..12).contains(&len) { + return Kind::Ident; + } + + // Overlapping loads assemble the identifier without padding or reading beyond + // its slice. Decoded escaped identifiers need not have any trailing source bytes. + // SAFETY: The length check proves 2 <= len <= 11. Each branch reads the first + // 2/4/8 bytes and the last 2/4 bytes, all within the slice. Unaligned loads do not + // require the identifier to start at an aligned address. + let (prefix, suffix) = unsafe { + let ptr = bytes.as_ptr(); + if len <= 4 { + let first = u64::from(u16::from_le(ptr.cast::().read_unaligned())); + let last = u64::from(u16::from_le(ptr.add(len - 2).cast::().read_unaligned())); + (first | (last << ((len - 2) * 8)), 0) + } else if len <= 8 { + let first = u64::from(u32::from_le(ptr.cast::().read_unaligned())); + let last = u64::from(u32::from_le(ptr.add(len - 4).cast::().read_unaligned())); + (first | (last << ((len - 4) * 8)), 0) + } else { + let first = u64::from_le(ptr.cast::().read_unaligned()); + let last = u32::from_le(ptr.add(len - 4).cast::().read_unaligned()); + (first, last >> ((12 - len) * 8)) + } + }; + // The length check above proves len fits in u32. + #[expect(clippy::cast_possible_truncation)] + let suffix_and_len = suffix | ((len as u32) << 24); + let entry = TABLE[slot(prefix, suffix_and_len)]; + if entry.prefix == prefix && entry.suffix_and_len == suffix_and_len { + entry.kind + } else { + Kind::Ident + } +} diff --git a/vendor/oxc_parser/src/lexer/kind.rs b/vendor/oxc_parser/src/lexer/kind.rs index 79dd29252..15f7e21c6 100644 --- a/vendor/oxc_parser/src/lexer/kind.rs +++ b/vendor/oxc_parser/src/lexer/kind.rs @@ -272,16 +272,6 @@ impl Kind { self.is_identifier_name() && !self.is_reserved_keyword() } - /// TypeScript Identifier - /// - /// - #[inline] - pub const fn is_ts_identifier(self, is_yield_context: bool, is_await_context: bool) -> bool { - self.is_identifier_reference(is_yield_context, is_await_context) - && !self.is_strict_mode_contextual_keyword() - && !self.is_contextual_keyword() - } - /// `IdentifierName` /// All identifier names are either `Ident` or keywords (Await..=Null in the enum). #[inline] @@ -552,7 +542,7 @@ impl Kind { } } - pub fn to_str(self) -> &'static str { + pub const fn to_str(self) -> &'static str { #[expect(clippy::match_same_arms)] match self { Undetermined => "Unknown", diff --git a/vendor/oxc_parser/src/lexer/mod.rs b/vendor/oxc_parser/src/lexer/mod.rs index d853f74fe..2e6c9d275 100644 --- a/vendor/oxc_parser/src/lexer/mod.rs +++ b/vendor/oxc_parser/src/lexer/mod.rs @@ -11,11 +11,13 @@ use rustc_hash::FxHashMap; use oxc_allocator::{Allocator, ArenaVec}; use oxc_ast::ast::RegExpFlags; +use oxc_data_structures::brands::BrandOrigin; +#[cfg(any(test, feature = "benchmarking"))] +use oxc_data_structures::brands::BrandScope; use oxc_span::{SourceType, Span}; use oxc_str::JSStr; use crate::{ - UniquePromise, config::LexerConfig as Config, diagnostics::{self, ParserDiagnostic}, }; @@ -24,6 +26,7 @@ mod byte_handlers; mod comment; mod identifier; mod jsx; +mod keyword; mod kind; mod number; mod numeric; @@ -46,23 +49,28 @@ pub use number::{parse_big_int, parse_float, parse_int}; pub use token::Token; use source::{Source, SourcePosition}; -use trivia_builder::{AnnotationComments, TriviaBuilder}; +use token::PendingToken; +use trivia_builder::{TriviaBuilder, TriviaCheckpoint}; -#[derive(Debug)] +#[derive(Debug, Clone, Copy)] pub struct LexerCheckpoint<'a> { source_position: SourcePosition<'a>, - errors_snapshot: ErrorSnapshot<'a>, + errors_len: usize, tokens_len: usize, - annotation_comments: AnnotationComments, + trivia: TriviaCheckpoint, } -#[derive(Debug)] -enum ErrorSnapshot<'a> { - Empty, - Count(usize), - Full(Vec>), +impl LexerCheckpoint<'_> { + pub(crate) fn errors_len(&self) -> usize { + self.errors_len + } } +/// Number of bytes which are always available to read from the position passed to a token handler. +/// i.e. a token handler can read the byte after the first byte of the token, without checking +/// whether it is at the end of the source. +const TOKEN_HANDLER_MIN_BYTES: usize = 2; + /// Action to take when finishing a token. /// Passed to [`Lexer::finish_next_inner`]. #[derive(Clone, Copy, Eq, PartialEq)] @@ -80,18 +88,23 @@ pub struct Lexer<'a, C: Config> { source_type: SourceType, - /// The token currently being built. - /// Only its start and flags are written here; its kind and end remain zero until - /// `Token::finish` constructs the completed token. + /// Start of the token currently being lexed. + token_start: u32, + + /// Flags of the token currently being lexed, and trivia state since the previous token. + /// The `Token` itself is only constructed by `Token::new` once its kind and end are known. /// - /// Between lexer calls, `token` is always `Token::default()`. Every method which produces a token - /// ends in `finish_next_inner` or `finish_re_lex`, and both reset it. + /// Between lexer calls, `pending` is always `PendingToken::NONE`. Every method which produces + /// a token ends in one of: + /// * `finish_next_inner`, which resets it. + /// * `finish_re_lex`, which never alters it. + /// * `finish_fresh_token`, which is only for tokens which nothing has altered it for. /// - /// The one exception is before the first token is lexed, when it is `Token::new_on_new_line()`. - /// `checkpoint` and `rewind` can never see that state, because the parser lexes the first token - /// before it does anything else, and they are the only things which depend on `token` being - /// `Token::default()`. Both assert it. - token: Token, + /// The one exception is before the first token is lexed, when it is `PendingToken::START_OF_FILE`. + /// `next_token`, `checkpoint` and `rewind` depend on `pending` being `PendingToken::NONE`, + /// and assert it in debug builds. They can never see that state, because the parser lexes + /// the first token with `first_token` before it does anything else. + pending: PendingToken, pub(crate) errors: Vec>, @@ -112,9 +125,6 @@ pub struct Lexer<'a, C: Config> { /// `None` is saved when the string contains an invalid escape sequence. pub escaped_templates: FxHashMap>>, - /// `memchr` Finder for end of multi-line comments. Created lazily when first used. - multi_line_comment_end_finder: Option>, - /// Collected tokens in source order. tokens: ArenaVec<'a, Token>, @@ -132,16 +142,15 @@ pub struct Lexer<'a, C: Config> { impl<'a, C: Config> Lexer<'a, C> { /// Create new `Lexer`. /// - /// Requiring a `UniquePromise` to be provided guarantees only 1 `Lexer` can exist - /// on a single thread at one time. + /// `brand_origin` is for the `Lexer`'s `Source` (see `Source` docs). pub(super) fn new( allocator: &'a Allocator, source_text: &'a str, source_type: SourceType, config: C, - unique: UniquePromise, + brand_origin: BrandOrigin<'a>, ) -> Self { - let source = Source::new(source_text, unique); + let source = Source::new(source_text, brand_origin); // If collecting tokens, allocate enough space so that the `Vec` will not have to grow during parsing. // `source_text.len() + 1` is almost always a large overestimate of number of tokens, but it's impossible to @@ -160,19 +169,18 @@ impl<'a, C: Config> Lexer<'a, C> { ArenaVec::new_in(&allocator) }; - // The first token is at the start of file, so is allows on a new line - let token = Token::new_on_new_line(); Self { allocator, source, source_type, - token, + token_start: 0, + // The first token is at the start of file, so is always on a new line + pending: PendingToken::START_OF_FILE, errors: vec![], deferred_module_errors: vec![], trivia_builder: TriviaBuilder::new_in(allocator), escaped_strings: FxHashMap::default(), escaped_templates: FxHashMap::default(), - multi_line_comment_end_finder: None, tokens, config, bytes_rewound: 0, @@ -180,17 +188,30 @@ impl<'a, C: Config> Lexer<'a, C> { } } - /// Backdoor to create a `Lexer` without holding a `UniquePromise`, for benchmarks. - /// This function must NOT be exposed in public API as it breaks safety invariants. - #[cfg(feature = "benchmarking")] - pub fn new_for_benchmarks( + /// 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` + /// unique to it. `f` must accept a `Lexer` with any lifetime `'brand`, so code in `f` + /// can't treat `'brand` as the same as any other lifetime. That makes `'brand` a brand + /// (see [`brands`]). + /// + /// For tests and benchmarks only. + /// The parser creates its `Lexer` with `ParserImpl::scope`, and `Lexer::new`. + /// + /// [`brands`]: oxc_data_structures::brands + #[cfg(any(test, feature = "benchmarking"))] + pub fn scope( allocator: &'a Allocator, source_text: &'a str, source_type: SourceType, config: C, - ) -> Self { - let unique = UniquePromise::new_for_tests_and_benchmarks(); - Self::new(allocator, source_text, source_type, config, unique) + f: impl for<'brand> FnOnce(Lexer<'brand, C>) -> R, + ) -> R { + BrandOrigin::scope_within(|brand_origin, _: BrandScope<'_, 'a>| { + // `allocator` and `source_text` are shortened from `'a` to `'brand` here + let lexer = Lexer::new(allocator, source_text, source_type, config, brand_origin); + f(lexer) + }) } /// Get errors. @@ -208,59 +229,29 @@ impl<'a, C: Config> Lexer<'a, C> { /// Creates a checkpoint storing the current lexer state. /// Use `rewind` to restore the lexer to the state stored in the checkpoint. pub fn checkpoint(&self) -> LexerCheckpoint<'a> { - // `token` is always `Token::default()` here, so it does not need to be saved. See `token` field docs. - debug_assert_eq!(self.token, Token::default()); - - let errors_snapshot = if self.errors.is_empty() { - ErrorSnapshot::Empty - } else { - ErrorSnapshot::Count(self.errors.len()) - }; + // `pending` is always `PendingToken::NONE` here, so it does not need to be saved. See `pending` field docs. + debug_assert_eq!(self.pending, PendingToken::NONE); LexerCheckpoint { source_position: self.source.position(), - errors_snapshot, + errors_len: self.errors.len(), tokens_len: self.tokens.len(), - annotation_comments: self.trivia_builder.annotation_comments, - } - } - - /// Create a checkpoint that can handle error popping. - /// This is more expensive as it clones the errors vector. - pub(crate) fn checkpoint_with_error_recovery(&self) -> LexerCheckpoint<'a> { - // `token` is always `Token::default()` here, so it does not need to be saved. See `token` field docs. - debug_assert_eq!(self.token, Token::default()); - - let errors_snapshot = if self.errors.is_empty() { - ErrorSnapshot::Empty - } else { - ErrorSnapshot::Full(self.errors.clone()) - }; - - LexerCheckpoint { - source_position: self.source.position(), - errors_snapshot, - tokens_len: self.tokens.len(), - annotation_comments: self.trivia_builder.annotation_comments, + trivia: self.trivia_builder.checkpoint(), } } /// Rewinds the lexer to the same state as when the passed in `checkpoint` was created. pub fn rewind(&mut self, checkpoint: LexerCheckpoint<'a>) { - // `token` is always `Token::default()` here, so it does not need to be restored. See `token` field docs. - debug_assert_eq!(self.token, Token::default()); + // `pending` is always `PendingToken::NONE` here, so it does not need to be restored. See `pending` field docs. + debug_assert_eq!(self.pending, PendingToken::NONE); - match checkpoint.errors_snapshot { - ErrorSnapshot::Empty => self.errors.clear(), - ErrorSnapshot::Count(len) => self.errors.truncate(len), - ErrorSnapshot::Full(errors) => self.errors = errors, - } + self.errors.truncate(checkpoint.errors_len); self.tokens.truncate(checkpoint.tokens_len); let from = self.offset(); self.source.set_position(checkpoint.source_position); self.bytes_rewound += u64::from(from.saturating_sub(self.offset())); - self.trivia_builder.annotation_comments = checkpoint.annotation_comments; + self.trivia_builder.rewind(checkpoint.trivia); } /// Bytes the lexer has read beyond its current position: those it read @@ -270,6 +261,11 @@ impl<'a, C: Config> Lexer<'a, C> { self.bytes_rewound.saturating_sub(self.bytes_skipped) } + /// 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); + } + pub fn peek_token(&mut self) -> Token { let checkpoint = self.checkpoint(); let token = self.next_token(); @@ -285,18 +281,183 @@ impl<'a, C: Config> Lexer<'a, C> { // SAFETY: Next 2 bytes are `#!` let kind = unsafe { self.read_hashbang_comment() }; // Hashbangs are not included in tokens - self.finish_next_inner(kind, FinishTokenMode::Discard) + self.finish_next_inner(kind, self.source.position(), FinishTokenMode::Discard) } else { - let kind = self.read_next_token(); - self.finish_next(kind) + self.first_token_without_hashbang() } } + /// Read first token, without treating `#!` as the start of a hashbang comment. + /// For source which is not a whole file e.g. a lone expression. + pub fn first_token_without_hashbang(&mut self) -> Token { + let (kind, end) = self.read_next_token(); + self.finish_next_inner(kind, end, FinishTokenMode::Push) + } + /// Read next token in file. - /// Use `first_token` for first token, and this method for all further tokens. + /// + /// Use `first_token` or `first_token_without_hashbang` for first token, and this method for + /// all further tokens. This method relies on `pending` being `PendingToken::NONE`, which it is + /// after any token has been read, but not at the start of the file. Reading the first token + /// with this method gives that token, and a later one, the wrong `is_on_new_line` flag. + /// That is only checked in debug builds. pub fn next_token(&mut self) -> Token { - let kind = self.read_next_token(); - self.finish_next(kind) + self.next_token_impl() + } + + /// Read next token in file. + /// + /// This is inlined into every place the parser advances, so it only contains what most tokens + /// need: skip one space, then either complete a single-byte token, or call a token handler. + // `#[inline(always)]` so `next_token` and `next_token_for_benchmarks` contain the same code + #[expect(clippy::inline_always)] + #[inline(always)] + fn next_token_impl(&mut self) -> Token { + // No trivia has been seen since the previous token. See `pending` field docs. + debug_assert_eq!(self.pending, PendingToken::NONE); + + self.trivia_builder.clear_annotation_comments(); + + let mut pos = self.source.position(); + // SAFETY: `source.end()` is always equal to or after `source.position()` + let remaining_bytes = unsafe { self.source.end().offset_from(pos) }; + if remaining_bytes > TOKEN_HANDLER_MIN_BYTES { + // SAFETY: There are more than `TOKEN_HANDLER_MIN_BYTES` bytes remaining in source + let mut byte = unsafe { pos.read() }; + if byte == b' ' { + // SAFETY: A space is ASCII, and `TOKEN_HANDLER_MIN_BYTES` bytes remain after it + pos = unsafe { pos.add(1) }; + // SAFETY: `TOKEN_HANDLER_MIN_BYTES` bytes remain after the space + byte = unsafe { pos.read() }; + } + + if let Some(kind) = byte_handlers::single_byte_token(byte) { + // SAFETY: Single-byte tokens are ASCII, and at least 1 byte remains after `pos` + let end = unsafe { pos.add(1) }; + self.source.set_position(end); + return self.finish_fresh_token(kind, pos, end); + } + + let token_handlers = &Self::TOKEN_HANDLERS; + // SAFETY: `byte` is the byte at `pos`. `TOKEN_HANDLER_MIN_BYTES` bytes remain from + // `pos`. No trivia has been seen since the previous token, other than one space. + return unsafe { token_handlers[byte as usize](self, pos) }; + } + + self.next_token_after_trivia() + } + + /// Read next token, starting from the current position of source. + /// + /// Token handlers continue here once they have skipped whitespace or a comment. + /// `next_token_impl` calls this if it is at the end of the source. + #[inline(never)] + fn next_token_after_trivia(&mut self) -> Token { + let (kind, end) = self.read_next_token_after_trivia(); + self.finish_next_inner(kind, end, FinishTokenMode::Push) + } + + /// Finish a token which starts at `start` and ends at `end`, where all of these are true: + /// + /// * No trivia was seen between the previous token and it, other than one space. + /// * It has no flags (`escaped` or `has_separator`). + /// * Position of source has been set to `end`. + /// + /// Such a token is not on a new line, and has no comments to attach, so `pending` is neither + /// read nor reset. `token_start` is not read either, so does not need to have been set. + #[expect(clippy::inline_always)] + #[inline(always)] + fn finish_fresh_token( + &mut self, + kind: Kind, + start: SourcePosition<'a>, + end: SourcePosition<'a>, + ) -> Token { + self.finish_token_without_comments(kind, start, end, PendingToken::NONE) + } + + /// Same as `finish_fresh_token`, for a token which only line breaks and regular whitespace + /// were seen before. The token is on a new line. + #[expect(clippy::inline_always)] + #[inline(always)] + fn finish_fresh_token_on_new_line( + &mut self, + kind: Kind, + start: SourcePosition<'a>, + end: SourcePosition<'a>, + ) -> Token { + self.finish_token_without_comments(kind, start, end, PendingToken::AFTER_LINE_BREAK) + } + + /// Finish a token which has no flags, and which no comments were seen before. + /// `trivia` is what else was seen before it. `pending` must not have been altered. + #[expect(clippy::inline_always)] + #[inline(always)] + fn finish_token_without_comments( + &mut self, + kind: Kind, + start: SourcePosition<'a>, + end: SourcePosition<'a>, + trivia: PendingToken, + ) -> Token { + debug_assert_eq!(end, self.source.position()); + debug_assert_ne!(kind, Kind::Skip); + #[cfg(debug_assertions)] + self.assert_byte_handler_produces_token(kind, start, end); + + let token = + Token::new(kind, self.source.offset_of(start), self.source.offset_of(end), trivia); + self.record_token_without_comments(token) + } + + /// Check that the byte handler for the first byte of a token produces that same token, + /// with no flags. + /// + /// Code which finishes a token with `finish_fresh_token` decides for itself where the token + /// ends, what `Kind` it is, and that it has no flags. Byte handlers lex the same token where + /// it follows a comment or other trivia, so the two must agree. This checks that they do, + /// in debug builds, which all tests and conformance runs are. + #[cfg(debug_assertions)] + fn assert_byte_handler_produces_token( + &mut self, + kind: Kind, + start: SourcePosition<'a>, + end: SourcePosition<'a>, + ) { + let token_start = self.token_start; + let error_count = self.errors.len(); + + self.source.set_position(start); + self.token_start = self.source.offset_of(start); + // SAFETY: A token starts at `start`, so it is not the end of the source + let byte = unsafe { start.read() }; + // SAFETY: `byte` is the byte at `start`, which is the current position of source + let byte_handler_kind = unsafe { self.handle_byte(byte) }; + + assert_eq!( + (byte_handler_kind, self.source.position()), + (kind, end), + "Byte handler lexes a different token" + ); + assert_eq!(self.pending, PendingToken::NONE, "Byte handler gives the token flags"); + assert_eq!(self.errors.len(), error_count, "Byte handler reports an error for the token"); + + self.token_start = token_start; + } + + /// Record a finished token, where no comments were seen since the previous token, + /// and `pending` has not been altered since then. + #[expect(clippy::inline_always)] + #[inline(always)] + fn record_token_without_comments(&mut self, token: Token) -> Token { + debug_assert_eq!(self.pending, PendingToken::NONE); + if self.config.tokens() { + // We allocated sufficient capacity in the `Vec` for all tokens at the start. + // `push_fast` is optimized for the "doesn't need to grow" case. + self.tokens.push_fast(token); + } + self.trivia_builder.set_previous_token(token); + token } /// Read the next token after `=` in a JSX attribute. @@ -306,31 +467,37 @@ impl<'a, C: Config> Lexer<'a, C> { } // This is a workaround for a problem where `next_token` is not inlined in lexer benchmark. - // Must be kept in sync with `next_token` above, and contain exactly the same code. + // It contains exactly the same code as `next_token` above, as both only call `next_token_impl`. #[cfg(feature = "benchmarking")] #[expect(clippy::inline_always)] #[inline(always)] pub fn next_token_for_benchmarks(&mut self) -> Token { - let kind = self.read_next_token(); - self.finish_next(kind) + self.next_token_impl() } #[inline] fn finish_next(&mut self, kind: Kind) -> Token { - self.finish_next_inner(kind, FinishTokenMode::Push) + self.finish_next_inner(kind, self.source.position(), FinishTokenMode::Push) } #[inline] fn finish_next_retokenized(&mut self, kind: Kind) -> Token { - self.finish_next_inner(kind, FinishTokenMode::Replace) + self.finish_next_inner(kind, self.source.position(), FinishTokenMode::Replace) } // `#[inline(always)]` to ensure is inlined into `finish_next` and `finish_next_retokenized`, // so that `mode` is statically known #[expect(clippy::inline_always)] #[inline(always)] - fn finish_next_inner(&mut self, kind: Kind, mode: FinishTokenMode) -> Token { - let token = self.token.finish(kind, self.offset()); + fn finish_next_inner( + &mut self, + kind: Kind, + end: SourcePosition<'a>, + mode: FinishTokenMode, + ) -> Token { + debug_assert_eq!(end, self.source.position()); + let pending = mem::replace(&mut self.pending, PendingToken::NONE); + let token = Token::new(kind, self.token_start, self.source.offset_of(end), pending); if self.config.tokens() { match mode { FinishTokenMode::Push => { @@ -348,22 +515,20 @@ impl<'a, C: Config> Lexer<'a, C> { FinishTokenMode::Discard => {} } } - self.trivia_builder.handle_token(token); - self.token = Token::default(); + self.trivia_builder.handle_token(token, pending); token } /// Finish a re-lexed token used only for parser disambiguation. /// This must not mutate the externally collected token stream. - fn finish_re_lex(&mut self, kind: Kind) -> Token { - let token = self.token.finish(kind, self.offset()); - self.token = Token::default(); - token + fn finish_re_lex(&self, kind: Kind) -> Token { + debug_assert_eq!(self.pending, PendingToken::NONE); + Token::new(kind, self.token_start, self.offset(), PendingToken::NONE) } /// Overwrite the last token in the collected token stream. /// - /// Used by `re_lex_as_typescript_l_angle` to replace a compound token (`<<`, `<=` or `<<=`) + /// Used by `re_lex_as_typescript_l_angle` to replace a compound token (`<<` or `<<=`) /// with the single `<` it re-lexed, and to restore the compound token when `try_parse` /// fails and rewinds. #[inline] @@ -441,7 +606,7 @@ impl<'a, C: Config> Lexer<'a, C> { /// Get the current unterminated token range fn unterminated_range(&self) -> Span { - Span::new(self.token.start(), self.offset()) + Span::new(self.token_start, self.offset()) } /// Consume the current char if not at EOF @@ -504,6 +669,7 @@ impl<'a, C: Config> Lexer<'a, C> { } /// Return `IllegalCharacter` Error or `UnexpectedEnd` if EOF + #[cold] fn unexpected_err(&mut self) { let offset = self.current_offset(); match self.peek_char() { @@ -514,16 +680,22 @@ impl<'a, C: Config> Lexer<'a, C> { /// Read each char and set the current token /// Whitespace and line terminators are skipped - #[inline] // Make sure is inlined into `next_token` - fn read_next_token(&mut self) -> Kind { + /// Returns the `Kind` of the token, and the position of its end, which is current position of source. + #[inline] // Make sure is inlined into `first_token` + fn read_next_token(&mut self) -> (Kind, SourcePosition<'a>) { self.trivia_builder.clear_annotation_comments(); + self.read_next_token_after_trivia() + } + /// Same as `read_next_token`, but keeps any annotation comments found before the token so far. + #[inline] + fn read_next_token_after_trivia(&mut self) -> (Kind, SourcePosition<'a>) { let end_pos = self.source.end(); + let mut pos = self.source.position(); loop { // Single spaces between tokens are common, so consume a space before processing the next token. // Can only do this if there are at least 2 bytes left in source. // If there aren't 2 bytes left, delegate to `read_next_token_at_end` (cold branch). - let mut pos = self.source.position(); // SAFETY: `source.end()` is always equal to or after `source.position()` let remaining_bytes = unsafe { end_pos.offset_from(pos) }; if remaining_bytes >= 2 { @@ -542,17 +714,27 @@ impl<'a, C: Config> Lexer<'a, C> { // Set token start let offset = self.source.offset_of(pos); - self.token.set_start(offset); + self.token_start = offset; + if let Some(kind) = byte_handlers::single_byte_token(byte) { + // SAFETY: Single-byte tokens are ASCII, and at least 1 byte remains after `pos` + let end = unsafe { pos.add(1) }; + self.source.set_position(end); + return (kind, end); + } + + let byte_handlers = self.config.byte_handlers(); + let kind; // SAFETY: `byte` is byte value at current position in source - let kind = unsafe { self.handle_byte(byte) }; + (kind, pos) = unsafe { byte_handlers[byte as usize](self, pos) }; if kind != Kind::Skip { - return kind; + return (kind, pos); } } else { // Only 0 or 1 bytes left in source. // Delegate to `#[cold]` function as this is a very rare case. - return self.read_next_token_at_end(); + let kind = self.read_next_token_at_end(); + return (kind, self.source.position()); } } } @@ -562,7 +744,7 @@ impl<'a, C: Config> Lexer<'a, C> { #[cold] fn read_next_token_at_end(&mut self) -> Kind { let offset = self.offset(); - self.token.set_start(offset); + self.token_start = offset; if let Some(byte) = self.peek_byte() { // SAFETY: `byte` is byte value at current position in source @@ -571,7 +753,7 @@ impl<'a, C: Config> Lexer<'a, C> { return kind; } // Last byte was whitespace/line break (`Kind::Skip`), so now at EOF - self.token.set_start(offset + 1); + self.token_start = offset + 1; } Kind::Eof @@ -601,7 +783,7 @@ impl<'a, C: Config> Lexer<'a, C> { } let offset = self.source.offset_of(pos); - self.token.set_start(offset); + self.token_start = offset; if matches!(byte, b'"' | b'\'') { // SAFETY: `byte` is the current ASCII quote delimiter. @@ -623,7 +805,7 @@ impl<'a, C: Config> Lexer<'a, C> { #[cold] fn read_next_jsx_attribute_value_at_end(&mut self) -> Kind { let offset = self.offset(); - self.token.set_start(offset); + self.token_start = offset; if let Some(byte) = self.peek_byte() { if matches!(byte, b'"' | b'\'') { @@ -636,7 +818,7 @@ impl<'a, C: Config> Lexer<'a, C> { if kind != Kind::Skip { return kind; } - self.token.set_start(offset + 1); + self.token_start = offset + 1; } Kind::Eof diff --git a/vendor/oxc_parser/src/lexer/number.rs b/vendor/oxc_parser/src/lexer/number.rs index 7f0a1e0eb..c428dd11c 100644 --- a/vendor/oxc_parser/src/lexer/number.rs +++ b/vendor/oxc_parser/src/lexer/number.rs @@ -414,10 +414,10 @@ pub fn parse_big_int<'a>( let radix = match kind { // Skip parsing with `BigInt` - it's already in decimal form, and underscores are removed - Kind::Decimal => return Str::from_cow_in(&s, &allocator), - Kind::Binary => 2, - Kind::Octal => 8, - Kind::Hex => 16, + Kind::DecimalBigInt => return Str::from_cow_in(&s, &allocator), + Kind::BinaryBigInt => 2, + Kind::OctalBigInt => 8, + Kind::HexBigInt => 16, _ => unreachable!(), }; @@ -548,7 +548,11 @@ mod test { #[test] #[expect(clippy::cast_precision_loss)] fn test_nondecimal_rounding_boundaries() { - for bits in 54..128 { + // Under Miri, the full sweep takes over 7 minutes. Check only the smallest and largest widths, + // and widths on both sides of each radix's fast path length limit (octal 62/63, binary/hex 63/64). + let widths = + (54..128).filter(|bits| !cfg!(miri) || matches!(bits, 54 | 62 | 63 | 64 | 127)); + for bits in widths { let base = 1_u128 << bits; let half_ulp = 1_u128 << (bits - 53); // Both even and odd significands, immediately below, at, and above halfway. diff --git a/vendor/oxc_parser/src/lexer/numeric.rs b/vendor/oxc_parser/src/lexer/numeric.rs index 34f8ab059..f06e6d6e1 100644 --- a/vendor/oxc_parser/src/lexer/numeric.rs +++ b/vendor/oxc_parser/src/lexer/numeric.rs @@ -4,6 +4,25 @@ use crate::{config::LexerConfig as Config, diagnostics}; use super::{Kind, Lexer, Span, cold_branch}; +/// Whether a byte which follows decimal digits means those digits are a whole numeric literal. +/// +/// That is the case if the byte cannot continue the literal, and is valid straight after it, +/// which is any ASCII byte other than a letter, a digit, `_`, `$` or `.`. +/// See `read_zero`, `decimal_literal_after_first_digit` and `check_after_numeric_literal`. +#[inline] +pub(super) fn ends_decimal_integer(byte: u8) -> bool { + static TABLE: [bool; 256] = { + let mut table = [false; 256]; + let mut byte = 0u8; + while byte < 128 { + table[byte as usize] = !is_identifier_part_ascii(byte as char) && byte != b'.'; + byte += 1; + } + table + }; + TABLE[byte as usize] +} + impl Lexer<'_, C> { /// 12.9.3 Numeric Literals with `0` prefix pub(super) fn read_zero(&mut self) -> Kind { @@ -69,11 +88,14 @@ impl Lexer<'_, C> { // This seems to be a waste. It also requires us to put this // call here instead of after we ensure the next character // is a number character - self.token.set_has_separator(true); + self.pending.set_has_separator(); if self.peek_byte().is_some_and(|b| kind.matches_number_byte(b)) { self.consume_char(); } else { - self.unexpected_err(); + self.error(diagnostics::invalid_numeric_separator(Span::new( + self.offset() - 1, + self.offset(), + ))); self.advance_to_end(); return Kind::Eof; } @@ -164,11 +186,14 @@ impl Lexer<'_, C> { // This seems to be a waste. It also requires us to put this // call here instead of after we ensure the next character // is an ASCII digit - self.token.set_has_separator(true); + self.pending.set_has_separator(); if self.peek_byte().is_some_and(|b| b.is_ascii_digit()) { self.consume_char(); } else { - self.unexpected_err(); + self.error(diagnostics::invalid_numeric_separator(Span::new( + self.offset() - 1, + self.offset(), + ))); return; } } diff --git a/vendor/oxc_parser/src/lexer/punctuation.rs b/vendor/oxc_parser/src/lexer/punctuation.rs index 0025aa561..c640b72f6 100644 --- a/vendor/oxc_parser/src/lexer/punctuation.rs +++ b/vendor/oxc_parser/src/lexer/punctuation.rs @@ -38,8 +38,8 @@ impl Lexer<'_, C> { // the `<` byte-handler's stack frame on the common `<`/`<<`/`<=` path. Some(b'!') if self.remaining().starts_with("!--") => cold_branch(|| { if self.source_type.is_module() { - if self.token.is_on_new_line() { - let span = Span::sized(self.token.start(), 4); + if self.pending.is_on_new_line() { + let span = Span::sized(self.token_start, 4); self.errors.push(diagnostics::html_comment_in_module(span)); None } else { @@ -61,7 +61,7 @@ impl Lexer<'_, C> { Some(b'-') => { self.consume_char(); // `-->` HTML comment (Annex B.1.1) - not recognized in strict mode (.mjs) - if self.token.is_on_new_line() + if self.pending.is_on_new_line() && !self.source_type.is_strict() && self.next_ascii_byte_eq(b'>') { @@ -82,13 +82,13 @@ impl Lexer<'_, C> { /// Defer HTML comment error for unambiguous mode (emitted if file resolves to module) fn defer_html_comment_error(&mut self, len: u32) { if self.source_type.is_unambiguous() { - let span = Span::sized(self.token.start(), len); + let span = Span::sized(self.token_start, len); self.deferred_module_errors.push(diagnostics::html_comment_in_module(span)); } } pub(crate) fn re_lex_right_angle(&mut self) -> Token { - self.token.set_start(self.offset() - 1); + self.token_start = self.offset() - 1; let kind = self.read_right_angle(); self.finish_next_retokenized(kind) } diff --git a/vendor/oxc_parser/src/lexer/regex.rs b/vendor/oxc_parser/src/lexer/regex.rs index 9010a0658..f6dd573b7 100644 --- a/vendor/oxc_parser/src/lexer/regex.rs +++ b/vendor/oxc_parser/src/lexer/regex.rs @@ -17,14 +17,12 @@ impl Lexer<'_, C> { /// Which means the parser needs to re-tokenize on `PrimaryExpression`, /// `RegularExpressionLiteral` only appear on the right hand side of `PrimaryExpression` pub(crate) fn next_regex(&mut self, kind: Kind) -> (Token, u32, RegExpFlags) { - self.token.set_start( - self.offset() - - match kind { - Kind::Slash => 1, - Kind::SlashEq => 2, - _ => unreachable!(), - }, - ); + self.token_start = self.offset() + - match kind { + Kind::Slash => 1, + Kind::SlashEq => 2, + _ => unreachable!(), + }; let (pattern_end, flags) = self.read_regex(); let token = self.finish_next_retokenized(Kind::RegExp); (token, pattern_end, flags) diff --git a/vendor/oxc_parser/src/lexer/source.rs b/vendor/oxc_parser/src/lexer/source.rs index a1ed1b353..47c9e25c7 100644 --- a/vendor/oxc_parser/src/lexer/source.rs +++ b/vendor/oxc_parser/src/lexer/source.rs @@ -1,8 +1,11 @@ -use std::{cmp::Ordering, marker::PhantomData, slice, str}; +use std::{cmp::Ordering, slice, str}; -use oxc_data_structures::assert_unchecked; +use oxc_data_structures::{ + assert_unchecked, + brands::{Brand, BrandOrigin}, +}; -use crate::{MAX_LEN, UniquePromise}; +use crate::MAX_LEN; use super::search::SEARCH_BATCH_SIZE; @@ -60,6 +63,23 @@ use super::search::SEARCH_BATCH_SIZE; /// are satisfied, to restore this invariant before passing control back to other code. /// It will often be preferable to instead use `Source::peek_byte`, followed by `Source::next_char`, /// which are safe methods, and compiler will often reduce to equally efficient code. +/// +/// # Brand +/// +/// `'a` is the lifetime of the source text. It's also this `Source`'s brand (see [`brands`]). +/// +/// - No other `Source` has the same `'a`. +/// - Every `SourcePosition` which this `Source` creates carries its brand, so has the same `'a`. +/// +/// So a `SourcePosition<'a>` can only have been created by this `Source<'a>`, +/// or derived from one which it created (`SourcePosition::add`, `SourcePosition::sub`). +/// That's why methods which take a `SourcePosition<'a>` (e.g. `Source::set_position`) +/// can rely on it being within this `Source`'s source text, without checking. +/// +/// `Source::new` takes the [`BrandOrigin<'a>`] by value. +/// There's only one `BrandOrigin` for each `'a`, so there's only one `Source` for each `'a`. +/// +/// [`brands`]: oxc_data_structures::brands pub(super) struct Source<'a> { /// Pointer to start of source string. Never altered after initialization. start: *const u8, @@ -71,17 +91,16 @@ pub(super) struct Source<'a> { /// `SEARCH_BATCH_SIZE` bytes in one go. /// Must be `usize`, not a pointer, as if source is very short, a pointer could be out of bounds. end_for_batch_search_addr: usize, - /// Marker for immutable borrow of source string - _marker: PhantomData<&'a str>, + /// Origin of this `Source`'s brand `'a` (see above). + /// Also acts as the marker for the immutable borrow of source string. + brand_origin: BrandOrigin<'a>, } impl<'a> Source<'a> { /// Create `Source` from `&str`. /// - /// Requiring a `UniquePromise` to be provided guarantees only 1 `Source` can exist - /// on a single thread at one time. - #[expect(unused_variables, clippy::needless_pass_by_value)] - pub(super) fn new(mut source_text: &'a str, unique: UniquePromise) -> Self { + /// `brand_origin` is the origin of this `Source`'s brand `'a` (see [`Source`] docs). + pub(super) fn new(mut source_text: &'a str, brand_origin: BrandOrigin<'a>) -> Self { // If source text exceeds size limit, substitute a short source text which will fail to parse. // `Parser::parse` will convert error to `diagnostics::overlong_source()`. if source_text.len() > MAX_LEN { @@ -100,7 +119,7 @@ impl<'a> Source<'a> { // will always test positive, and disable batch search. let end_for_batch_search_addr = (end as usize).saturating_sub(SEARCH_BATCH_SIZE); - Self { start, end, ptr: start, end_for_batch_search_addr, _marker: PhantomData } + Self { start, end, ptr: start, end_for_batch_search_addr, brand_origin } } /// Get entire source text as `&str`. @@ -132,14 +151,14 @@ impl<'a> Source<'a> { #[inline] fn start(&self) -> SourcePosition<'a> { // SAFETY: `start` is the start of source, so in bounds and on a UTF-8 char boundary - unsafe { SourcePosition::new(self.start) } + unsafe { SourcePosition::new(self.start, self.brand_origin.brand()) } } /// Get [`SourcePosition`] for end of source. #[inline] pub(super) fn end(&self) -> SourcePosition<'a> { // SAFETY: `end` is the end of source, so in bounds and on a UTF-8 char boundary - unsafe { SourcePosition::new(self.end) } + unsafe { SourcePosition::new(self.end, self.brand_origin.brand()) } } /// Return whether at end of source. @@ -160,20 +179,15 @@ impl<'a> Source<'a> { pub(super) fn position(&self) -> SourcePosition<'a> { // SAFETY: Creating a `SourcePosition` from current position of `Source` is always valid, // if caller has upheld safety conditions of other unsafe methods of this type. - unsafe { SourcePosition::new(self.ptr) } + unsafe { SourcePosition::new(self.ptr, self.brand_origin.brand()) } } /// Move current position. #[inline] pub(super) fn set_position(&mut self, pos: SourcePosition<'a>) { - // `SourcePosition` always upholds the invariants of `Source`, as long as it's created - // from this `Source`. `SourcePosition`s can only be created from a `Source`. - // `Source::new` takes a `UniquePromise`, which guarantees that it's the only `Source` - // in existence on this thread. `Source` is not `Sync` or `Send`, so no possibility another - // `Source` originated on another thread can "jump" onto this one. - // This is sufficient to guarantee that any `SourcePosition` that parser/lexer holds must be - // from this `Source`. - // This guarantee is what allows this function to be safe. + // A `SourcePosition` upholds the invariants of the `Source` which created it. + // `pos` has the same brand `'a` as this `Source`, so this `Source` created it. + // That's what allows this function to be safe. // SAFETY: `SourcePosition::read`'s contract is upheld by: // * The preceding checks that `pos.ptr` >= `self.start` and < `self.end`. @@ -283,13 +297,9 @@ impl<'a> Source<'a> { } // SAFETY: Caller guarantees `start` is not after `end`. - // `SourcePosition`s can only be created from a `Source`. - // `Source::new` takes a `UniquePromise`, which guarantees that it's the only `Source` - // in existence on this thread. `Source` is not `Sync` or `Send`, so no possibility another - // `Source` originated on another thread can "jump" onto this one. - // This is sufficient to guarantee that any `SourcePosition` that parser/lexer holds must be - // from this `Source`, therefore `start.ptr` and `end.ptr` must both be within the same - // allocation, and derived from the same original pointer. + // `start` and `end` have the same brand `'a` as this `Source`, so this `Source` + // created both. So `start.ptr` and `end.ptr` are both within this `Source`'s allocation, + // and derived from the same pointer. // Invariants of `Source` and `SourcePosition` types guarantee that both are positioned // on UTF-8 character boundaries. So slicing source text between these 2 points will always // yield a valid UTF-8 string. @@ -315,14 +325,16 @@ impl<'a> Source<'a> { /// Get offset of `pos` as `u32`. #[inline] pub(super) fn offset_of(&self, pos: SourcePosition<'a>) -> u32 { - // SAFETY: All `SourcePosition`s are always in bounds of the source text, which starts at `start` + // SAFETY: `pos` has the same brand `'a` as this `Source`, so this `Source` created it. + // So it's within this `Source`'s source text, which starts at `start`. unsafe { pos.offset_from_u32(self.start()) } } /// Get offset of `pos` as `usize`. #[inline] pub(super) fn offset_of_usize(&self, pos: SourcePosition<'a>) -> usize { - // SAFETY: All `SourcePosition`s are always in bounds of the source text, which starts at `start` + // SAFETY: `pos` has the same brand `'a` as this `Source`, so this `Source` created it. + // So it's within this `Source`'s source text, which starts at `start`. unsafe { pos.offset_from(self.start()) } } @@ -615,27 +627,34 @@ impl<'a> Source<'a> { /// Wrapper around a pointer to a position in `Source`. /// +/// `'a` is the brand of the `Source` which created it (see [`Source`] docs). +/// So a `SourcePosition<'a>` can only be used with that `Source<'a>`, +/// and with other `SourcePosition<'a>`s which it created. +/// /// # SAFETY /// `SourcePosition` must always be on a UTF-8 character boundary, /// and within bounds of the `Source` that created it. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct SourcePosition<'a> { ptr: *const u8, - _marker: PhantomData<&'a u8>, + /// Brand of the `Source<'a>` which created this position. + brand: Brand<'a>, } impl<'a> SourcePosition<'a> { /// Create a new `SourcePosition` from a pointer. /// + /// `brand` is the brand of the `Source` which the position belongs to. + /// /// # SAFETY /// * Pointer must obey all the same invariants as `Source::ptr`. - /// * It must be created from a `Source`. - /// * It must be in bounds of the source text `&str` the `Source` is created from, + /// * It must be created from the `Source` which `brand` is the brand of. + /// * It must be in bounds of the source text `&str` that `Source` is created from, /// or 1 byte after the end of the source text (i.e. positioned at EOF). /// * It must be positioned on a UTF-8 character boundary (or EOF). #[inline] - pub(super) unsafe fn new(ptr: *const u8) -> Self { - Self { ptr, _marker: PhantomData } + pub(super) unsafe fn new(ptr: *const u8, brand: Brand<'a>) -> Self { + Self { ptr, brand } } /// Create new `SourcePosition` which is `n` bytes after this one. @@ -649,7 +668,7 @@ impl<'a> SourcePosition<'a> { #[inline] pub(super) unsafe fn add(self, n: usize) -> Self { // SAFETY: Caller guarantees that `add` will not go out of bounds - unsafe { Self::new(self.ptr.add(n)) } + unsafe { Self::new(self.ptr.add(n), self.brand) } } /// Create new `SourcePosition` which is `n` bytes before this one. @@ -661,7 +680,7 @@ impl<'a> SourcePosition<'a> { #[inline] pub(super) unsafe fn sub(self, n: usize) -> Self { // SAFETY: Caller guarantees that `sub` will not go out of bounds - unsafe { Self::new(self.ptr.sub(n)) } + unsafe { Self::new(self.ptr.sub(n), self.brand) } } /// Get the distance between this [`SourcePosition`] and another [`SourcePosition`] as `usize`. @@ -671,7 +690,8 @@ impl<'a> SourcePosition<'a> { #[inline] pub(super) unsafe fn offset_from(self, origin: Self) -> usize { // SAFETY: Caller guarantees `self` is not before `origin`. - // All `SourcePosition<'a>`s are within bounds of same source text. + // Both have the same brand `'a`, so the same `Source` created both, + // and they're within the same allocation. unsafe { self.ptr.offset_from_unsigned(origin.ptr) } } @@ -695,7 +715,8 @@ impl<'a> SourcePosition<'a> { /// negative if `self` is before `other`, or 0 if they're the same. #[inline] fn offset_from_signed(self, other: Self) -> isize { - // SAFETY: All `SourcePosition<'a>`s are within bounds of same source text + // SAFETY: Both have the same brand `'a`, so the same `Source` created both, + // and they're within the same allocation unsafe { self.ptr.offset_from(other.ptr) } } @@ -785,7 +806,7 @@ impl<'a> SourcePosition<'a> { } // Implement `Ord` and `PartialOrd` using `(*const u8)::offset_from` to utilize the invariant -// that `SourcePosition`s are always within the same allocation. +// that `SourcePosition`s with the same `'a` are always within the same allocation. impl Ord for SourcePosition<'_> { #[inline] fn cmp(&self, other: &Self) -> Ordering { diff --git a/vendor/oxc_parser/src/lexer/string.rs b/vendor/oxc_parser/src/lexer/string.rs index cdaa3e0c6..d8f60866c 100644 --- a/vendor/oxc_parser/src/lexer/string.rs +++ b/vendor/oxc_parser/src/lexer/string.rs @@ -5,7 +5,7 @@ use oxc_str::{JSStr, JSStrBuilder}; use crate::{config::LexerConfig as Config, diagnostics}; use super::{ - Kind, Lexer, Span, Token, cold_branch, + FinishTokenMode, Kind, Lexer, SourcePosition, Span, Token, cold_branch, search::{SafeByteMatchTable, byte_search, safe_byte_match_table}, }; @@ -51,48 +51,90 @@ fn find_string_chunk_end( /// `$table` must only match `$delimiter`, '\', '\r' or '\n'. macro_rules! handle_string_literal { ($lexer:ident, $delimiter:literal, $table:ident) => {{ + let pos = $lexer.source.position(); + match handle_plain_string_literal!($lexer, pos, $delimiter, $table) { + Ok(_) => Kind::Str, + // An escape, or an unterminated string, which is invalid JS. Either way, a cold path. + // Building the diagnostic out-of-line keeps the `OxcDiagnostic` return buffer out of + // this handler's stack frame. + Err(next_byte) => cold_branch(|| { + handle_string_literal_rest!($lexer, pos, $delimiter, $table, next_byte) + }), + } + }}; +} + +/// Macro to read a string literal up to its closing quote, or to the first thing in it which is not +/// plain text. The opening quote is at `$pos`. +/// +/// Evaluates to `Ok(end)` if the string contains no escapes. `end` is the position after the closing +/// quote, and position of `lexer.source` has been set to it. +/// +/// Otherwise evaluates to `Err(byte)`, and `handle_string_literal_rest!` handles the rest of the string: +/// * `byte` is `\`, `\r` or `\n`: position of `lexer.source` is on that byte. +/// * `byte` is 0: the source ended. Position of `lexer.source` is the end of the source. +/// +/// # SAFETY +/// `$delimiter` must be an ASCII byte. +/// `$pos` must be the position of a `$delimiter` byte. +/// `$table` must be a `SafeByteMatchTable`. +/// `$table` must only match `$delimiter`, '\', '\r' or '\n'. +macro_rules! handle_plain_string_literal { + ($lexer:ident, $pos:ident, $delimiter:literal, $table:ident) => {{ debug_assert!($delimiter.is_ascii()); // Skip opening quote. - // SAFETY: Caller guarantees next byte is ASCII, so safe to advance past it. - let after_opening_quote = $lexer.source.position().add(1); + // SAFETY: Caller guarantees byte at `$pos` is ASCII, so safe to advance past it. + let after_opening_quote = $pos.add(1); // Consume bytes which are part of string let next_byte = byte_search! { lexer: $lexer, table: $table, start: after_opening_quote, - handle_eof: { - // Unterminated string is invalid JS, so a cold path. Building the diagnostic - // out-of-line keeps the `OxcDiagnostic` return buffer out of this handler's - // stack frame (matching the sibling `\\` and line-break arms below). - return cold_branch(|| { - $lexer.error(diagnostics::unterminated_string($lexer.unterminated_range())); - Kind::Undetermined - }); - }, + // `$table` does not match 0, so the search only produces it at EOF + handle_eof: 0, }; - // Found a matching byte. - // Either end of string found, or a line break, or `\` escape. - match next_byte { - $delimiter => { - // SAFETY: Macro user guarantees delimiter is ASCII, so consuming it cannot move - // `lexer.source` off a UTF-8 character boundary. - $lexer.source.next_byte_unchecked(); - Kind::Str - } - b'\\' => cold_branch(|| { + if next_byte == $delimiter { + // SAFETY: Macro user guarantees delimiter is ASCII, so consuming it cannot move + // `lexer.source` off a UTF-8 character boundary. + let end = $lexer.source.position().add(1); + $lexer.source.set_position(end); + Ok(end) + } else { + Err(next_byte) + } + }}; +} + +/// Macro to handle the rest of a string literal whose opening quote is at `$pos`, +/// after `handle_plain_string_literal!` evaluated to `Err($next_byte)` for it. +/// +/// Evaluates to the `Kind` of the token. May also return it from the enclosing function. +/// +/// # SAFETY +/// As for `handle_plain_string_literal!`. +/// Position of `lexer.source` must be where `handle_plain_string_literal!` left it. +macro_rules! handle_string_literal_rest { + ($lexer:ident, $pos:ident, $delimiter:literal, $table:ident, $next_byte:ident) => {{ + match $next_byte { + b'\\' => { + // SAFETY: Macro user guarantees byte at `$pos` is ASCII, so safe to advance past it. + let after_opening_quote = $pos.add(1); handle_string_literal_escape!($lexer, $delimiter, $table, after_opening_quote) - }), + } + 0 => { + // End of source + $lexer.error(diagnostics::unterminated_string($lexer.unterminated_range())); + Kind::Undetermined + } _ => { - // Line break. This is impossible in valid JS, so cold path. - cold_branch(|| { - debug_assert!(matches!(next_byte, b'\r' | b'\n')); - $lexer.consume_char(); - $lexer.error(diagnostics::unterminated_string($lexer.unterminated_range())); - Kind::Undetermined - }) + // Line break + debug_assert!(matches!($next_byte, b'\r' | b'\n')); + $lexer.consume_char(); + $lexer.error(diagnostics::unterminated_string($lexer.unterminated_range())); + Kind::Undetermined } } }}; @@ -100,16 +142,90 @@ macro_rules! handle_string_literal { macro_rules! handle_string_literal_escape { ($lexer:ident, $delimiter:literal, $table:ident, $after_opening_quote:ident) => {{ - // Create arena string to hold unescaped string. - // We don't know how long string will end up being. Take a guess that total length - // will be double what we've seen so far, or `MIN_ESCAPED_STR_LEN` minimum. let so_far = $lexer.source.str_from_pos_to_current($after_opening_quote); - let capacity = max(so_far.len() * 2, MIN_ESCAPED_STR_LEN); - let mut str = JSStrBuilder::with_capacity_in(capacity, &$lexer.allocator); + if so_far.is_empty() && $lexer.read_single_character_escape::<$delimiter>() { + return Kind::Str; + } + + // Decode the first escape before allocating. Each escape produces at most one + // code point (or no text for a line continuation). + let escape_start_offset = $lexer.offset(); + $lexer.consume_char(); + let after_backslash = $lexer.source.position(); + let mut is_valid_escape_sequence = true; + let first = $lexer.decode_string_escape_sequence(false, &mut is_valid_escape_sequence); + if !is_valid_escape_sequence { + let range = Span::new(escape_start_offset, $lexer.offset()); + $lexer.error(diagnostics::invalid_escape_sequence(range)); + } - // Push chunk before `\` into `str`. + let chunk_start = $lexer.source.position(); + let remaining = $lexer.source.remaining().as_bytes(); + let Some(end) = find_string_chunk_end::<$delimiter>(remaining, &$table) else { + $lexer.source.advance_to_end(); + $lexer.error(diagnostics::unterminated_string($lexer.unterminated_range())); + return Kind::Undetermined; + }; + let b = remaining[end]; + // SAFETY: The match is an in-bounds ASCII byte, hence a UTF-8 character boundary. + $lexer.source.set_position(chunk_start.add(end)); + let chunk = $lexer.source.str_from_pos_to_current(chunk_start); + if b != $delimiter && b != b'\\' { + return cold_branch(|| { + debug_assert!(matches!(b, b'\r' | b'\n')); + $lexer.consume_char(); + $lexer.error(diagnostics::unterminated_string($lexer.unterminated_range())); + Kind::Undetermined + }); + } + + if b == $delimiter && is_valid_escape_sequence { + // Identity escapes and one-sided line continuations can leave the decoded + // value in one contiguous source span. + let borrowed = match first { + None if so_far.is_empty() => Some(chunk), + None if chunk.is_empty() => Some(so_far), + Some(value) if so_far.is_empty() => value.to_char().and_then(|c| { + let source_value = $lexer.source.str_from_pos_to_current(after_backslash); + let escape_len = source_value.len() - chunk.len(); + // Check the whole escape payload, so `\u0075` cannot borrow `u0075`. + (escape_len == c.len_utf8() && source_value.starts_with(c)) + .then_some(source_value) + }), + _ => None, + }; + if let Some(value) = borrowed { + // SAFETY: The closing quote is ASCII, so consuming it preserves a UTF-8 boundary. + $lexer.source.next_byte_unchecked(); + $lexer.save_js_string(value.into()); + return Kind::Str; + } + } + + // With no further escape, the final size is known. The source chunks are UTF-8, + // so neither can form a surrogate pair with the decoded escape. + let capacity = if b == $delimiter { + so_far.len() + first.map_or(0, |c| c.len_bytes()) + chunk.len() + } else { + max(so_far.len() * 2, MIN_ESCAPED_STR_LEN) + }; + let mut str = JSStrBuilder::with_capacity_in(capacity, &$lexer.allocator); str.push_str(so_far); + if let Some(first) = first { + if let Some(c) = first.to_char() { + str.push(c); + } else { + str.push_js_char(first); + } + } + str.push_str(chunk); + if b == $delimiter { + // SAFETY: The closing quote is ASCII, so consuming it preserves a UTF-8 boundary. + $lexer.source.next_byte_unchecked(); + $lexer.save_js_string(str.into_js_str()); + return Kind::Str; + } loop { // Consume `\` let escape_start_offset = $lexer.offset(); @@ -171,6 +287,43 @@ macro_rules! handle_string_literal_escape { /// 12.9.4 String Literals impl<'a, C: Config> Lexer<'a, C> { + /// Decode a single common escape without growing an arena string. + #[inline] + fn read_single_character_escape(&mut self) -> bool { + let remaining = self.source.remaining(); + let [b'\\', escape, delimiter, ..] = remaining.as_bytes() else { + return false; + }; + if *delimiter != DELIMITER { + return false; + } + let value = match escape { + b'\'' => "'", + b'\"' => "\"", + b'\\' => "\\", + b'b' => "\u{8}", + b'f' => "\u{c}", + b'n' => "\n", + b'r' => "\r", + b't' => "\t", + b'v' => "\u{b}", + // The closing quote guarantees this cannot start an octal escape. + b'0' => "\0", + _ => return false, + }; + // Raw transfer requires nonempty strings to reside in the source or arena. + let value = if matches!(escape, b'\'' | b'"' | b'\\') { + JSStr::from(&remaining[1..2]) + } else { + JSStr::from_str_in(value, &self.allocator) + }; + // SAFETY: The matched escape and closing quote are three in-bounds ASCII bytes. + let end = unsafe { self.source.position().add(3) }; + self.source.set_position(end); + self.save_js_string(value); + true + } + /// Read string literal delimited with `"`. /// # SAFETY /// Next character must be `"`. @@ -189,9 +342,105 @@ impl<'a, C: Config> Lexer<'a, C> { unsafe { handle_string_literal!(self, b'\'', SINGLE_QUOTE_STRING_END_TABLE) } } + /// Read string literal delimited with `"`, up to its closing quote, or to the first thing in it + /// which is not plain text. + /// + /// Returns `Ok(end)` if the string contains no escapes. `end` is the position after the closing + /// quote, which position of source has been set to. + /// + /// Otherwise returns `Err(next_byte)`. `string_token_rest_double_quote` reads the rest. + /// + /// # SAFETY + /// `pos` must be the position of a `"`. + #[expect(clippy::inline_always)] + #[inline(always)] + pub(super) unsafe fn read_plain_string_literal_double_quote( + &mut self, + pos: SourcePosition<'a>, + ) -> Result, u8> { + // SAFETY: Caller guarantees byte at `pos` is `"`, which is ASCII. + // `DOUBLE_QUOTE_STRING_END_TABLE` is a `SafeByteMatchTable`. + unsafe { handle_plain_string_literal!(self, pos, b'"', DOUBLE_QUOTE_STRING_END_TABLE) } + } + + /// Read string literal delimited with `'`, up to its closing quote, or to the first thing in it + /// which is not plain text. + /// + /// Returns `Ok(end)` if the string contains no escapes. `end` is the position after the closing + /// quote, which position of source has been set to. + /// + /// Otherwise returns `Err(next_byte)`. `string_token_rest_single_quote` reads the rest. + /// + /// # SAFETY + /// `pos` must be the position of a `'`. + #[expect(clippy::inline_always)] + #[inline(always)] + pub(super) unsafe fn read_plain_string_literal_single_quote( + &mut self, + pos: SourcePosition<'a>, + ) -> Result, u8> { + // SAFETY: Caller guarantees byte at `pos` is `'`, which is ASCII. + // `SINGLE_QUOTE_STRING_END_TABLE` is a `SafeByteMatchTable`. + unsafe { handle_plain_string_literal!(self, pos, b'\'', SINGLE_QUOTE_STRING_END_TABLE) } + } + + /// Read the rest of the string literal whose opening `"` is at `pos`, and finish the token, + /// after `read_plain_string_literal_double_quote` returned `Err(next_byte)` for it. + /// + /// The string contains an escape, or is unterminated. Neither is common. + /// `pending` must reflect the trivia seen since the previous token. + /// + /// # SAFETY + /// * `pos` must be the position of a `"`. + /// * Position of source must be where `read_plain_string_literal_double_quote` left it. + #[cold] + #[inline(never)] + pub(super) unsafe fn string_token_rest_double_quote( + &mut self, + pos: SourcePosition<'a>, + next_byte: u8, + ) -> Token { + // Escaped strings and diagnostics are recorded against `token_start` + self.token_start = self.source.offset_of(pos); + // SAFETY: Caller guarantees byte at `pos` is `"`, which is ASCII, and that position + // of source is as `handle_plain_string_literal!` left it. + // `DOUBLE_QUOTE_STRING_END_TABLE` is a `SafeByteMatchTable`. + let kind = cold_branch(|| unsafe { + handle_string_literal_rest!(self, pos, b'"', DOUBLE_QUOTE_STRING_END_TABLE, next_byte) + }); + self.finish_next_inner(kind, self.source.position(), FinishTokenMode::Push) + } + + /// Read the rest of the string literal whose opening `'` is at `pos`, and finish the token, + /// after `read_plain_string_literal_single_quote` returned `Err(next_byte)` for it. + /// + /// The string contains an escape, or is unterminated. Neither is common. + /// `pending` must reflect the trivia seen since the previous token. + /// + /// # SAFETY + /// * `pos` must be the position of a `'`. + /// * Position of source must be where `read_plain_string_literal_single_quote` left it. + #[cold] + #[inline(never)] + pub(super) unsafe fn string_token_rest_single_quote( + &mut self, + pos: SourcePosition<'a>, + next_byte: u8, + ) -> Token { + // Escaped strings and diagnostics are recorded against `token_start` + self.token_start = self.source.offset_of(pos); + // SAFETY: Caller guarantees byte at `pos` is `'`, which is ASCII, and that position + // of source is as `handle_plain_string_literal!` left it. + // `SINGLE_QUOTE_STRING_END_TABLE` is a `SafeByteMatchTable`. + let kind = cold_branch(|| unsafe { + handle_string_literal_rest!(self, pos, b'\'', SINGLE_QUOTE_STRING_END_TABLE, next_byte) + }); + self.finish_next_inner(kind, self.source.position(), FinishTokenMode::Push) + } + fn save_js_string(&mut self, value: JSStr<'a>) { - self.escaped_strings.insert(self.token.start(), value); - self.token.set_escaped(true); + self.escaped_strings.insert(self.token_start, value); + self.pending.set_escaped(); } pub(crate) fn get_js_string(&self, token: Token) -> JSStr<'a> { @@ -217,8 +466,8 @@ impl<'a, C: Config> Lexer<'a, C> { #[cold] fn save_escaped_string(&mut self, s: &'a str) { - self.escaped_strings.insert(self.token.start(), s.into()); - self.token.set_escaped(true); + self.escaped_strings.insert(self.token_start, s.into()); + self.pending.set_escaped(); } pub(crate) fn get_string(&self, token: Token) -> &'a str { diff --git a/vendor/oxc_parser/src/lexer/template.rs b/vendor/oxc_parser/src/lexer/template.rs index f05f01e3a..30d232636 100644 --- a/vendor/oxc_parser/src/lexer/template.rs +++ b/vendor/oxc_parser/src/lexer/template.rs @@ -338,15 +338,15 @@ impl<'a, C: Config> Lexer<'a, C> { /// Re-tokenize the current `}` token for `TemplateSubstitutionTail` /// See Section 12, the parser needs to re-tokenize on `TemplateSubstitutionTail`, pub(crate) fn next_template_substitution_tail(&mut self) -> Token { - self.token.set_start(self.offset() - 1); + self.token_start = self.offset() - 1; let kind = self.read_template_literal(Kind::TemplateMiddle, Kind::TemplateTail); self.finish_next_retokenized(kind) } /// Save escaped template string fn save_template_string(&mut self, is_valid_escape_sequence: bool, s: JSStr<'a>) { - self.escaped_templates.insert(self.token.start(), is_valid_escape_sequence.then_some(s)); - self.token.set_escaped(true); + self.escaped_templates.insert(self.token_start, is_valid_escape_sequence.then_some(s)); + self.pending.set_escaped(); } pub(crate) fn get_template_string(&self, start: u32) -> Option> { @@ -362,7 +362,7 @@ mod test { use crate::config::NoTokensLexerConfig; - use super::super::{Kind, Lexer, UniquePromise}; + use super::super::{Kind, Lexer}; #[test] fn template_literal_linebreaks() { @@ -394,21 +394,25 @@ mod test { #[expect(clippy::items_after_statements, clippy::needless_pass_by_value)] fn run_test(source_text: String, expected_escaped: String, is_only_part: bool) { let allocator = Allocator::default(); - let unique = UniquePromise::new_for_tests_and_benchmarks(); - let mut lexer = Lexer::new( + Lexer::scope( &allocator, &source_text, SourceType::default(), NoTokensLexerConfig, - unique, - ); - let token = lexer.next_token(); - assert_eq!( - token.kind(), - if is_only_part { Kind::NoSubstitutionTemplate } else { Kind::TemplateHead } + |mut lexer| { + let token = lexer.first_token(); + assert_eq!( + token.kind(), + if is_only_part { + Kind::NoSubstitutionTemplate + } else { + Kind::TemplateHead + } + ); + let escaped = lexer.escaped_templates[&token.start()]; + assert_eq!(escaped.and_then(JSStr::as_str), Some(expected_escaped.as_str())); + }, ); - let escaped = lexer.escaped_templates[&token.start()]; - assert_eq!(escaped.and_then(JSStr::as_str), Some(expected_escaped.as_str())); } for (source_fragment, escaped_fragment) in escapes { diff --git a/vendor/oxc_parser/src/lexer/token.rs b/vendor/oxc_parser/src/lexer/token.rs index eb084d0ef..4e8d1b226 100644 --- a/vendor/oxc_parser/src/lexer/token.rs +++ b/vendor/oxc_parser/src/lexer/token.rs @@ -82,20 +82,96 @@ impl fmt::Debug for Token { } impl Token { - /// Finish the lexer's scratch token without writing its fields back to memory first. - pub(super) fn finish(self, kind: Kind, end: u32) -> Self { - debug_assert_eq!(self.kind(), Kind::Eof); - debug_assert_eq!(self.end(), 0); - debug_assert!(end >= self.start()); - Self(self.0 | (u128::from(end) << END_SHIFT) | ((kind as u128) << KIND_SHIFT)) + #[inline] + pub(super) fn new(kind: Kind, start: u32, end: u32, pending: PendingToken) -> Self { + debug_assert!(end >= start); + Self( + (u128::from(start) << START_SHIFT) + | (u128::from(end) << END_SHIFT) + | ((kind as u128) << KIND_SHIFT) + | (u128::from(pending.0 & PendingToken::TOKEN_FLAGS) << IS_ON_NEW_LINE_SHIFT), + ) + } +} + +/// Flags of the token being lexed, and trivia state since the previous token, packed in one `u32` +/// so the lexer reads and resets all per-token state with one load and one store. +/// +/// The low 3 bytes are `is_on_new_line`, `escaped` and `has_separator`, in the same layout as in +/// [`Token`]. The other bits are trivia state, used by `TriviaBuilder`. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub(super) struct PendingToken(u32); + +impl PendingToken { + const IS_ON_NEW_LINE: u32 = 1; + const ESCAPED: u32 = 1 << (ESCAPED_SHIFT - IS_ON_NEW_LINE_SHIFT); + const HAS_SEPARATOR: u32 = 1 << (HAS_SEPARATOR_SHIFT - IS_ON_NEW_LINE_SHIFT); + const TOKEN_FLAGS: u32 = Self::IS_ON_NEW_LINE | Self::ESCAPED | Self::HAS_SEPARATOR; + /// Saw a newline since the last token. + const SAW_NEWLINE: u32 = 1 << 24; + /// Saw a newline since the last comment or token. + const SAW_NEWLINE_FOR_COMMENT: u32 = 1 << 25; + /// Comments have been added which are not yet attached to a token. + const HAS_PENDING_COMMENTS: u32 = 1 << 26; + + pub(super) const NONE: Self = Self(0); + /// State when line breaks, and no comments, have been seen since the previous token. + pub(super) const AFTER_LINE_BREAK: Self = + Self(Self::IS_ON_NEW_LINE | Self::SAW_NEWLINE | Self::SAW_NEWLINE_FOR_COMMENT); + pub(super) const START_OF_FILE: Self = Self::AFTER_LINE_BREAK; + + #[inline] + pub(super) fn is_on_new_line(self) -> bool { + self.0 & Self::IS_ON_NEW_LINE != 0 + } + + #[inline] + pub(super) fn set_is_on_new_line(&mut self) { + self.0 |= Self::IS_ON_NEW_LINE; + } + + #[inline] + pub(super) fn set_escaped(&mut self) { + self.0 |= Self::ESCAPED; + } + + #[inline] + pub(super) fn set_has_separator(&mut self) { + self.0 |= Self::HAS_SEPARATOR; } #[inline] - pub(super) fn new_on_new_line() -> Self { - // Start with a default token, then set the flag - let mut token = Self::default(); - token.set_is_on_new_line(true); - token + pub(super) fn saw_newline(self) -> bool { + self.0 & Self::SAW_NEWLINE != 0 + } + + #[inline] + pub(super) fn saw_newline_for_comment(self) -> bool { + self.0 & Self::SAW_NEWLINE_FOR_COMMENT != 0 + } + + #[inline] + pub(super) fn set_saw_newline(&mut self) { + self.0 |= Self::SAW_NEWLINE | Self::SAW_NEWLINE_FOR_COMMENT; + } + + #[inline] + pub(super) fn clear_saw_newline_for_comment(&mut self) { + self.0 &= !Self::SAW_NEWLINE_FOR_COMMENT; + } + + #[inline] + pub(super) fn has_pending_comments(self) -> bool { + self.0 & Self::HAS_PENDING_COMMENTS != 0 + } + + #[inline] + pub(super) fn set_has_pending_comments(&mut self, value: bool) { + if value { + self.0 |= Self::HAS_PENDING_COMMENTS; + } else { + self.0 &= !Self::HAS_PENDING_COMMENTS; + } } } @@ -223,62 +299,26 @@ impl Token { pub fn is_on_new_line(&self) -> bool { // Use a pointer read rather than arithmetic as it produces less instructions. // SAFETY: 8 bits starting at `IS_ON_NEW_LINE_SHIFT` are only set in `Token::default` and - // `Token::set_is_on_new_line`. Both only set these bits to 0 or 1, so valid to read as a `bool`. + // `Token::new`. Both only set these bits to 0 or 1, so valid to read as a `bool`. unsafe { self.read_bool(IS_ON_NEW_LINE_SHIFT) } } - #[inline] - pub(super) fn set_is_on_new_line(&mut self, value: bool) { - /* - // Original version. Perf regressed in Rust 1.95.0. - self.0 &= !(BOOL_MASK << IS_ON_NEW_LINE_SHIFT); // Clear current `is_on_new_line` bits - self.0 |= u128::from(value) << IS_ON_NEW_LINE_SHIFT; - */ - - // SAFETY: `IS_ON_NEW_LINE_SHIFT` is a valid `bool` field position in `Token` - unsafe { self.write_bool(IS_ON_NEW_LINE_SHIFT, value) }; - } - #[inline] pub fn escaped(&self) -> bool { // Use a pointer read rather than arithmetic as it produces less instructions. // SAFETY: 8 bits starting at `ESCAPED_SHIFT` are only set in `Token::default` and - // `Token::set_escaped`. Both only set these bits to 0 or 1, so valid to read as a `bool`. + // `Token::new`. Both only set these bits to 0 or 1, so valid to read as a `bool`. unsafe { self.read_bool(ESCAPED_SHIFT) } } - #[inline] - pub(super) fn set_escaped(&mut self, escaped: bool) { - /* - // Original version. Perf regressed in Rust 1.95.0. - self.0 &= !(BOOL_MASK << ESCAPED_SHIFT); // Clear current `escaped` bits - self.0 |= u128::from(escaped) << ESCAPED_SHIFT; - */ - - // SAFETY: `ESCAPED_SHIFT` is a valid `bool` field position in `Token` - unsafe { self.write_bool(ESCAPED_SHIFT, escaped) }; - } - #[inline] pub fn has_separator(&self) -> bool { // Use a pointer read rather than arithmetic as it produces less instructions. // SAFETY: 8 bits starting at `HAS_SEPARATOR_SHIFT` are only set in `Token::default` and - // `Token::set_has_separator`. Both only set these bits to 0 or 1, so valid to read as a `bool`. + // `Token::new`. Both only set these bits to 0 or 1, so valid to read as a `bool`. unsafe { self.read_bool(HAS_SEPARATOR_SHIFT) } } - #[inline] - pub(super) fn set_has_separator(&mut self, value: bool) { - /* - // Original version. Perf regressed in Rust 1.95.0. - self.0 &= !(BOOL_MASK << HAS_SEPARATOR_SHIFT); // Clear current `has_separator` bits - self.0 |= u128::from(value) << HAS_SEPARATOR_SHIFT; - */ - - // SAFETY: `HAS_SEPARATOR_SHIFT` is a valid `bool` field position in `Token` - unsafe { self.write_bool(HAS_SEPARATOR_SHIFT, value) }; - } - /// Read `bool` from 8 bits starting at bit position `shift`. /// /// # SAFETY @@ -327,29 +367,6 @@ impl Token { } } - /// Write `bool` to the 8 bits starting at bit position `shift`. - /// - /// # SAFETY - /// - /// `shift` must be the location of a valid boolean "field" in [`Token`] e.g. `ESCAPED_SHIFT`. - /// - /// # Performance analysis - /// - /// Writing the whole byte via a pointer avoids a read-modify-write of the underlying `u128`. - /// LLVM stopped folding the safe `self.0 &= !mask; self.0 |= val << shift` pattern - /// into a single byte store as of rustc 1.95.0 - see . - /// This implementation produces `mov byte ptr [rdi + N], sil` on both affected and unaffected Rust versions. - #[expect(clippy::inline_always)] - #[inline(always)] // So `shift` is statically known - unsafe fn write_bool(&mut self, shift: usize, value: bool) { - // Byte offset depends on endianness of the system - let offset = if cfg!(target_endian = "little") { shift / 8 } else { 15 - (shift / 8) }; - // SAFETY: Caller guarantees `shift` points to a valid `bool` field. - // `Token` is borrowed mutably, so the write is unaliased. - // `as_mut` produces a `&mut bool` with `noalias` metadata for LLVM. - unsafe { *NonNull::from(self).cast::().add(offset).as_mut() = value }; - } - /// Write `u32` to the 32 bits starting at bit position `shift`. /// /// # SAFETY @@ -358,7 +375,10 @@ impl Token { /// /// # Performance analysis /// - /// See `write_bool` - same story, but `mov dword ptr [rdi + N], esi`. + /// Writing the whole `u32` via a pointer avoids a read-modify-write of the underlying `u128`. + /// LLVM stopped folding the safe `self.0 &= !mask; self.0 |= val << shift` pattern + /// into a single store as of rustc 1.95.0 - see . + /// This implementation produces `mov dword ptr [rdi + N], esi` on both affected and unaffected Rust versions. #[expect(clippy::inline_always)] #[inline(always)] // So `shift` is statically known unsafe fn write_u32(&mut self, shift: usize, value: u32) { @@ -374,7 +394,7 @@ impl Token { #[cfg(test)] mod test { - use super::{Kind, Span, Token}; + use super::{Kind, PendingToken, Span, Token}; // Test size of `Token` const _: () = assert!(size_of::() == 16); @@ -392,147 +412,52 @@ mod test { } #[test] - fn new_on_new_line_token_values() { - let token = Token::new_on_new_line(); - assert_eq!(token.start(), 0); - assert_eq!(token.end(), 0); - assert_eq!(token.kind(), Kind::Eof); - assert!(token.is_on_new_line()); + fn new_token() { + let token = Token::new(Kind::Ident, 3, 7, PendingToken::NONE); + assert_eq!(token.kind(), Kind::Ident); + assert_eq!(token.span(), Span::new(3, 7)); + assert!(!token.is_on_new_line()); assert!(!token.escaped()); assert!(!token.has_separator()); - } - - #[test] - fn token_creation_and_retrieval() { - let kind = Kind::Ident; - let start = 100u32; - let end = start + 5u32; - let is_on_new_line = true; - let escaped = false; - let has_separator = false; - - let mut token = Token::default(); - token.set_kind(kind); - token.set_start(start); - token.set_end(end); - token.set_is_on_new_line(is_on_new_line); - token.set_escaped(escaped); - if has_separator { - // Assuming set_has_separator is not always called if false - token.set_has_separator(true); - } - - assert_eq!(token.kind(), kind); - assert_eq!(token.start(), start); - assert_eq!(token.end(), end); - assert_eq!(token.is_on_new_line(), is_on_new_line); - assert_eq!(token.escaped(), escaped); - assert_eq!(token.has_separator(), has_separator); - } - #[test] - fn token_setters() { - let mut token = Token::default(); - token.set_kind(Kind::Ident); - token.set_span(Span::new(10, 15)); - - assert_eq!(token.start(), 10); - assert_eq!(token.end(), 15); + // Trivia state is not copied into `Token` + let token = Token::new(Kind::Eof, 0, 0, PendingToken::START_OF_FILE); + assert!(token.is_on_new_line()); assert!(!token.escaped()); - assert!(!token.is_on_new_line()); - - // Test set_end - let mut token_for_set_end = Token::default(); - token_for_set_end.set_kind(Kind::Ident); - token_for_set_end.set_start(10); - token_for_set_end.set_end(15); - - assert_eq!(token_for_set_end.end(), 15); - token_for_set_end.set_end(30); - assert_eq!(token_for_set_end.start(), 10); - assert_eq!(token_for_set_end.end(), 30); - - // Test that other flags are not affected by set_start - let mut token_with_flags = Token::default(); - token_with_flags.set_kind(Kind::Str); - token_with_flags.set_start(30); - token_with_flags.set_end(33); - token_with_flags.set_is_on_new_line(true); - token_with_flags.set_escaped(true); - token_with_flags.set_has_separator(true); - - token_with_flags.set_start(40); - assert_eq!(token_with_flags.start(), 40); - assert!(token_with_flags.is_on_new_line()); - assert!(token_with_flags.escaped()); - assert!(token_with_flags.has_separator()); - - // Test that other flags are not affected by set_escaped - let mut token_with_flags2 = Token::default(); - token_with_flags2.set_kind(Kind::Str); - token_with_flags2.set_start(50); - token_with_flags2.set_end(52); - token_with_flags2.set_is_on_new_line(true); - // escaped is false by default - token_with_flags2.set_has_separator(true); - - token_with_flags2.set_escaped(true); - assert_eq!(token_with_flags2.start(), 50); - assert!(token_with_flags2.is_on_new_line()); - assert!(token_with_flags2.escaped()); - assert!(token_with_flags2.has_separator()); - token_with_flags2.set_escaped(false); - assert!(!token_with_flags2.escaped()); - assert!(token_with_flags2.is_on_new_line()); // Check again - assert!(token_with_flags2.has_separator()); // Check again - - // Test set_is_on_new_line does not affect other flags - let mut token_flags_test_newline = Token::default(); - token_flags_test_newline.set_kind(Kind::Str); - token_flags_test_newline.set_start(60); - token_flags_test_newline.set_end(62); - // is_on_new_line is false by default - token_flags_test_newline.set_escaped(true); - token_flags_test_newline.set_has_separator(true); - - token_flags_test_newline.set_is_on_new_line(true); - assert!(token_flags_test_newline.is_on_new_line()); - assert_eq!(token_flags_test_newline.start(), 60); - assert!(token_flags_test_newline.escaped()); - assert!(token_flags_test_newline.has_separator()); - token_flags_test_newline.set_is_on_new_line(false); - assert!(!token_flags_test_newline.is_on_new_line()); - assert!(token_flags_test_newline.escaped()); - assert!(token_flags_test_newline.has_separator()); - } + assert!(!token.has_separator()); - #[test] - fn is_on_new_line() { - let mut token = Token::default(); + let mut pending = PendingToken::NONE; + pending.set_escaped(); + pending.set_has_separator(); + pending.set_has_pending_comments(true); + let mut token = Token::new(Kind::Str, 30, 33, pending); assert!(!token.is_on_new_line()); - token.set_is_on_new_line(true); - assert!(token.is_on_new_line()); - token.set_is_on_new_line(false); - assert!(!token.is_on_new_line()); - } + assert!(token.escaped()); + assert!(token.has_separator()); - #[test] - fn escaped() { - let mut token = Token::default(); - assert!(!token.escaped()); - token.set_escaped(true); + // Setters do not affect other fields + token.set_span(Span::new(10, 15)); + token.set_kind(Kind::Ident); + assert_eq!(token.span(), Span::new(10, 15)); + assert_eq!(token.kind(), Kind::Ident); + assert!(!token.is_on_new_line()); assert!(token.escaped()); - token.set_escaped(false); - assert!(!token.escaped()); + assert!(token.has_separator()); } #[test] - fn has_separator() { - let mut token = Token::default(); - assert!(!token.has_separator()); - token.set_has_separator(true); - assert!(token.has_separator()); - token.set_has_separator(false); - assert!(!token.has_separator()); + fn pending_token_trivia_state() { + let mut pending = PendingToken::NONE; + pending.set_saw_newline(); + assert!(pending.saw_newline()); + assert!(pending.saw_newline_for_comment()); + pending.clear_saw_newline_for_comment(); + assert!(pending.saw_newline()); + assert!(!pending.saw_newline_for_comment()); + pending.set_has_pending_comments(true); + assert!(pending.has_pending_comments()); + pending.set_has_pending_comments(false); + assert!(!pending.has_pending_comments()); + assert!(!pending.is_on_new_line()); } } diff --git a/vendor/oxc_parser/src/lexer/trivia_builder.rs b/vendor/oxc_parser/src/lexer/trivia_builder.rs index df5703c2e..b169dce1e 100644 --- a/vendor/oxc_parser/src/lexer/trivia_builder.rs +++ b/vendor/oxc_parser/src/lexer/trivia_builder.rs @@ -1,19 +1,119 @@ -use std::num::NonZeroU32; +use std::{ + num::NonZeroU32, + ops::{Deref, DerefMut}, +}; -use memchr::memchr_iter; - -use oxc_allocator::{Allocator, ArenaVec}; +use oxc_allocator::{Allocator, ArenaVec, GetAllocator, TakeIn}; use oxc_ast::ast::{Comment, CommentContent, CommentKind, CommentPosition}; use oxc_span::Span; -use super::{Kind, Token}; +use super::{Kind, PendingToken, Token}; + +/// Buffer short comment lists before allocating their final arena storage. +#[derive(Debug)] +pub struct Comments<'a> { + inline: [Comment; 16], + len: usize, + vec: ArenaVec<'a, Comment>, + /// Source offset which every comment starts before. + /// 1 more than the start of the last comment, or 0 if there are no comments. + starts_end: u32, +} + +impl<'a> Comments<'a> { + fn new_in(allocator: &'a Allocator) -> Self { + Self { + inline: std::array::from_fn(|_| Comment::new(0, 0, CommentKind::Line)), + len: 0, + vec: ArenaVec::new_in(&allocator), + starts_end: 0, + } + } + + #[inline] + fn len(&self) -> usize { + self.len + } + + /// Returns `true` if a comment which starts at `start` was added before. + /// + /// Comments are added in source order, so that is any comment which does not start + /// after the last one. + #[inline] + fn is_seen(&self, start: u32) -> bool { + start < self.starts_end + } + + /// Add a comment. It must start after the last one. + #[inline] + fn push(&mut self, comment: Comment) { + debug_assert!(!self.is_seen(comment.span.start)); + self.starts_end = comment.span.start + 1; + if self.vec.is_empty() && self.len < self.inline.len() { + self.inline[self.len] = comment; + } else { + if self.vec.is_empty() { + self.move_inline_to_vec(); + } + self.vec.push(comment); + } + self.len += 1; + } + + /// Discard comments after the first `len`. + fn truncate(&mut self, len: usize) { + if len < self.len { + self.len = len; + self.vec.truncate(len); + self.starts_end = self.last().map_or(0, |comment| comment.span.start + 1); + } + } + + /// Move the comments to arena storage, once there are too many to store inline. + #[cold] + #[inline(never)] + fn move_inline_to_vec(&mut self) { + self.vec.reserve(self.inline.len() * 2); + self.vec.extend(self.inline.iter().cloned()); + } + + /// Take the comments in their final arena storage, leaving `self` empty. + /// + /// This takes `&mut self` so that the inline storage is not copied, as it would be + /// to move `self` or to consume its array. + pub(crate) fn take_vec(&mut self, allocator: &impl GetAllocator<'a>) -> ArenaVec<'a, Comment> { + if self.vec.is_empty() { + self.vec.reserve_exact(self.len); + self.vec.extend(self.inline[..self.len].iter().cloned()); + } + self.len = 0; + self.starts_end = 0; + self.vec.take_in(allocator) + } +} + +impl Deref for Comments<'_> { + type Target = [Comment]; + + #[inline] + fn deref(&self) -> &[Comment] { + if self.vec.is_empty() { &self.inline[..self.len] } else { &self.vec } + } +} + +impl DerefMut for Comments<'_> { + #[inline] + fn deref_mut(&mut self) -> &mut [Comment] { + if self.vec.is_empty() { &mut self.inline[..self.len] } else { &mut self.vec } + } +} #[derive(Debug)] pub struct TriviaBuilder<'a> { // This is a set of unique comments. Duplicated // comments could be generated in case of rewind; they are // filtered out at insertion time. - pub(crate) comments: ArenaVec<'a, Comment>, + pub(crate) comments: Comments<'a>, pub(crate) irregular_whitespaces: Vec, @@ -21,19 +121,20 @@ pub struct TriviaBuilder<'a> { /// index of processed comments processed: usize, - /// Saw a newline before this position (since last token). - /// Used to determine if comments are trailing comments of the previous token. - saw_newline: bool, - - /// Saw a newline before this position (since last comment or token). - /// Used to set `preceded_by_newline` on comments. - saw_newline_for_comment: bool, - /// Previous token, used to attach trailing comments to its end. previous_token: Token, /// Annotation ranges preceding the current token, also saved by lexer checkpoints. - pub(super) annotation_comments: AnnotationComments, + annotation_comments: AnnotationComments, +} + +/// Trivia state saved by lexer checkpoints. +#[derive(Clone, Copy, Debug)] +pub(super) struct TriviaCheckpoint { + comments_len: usize, + irregular_whitespaces_len: usize, + previous_token: Token, + annotation_comments: AnnotationComments, } #[derive(Clone, Copy, Debug, Default)] @@ -51,16 +152,39 @@ impl<'a> TriviaBuilder<'a> { let mut previous_token = Token::default(); previous_token.set_kind(Kind::Undetermined); Self { - comments: ArenaVec::new_in(&allocator), + comments: Comments::new_in(allocator), irregular_whitespaces: vec![], processed: 0, - saw_newline: true, - saw_newline_for_comment: true, previous_token, annotation_comments: AnnotationComments::default(), } } + pub(super) fn checkpoint(&self) -> TriviaCheckpoint { + TriviaCheckpoint { + comments_len: self.comments.len(), + irregular_whitespaces_len: self.irregular_whitespaces.len(), + previous_token: self.previous_token, + annotation_comments: self.annotation_comments, + } + } + + /// Discard trivia lexed after `checkpoint`. It is lexed again, maybe differently: + /// a speculative parse can lex JSX text as a comment. + pub(super) fn rewind(&mut self, checkpoint: TriviaCheckpoint) { + self.comments.truncate(checkpoint.comments_len); + self.irregular_whitespaces.truncate(checkpoint.irregular_whitespaces_len); + self.processed = self.comments.len(); + self.previous_token = checkpoint.previous_token; + self.annotation_comments = checkpoint.annotation_comments; + } + + /// Make rewinding to `checkpoint` keep the trivia lexed after it. + pub(super) fn keep_trivia(&self, checkpoint: &mut TriviaCheckpoint) { + checkpoint.comments_len = self.comments.len(); + checkpoint.irregular_whitespaces_len = self.irregular_whitespaces.len(); + } + pub fn previous_token_pure_comments(&self) -> Option<(u32, NonZeroU32)> { self.annotation_comments.ends[0].map(|end| (self.annotation_comments.starts[0], end)) } @@ -91,8 +215,8 @@ impl<'a> TriviaBuilder<'a> { pub fn add_irregular_whitespace(&mut self, start: u32, end: u32) { // The irregular whitespaces array is ordered; only add if not added before, to avoid - // duplicates when the parser looks ahead (e.g. `peek_token`) and rewinds, then re-lexes the - // same whitespace. Same approach as `add_comment`. + // duplicates when the parser rewinds keeping trivia, then re-lexes the same whitespace. + // Same approach as comments. if let Some(last) = self.irregular_whitespaces.last() && start <= last.start { @@ -101,71 +225,190 @@ impl<'a> TriviaBuilder<'a> { self.irregular_whitespaces.push(Span::new(start, end)); } - pub fn add_line_comment(&mut self, start: u32, end: u32, kind: CommentKind, source_text: &str) { - self.add_comment(Comment::new(start, end, kind), source_text); + /// Add a line comment. `end` is the line break which ends it, or the end of the source. + /// + /// `has_legal_tag` is whether the comment contains `@license` or `@preserve`. + /// The lexer finds that out while it searches for the end of the comment. + pub(super) fn add_line_comment( + &mut self, + start: u32, + end: u32, + kind: CommentKind, + has_legal_tag: bool, + source_text: &str, + pending: &mut PendingToken, + ) { + let mut comment = Comment::new(start, end, kind); + if self.is_seen_comment(start) { + self.replay_comment(&comment); + return; + } + + let content_span = comment.content_span(); + let bytes = &source_text.as_bytes()[content_span.start as usize..content_span.end as usize]; + comment.content = comment_content(bytes, false, has_legal_tag, content_span, source_text); + + // This newly added comment may be preceded by a newline. + // Use `saw_newline_for_comment` which tracks newlines since the last comment or token, + // not just since the last token. + comment.set_preceded_by_newline(pending.saw_newline_for_comment()); + // A line comment is always followed by a newline. This is never set in `handle_newline`. + comment.set_followed_by_newline(true); + let becomes_trailing = self.should_be_treated_as_trailing_comment(*pending) + && !Self::should_stay_leading(&comment); + pending.set_saw_newline(); + + self.push_comment(comment); + if becomes_trailing { + self.attach_pending_comments( + CommentPosition::Trailing, + self.previous_token.end(), + self.comments.len(), + pending, + ); + } else { + pending.set_has_pending_comments(true); + } } - pub fn add_block_comment( + /// Add a block comment. + /// + /// `has_legal_tag` is whether the comment contains `@license` or `@preserve`. + /// The lexer finds that out while it searches for the end of the comment. + pub(super) fn add_block_comment( &mut self, start: u32, end: u32, kind: CommentKind, + has_legal_tag: bool, source_text: &str, + pending: &mut PendingToken, ) { - self.add_comment(Comment::new(start, end, kind), source_text); + let mut comment = Comment::new(start, end, kind); + if self.is_seen_comment(start) { + self.replay_comment(&comment); + return; + } + + let content_span = comment.content_span(); + let bytes = &source_text.as_bytes()[content_span.start as usize..content_span.end as usize]; + comment.content = comment_content(bytes, true, has_legal_tag, content_span, source_text); + + // This newly added comment may be preceded by a newline. + // Use `saw_newline_for_comment` which tracks newlines since the last comment or token, + // not just since the last token. + comment.set_preceded_by_newline(pending.saw_newline_for_comment()); + // Block comments don't end with a newline, so reset saw_newline_for_comment. + // If there's a newline after the block comment, `handle_newline` will set it back to true. + pending.clear_saw_newline_for_comment(); + + self.push_comment(comment); + pending.set_has_pending_comments(true); + } + + /// Returns `true` if a comment which starts at `start` was added before. + /// + /// The comments array is an ordered vec, only add the comment if its not added before, + /// to avoid situations where the parser needs to rewind and tries to reinsert the comment. + #[inline] + fn is_seen_comment(&self, start: u32) -> bool { + self.comments.is_seen(start) + } + + /// Handle a comment which was added before. The parser rewound, and is lexing it again. + #[cold] + #[inline(never)] + fn replay_comment(&mut self, comment: &Comment) { + // A comment is only seen once a comment has been added + let last_comment = self.comments.last().unwrap(); + debug_assert!(comment.span.start <= last_comment.span.start); + // Reuse the classification from before lookahead/rewind, including annotations + // that have already been applied. Usually this is the most recent comment. + let index = if comment.span.start == last_comment.span.start { + Some(self.comments.len() - 1) + } else { + self.comments + .binary_search_by_key(&comment.span.start, |existing| existing.span.start) + .ok() + }; + if let Some(index) = index + && self.comments[index].span == comment.span + { + self.set_annotation_flags(self.comments[index].content, index); + } + } + + /// Add a comment which was not added before, once it is complete. + #[inline] + fn push_comment(&mut self, comment: Comment) { + // Set annotation flags here (not when working out the content) so the index is correct + // even when a duplicate from parser lookahead/rewind was skipped. + self.set_annotation_flags(comment.content, self.comments.len()); + self.comments.push(comment); } // For block comments only. This function is not called after line comments because the lexer skips // newline after line comments. - pub fn handle_newline(&mut self) { + #[inline] + pub(super) fn handle_newline(&mut self, pending: &mut PendingToken) { + if pending.has_pending_comments() { + self.handle_newline_with_comments(pending); + } + pending.set_saw_newline(); + } + + #[cold] + fn handle_newline_with_comments(&mut self, pending: &mut PendingToken) { // The last unprocessed comment is on a newline. let len = self.comments.len(); - if self.processed < len { - let becomes_trailing = { - let comment = &mut self.comments[len - 1]; - comment.set_followed_by_newline(true); - !self.saw_newline && !Self::should_stay_leading(comment) - }; - if becomes_trailing { - self.attach_pending_comments( - CommentPosition::Trailing, - self.previous_token.end(), - len, - ); - } + let becomes_trailing = { + let comment = &mut self.comments[len - 1]; + comment.set_followed_by_newline(true); + !pending.saw_newline() && !Self::should_stay_leading(comment) + }; + if becomes_trailing { + self.attach_pending_comments( + CommentPosition::Trailing, + self.previous_token.end(), + len, + pending, + ); } - self.saw_newline = true; - self.saw_newline_for_comment = true; } #[inline] - pub fn handle_token(&mut self, token: Token) { - self.saw_newline = false; - self.saw_newline_for_comment = false; + pub(super) fn handle_token(&mut self, token: Token, pending: PendingToken) { + debug_assert_eq!(pending.has_pending_comments(), self.processed < self.comments.len()); // Cold path: attach any unprocessed comments between the previous token and this one. // For files with no comments (or once all comments are consumed), this branch is skipped. - let len = self.comments.len(); - if self.processed < len { - self.attach_pending_comments_to_token(token, len); + if pending.has_pending_comments() { + self.attach_pending_comments_to_token(token); } self.previous_token = token; } + /// Same as `handle_token`, for a token which no comments are waiting to be attached to. + #[inline] + pub(super) fn set_previous_token(&mut self, token: Token) { + debug_assert_eq!(self.processed, self.comments.len()); + self.previous_token = token; + } + #[cold] - fn attach_pending_comments_to_token(&mut self, token: Token, len: usize) { - let previous_kind = self.previous_token.kind(); - let can_attach_to_previous = previous_kind != Kind::Undetermined - && (token.kind() == Kind::Eof - || (Self::can_end_expression(previous_kind) - && Self::continues_previous_expression(token.kind()))); - let previous_token_end = self.previous_token.end(); + fn attach_pending_comments_to_token(&mut self, token: Token) { + let len = self.comments.len(); + let previous_token = self.previous_token; + // Most comments are on their own line, and those always lead the following token. + // So only work out whether the previous token can take comments if one could go to it. + let mut can_attach_to_previous = None; for comment in &mut self.comments[self.processed..len] { - if can_attach_to_previous - && !comment.preceded_by_newline() + if !comment.preceded_by_newline() && !Self::should_stay_leading(comment) + && *can_attach_to_previous + .get_or_insert_with(|| Self::can_attach_to_previous(previous_token, token)) { comment.position = CommentPosition::Trailing; - comment.attached_to = previous_token_end; + comment.attached_to = previous_token.end(); } else { comment.position = CommentPosition::Leading; comment.attached_to = token.start(); @@ -174,13 +417,31 @@ impl<'a> TriviaBuilder<'a> { self.processed = len; } + /// Whether comments between `previous_token` and `token` which are on the same line as + /// `previous_token` trail it, rather than leading `token`. + #[cold] + fn can_attach_to_previous(previous_token: Token, token: Token) -> bool { + let previous_kind = previous_token.kind(); + previous_kind != Kind::Undetermined + && (token.kind() == Kind::Eof + || (Self::can_end_expression(previous_kind) + && Self::continues_previous_expression(token.kind()))) + } + #[cold] - fn attach_pending_comments(&mut self, position: CommentPosition, attached_to: u32, len: usize) { + fn attach_pending_comments( + &mut self, + position: CommentPosition, + attached_to: u32, + len: usize, + pending: &mut PendingToken, + ) { for comment in &mut self.comments[self.processed..len] { comment.position = position; comment.attached_to = attached_to; } self.processed = len; + pending.set_has_pending_comments(false); } /// Whether a token can form the completed left-hand side of an infix or suffix boundary. @@ -244,8 +505,8 @@ impl<'a> TriviaBuilder<'a> { /// Treating a comment after `:` as trailing drops it (it anchors to the /// previous token rather than the following operand), which breaks codegen /// idempotency once a transform emits `? consequent : // comment\nalternate`. - fn should_be_treated_as_trailing_comment(&self) -> bool { - !self.saw_newline + fn should_be_treated_as_trailing_comment(&self, pending: PendingToken) -> bool { + !pending.saw_newline() && !matches!(self.previous_token.kind(), Kind::Eq | Kind::LParen | Kind::Colon) } @@ -286,247 +547,175 @@ impl<'a> TriviaBuilder<'a> { } self.annotation_comments.ends[range] = Some(end); } +} - fn add_comment(&mut self, mut comment: Comment, source_text: &str) { - // The comments array is an ordered vec, only add the comment if its not added before, - // to avoid situations where the parser needs to rewind and tries to reinsert the comment. - if let Some(last_comment) = self.comments.last() - && comment.span.start <= last_comment.span.start - { - // Reuse the classification from before lookahead/rewind, including annotations - // that have already been applied. Usually this is the most recent comment. - let index = if comment.span.start == last_comment.span.start { - Some(self.comments.len() - 1) +/// Work out what a comment is from its content. +/// +/// * `bytes` is the content of the comment, which `content_span` is the span of. +/// * `has_legal_tag` is whether the comment contains `@license` or `@preserve`. +#[inline] +fn comment_content( + bytes: &[u8], + is_block: bool, + has_legal_tag: bool, + content_span: Span, + source_text: &str, +) -> CommentContent { + // Check first byte for quick routing + match bytes.first() { + // Empty comment + None => return CommentContent::None, + Some(b'!') => return CommentContent::Legal, + Some(b'*') if is_block => { + // Ignore webpack comment `/*****/` + return if bytes.iter().all(|&c| c == b'*') { + CommentContent::None + } else if has_legal_tag { + CommentContent::JsdocLegal } else { - self.comments - .binary_search_by_key(&comment.span.start, |existing| existing.span.start) - .ok() + CommentContent::Jsdoc }; - if let Some(index) = index - && self.comments[index].span == comment.span - { - self.set_annotation_flags(self.comments[index].content, index); - } - return; } + Some(_) => {} + } - Self::parse_annotation(&mut comment, source_text); + // Skip leading whitespace without allocation + let mut start = 0; + while start < bytes.len() && bytes[start].is_ascii_whitespace() { + start += 1; + } - // This newly added comment may be preceded by a newline. - // Use `saw_newline_for_comment` which tracks newlines since the last comment or token, - // not just since the last token. - comment.set_preceded_by_newline(self.saw_newline_for_comment); - let becomes_trailing = if comment.is_line() { - // A line comment is always followed by a newline. This is never set in `handle_newline`. - comment.set_followed_by_newline(true); - let becomes_trailing = self.should_be_treated_as_trailing_comment() - && !Self::should_stay_leading(&comment); - self.saw_newline = true; - self.saw_newline_for_comment = true; - becomes_trailing - } else { - // Block comments don't end with a newline, so reset saw_newline_for_comment. - // If there's a newline after the block comment, `handle_newline` will set it back to true. - self.saw_newline_for_comment = false; - false - }; + let Some(&first_byte) = bytes.get(start) else { + return CommentContent::None; + }; - // Set annotation flags here (not in `parse_annotation`) so the index is correct - // even when the dedup check above skips a duplicate from parser lookahead/rewind. - self.set_annotation_flags(comment.content, self.comments.len()); - self.comments.push(comment); - if becomes_trailing { - self.attach_pending_comments( - CommentPosition::Trailing, - self.previous_token.end(), - self.comments.len(), - ); - } + // Most comments are prose. Only a few bytes can start an annotation. + if ANNOTATION_START_TABLE[first_byte as usize] + && let Some(content) = annotation_content(bytes, start, content_span, source_text) + { + return content; } - /// Parse Notation - fn parse_annotation(comment: &mut Comment, source_text: &str) { - let s = comment.content_span().source_text(source_text); - let bytes = s.as_bytes(); + // Check for `@license` or `@preserve` anywhere in the comment. + // This handles cases like `/* @foo @preserve */` where the first `@` doesn't match known patterns. + if has_legal_tag { CommentContent::Legal } else { CommentContent::None } +} - // Early exit for empty comments - if bytes.is_empty() { - return; - } +/// Work out what a comment is, where `bytes[start]` is its first byte which is not whitespace, +/// and that byte can start an annotation. +/// +/// `bytes` is the content of the comment, which `content_span` is the span of. +/// +/// Returns `None` if the comment is not an annotation. It may still be a legal comment. +#[inline(never)] +fn annotation_content( + bytes: &[u8], + mut start: usize, + content_span: Span, + source_text: &str, +) -> Option { + let rest = &bytes[start..]; + if (rest.starts_with(b"@__KEY__") || rest.starts_with(b"#__KEY__") || !rest[0].is_ascii()) + && is_property_key_annotation(content_span.source_text(source_text)) + { + return Some(CommentContent::PropertyKey); + } - // Check first byte for quick routing - match bytes[0] { - b'!' => { - comment.content = CommentContent::Legal; - return; - } - b'*' if comment.is_block() => { - // Ignore webpack comment `/*****/` - if !bytes.iter().all(|&c| c == b'*') { - if contains_license_or_preserve_comment(s) { - comment.content = CommentContent::JsdocLegal; - } else { - comment.content = CommentContent::Jsdoc; - } - } - return; + // Fast path: check first non-whitespace byte + match bytes[start] { + b'@' => { + start += 1; + if start >= bytes.len() { + return Some(CommentContent::None); } - _ => {} - } - // Skip leading whitespace without allocation - let mut start = 0; - while start < bytes.len() && bytes[start].is_ascii_whitespace() { - start += 1; - } + // Check for @vite, @license, @preserve + if bytes[start..].starts_with(b"vite") { + return Some(CommentContent::Vite); + } + if bytes[start..].starts_with(b"license") || bytes[start..].starts_with(b"preserve") { + return Some(CommentContent::Legal); + } - if start >= bytes.len() { - return; + // Continue to check for __PURE__ or __NO_SIDE_EFFECTS__ after @ } - - let rest = &bytes[start..]; - if (rest.starts_with(b"@__KEY__") || rest.starts_with(b"#__KEY__") || !rest[0].is_ascii()) - && is_property_key_annotation(s) - { - comment.content = CommentContent::PropertyKey; - return; + b'#' => { + start += 1; + // Continue to check for __PURE__ or __NO_SIDE_EFFECTS__ after # } - - // Fast path: check first non-whitespace byte - match bytes[start] { - b'@' => { - start += 1; - if start >= bytes.len() { - return; - } - - // Check for @vite, @license, @preserve - if bytes[start..].starts_with(b"vite") { - comment.content = CommentContent::Vite; - return; - } - if bytes[start..].starts_with(b"license") || bytes[start..].starts_with(b"preserve") - { - comment.content = CommentContent::Legal; - return; - } - - // Continue to check for __PURE__ or __NO_SIDE_EFFECTS__ after @ - } - b'#' => { - start += 1; - // Continue to check for __PURE__ or __NO_SIDE_EFFECTS__ after # - } - b'w' => { - // Check for webpack comments - if bytes[start..].starts_with(b"webpack") - && start + 7 < bytes.len() - && bytes[start + 7].is_ascii_uppercase() - { - comment.content = CommentContent::Webpack; - return; - } - // Fall through to check for coverage ignore patterns - } - b't' => { - // Check for turbopack comments - if bytes[start..].starts_with(b"turbopack") - && start + 9 < bytes.len() - && bytes[start + 9].is_ascii_uppercase() - { - comment.content = CommentContent::Turbopack; - return; - } - // Fall through to check for coverage ignore patterns - } - b'v' | b'c' | b'n' | b'i' => { - // Check coverage ignore patterns: "v8 ignore", "c8 ignore", "node:coverage", "istanbul ignore" - let rest = &bytes[start..]; - if rest.starts_with(b"v8 ignore") - || rest.starts_with(b"c8 ignore") - || rest.starts_with(b"node:coverage") - || rest.starts_with(b"istanbul ignore") - { - comment.content = if is_coverage_ignore_file(rest) { - CommentContent::CoverageIgnoreFile - } else { - CommentContent::CoverageIgnore - }; - return; - } - // Fall through to check license/preserve + b'w' => { + // Check for webpack comments + if bytes[start..].starts_with(b"webpack") + && start + 7 < bytes.len() + && bytes[start + 7].is_ascii_uppercase() + { + return Some(CommentContent::Webpack); } - _ => { - // Check for license/preserve comments in remaining cases - if contains_license_or_preserve_comment(s) { - comment.content = CommentContent::Legal; - } - return; + // Fall through to check for coverage ignore patterns + } + b't' => { + // Check for turbopack comments + if bytes[start..].starts_with(b"turbopack") + && start + 9 < bytes.len() + && bytes[start + 9].is_ascii_uppercase() + { + return Some(CommentContent::Turbopack); } + // Fall through to check for coverage ignore patterns } - - // Check for __PURE__ or __NO_SIDE_EFFECTS__ after @ or # - if start < bytes.len() && bytes[start..].starts_with(b"__") { - let rest = &bytes[start + 2..]; - if rest.starts_with(b"PURE__") { - comment.content = CommentContent::PureNotApplied; - return; - } else if rest.starts_with(b"NO_SIDE_EFFECTS__") { - comment.content = CommentContent::NoSideEffectsNotApplied; - return; + b'v' | b'c' | b'n' | b'i' => { + // Check coverage ignore patterns: "v8 ignore", "c8 ignore", "node:coverage", "istanbul ignore" + let rest = &bytes[start..]; + if rest.starts_with(b"v8 ignore") + || rest.starts_with(b"c8 ignore") + || rest.starts_with(b"node:coverage") + || rest.starts_with(b"istanbul ignore") + { + return Some(if is_coverage_ignore_file(rest) { + CommentContent::CoverageIgnoreFile + } else { + CommentContent::CoverageIgnore + }); } + // Fall through to check license/preserve } + // Not an annotation + _ => return None, + } - // Fallback: check for @license or @preserve anywhere in the comment - // This handles cases like /* @foo @preserve */ where the first @ doesn't match known patterns - if contains_license_or_preserve_comment(s) { - comment.content = CommentContent::Legal; + // Check for __PURE__ or __NO_SIDE_EFFECTS__ after @ or # + if start < bytes.len() && bytes[start..].starts_with(b"__") { + let rest = &bytes[start + 2..]; + if rest.starts_with(b"PURE__") { + return Some(CommentContent::PureNotApplied); + } else if rest.starts_with(b"NO_SIDE_EFFECTS__") { + return Some(CommentContent::NoSideEffectsNotApplied); } } -} -#[inline] -fn is_property_key_annotation(source: &str) -> bool { - matches!(source.trim().strip_prefix(['@', '#']), Some("__KEY__")) + // Not an annotation + None } -#[inline(always)] -fn contains_license_or_preserve_comment(s: &str) -> bool { - const LICENSE_LEN: usize = b"@license".len(); - const PRESERVE_LEN: usize = b"@preserve".len(); - let hay = s.as_bytes(); - - if hay.len() < LICENSE_LEN { - return false; - } - - let search_len = hay.len() - LICENSE_LEN + 1; - - for i in memchr_iter(b'@', &hay[..search_len]) { - debug_assert!(i < search_len); - debug_assert!(hay.len() - i >= LICENSE_LEN); - // SAFETY: `search_len` only includes candidate starts with at least `LICENSE_LEN` bytes - // remaining, so `i + 1` and the full `@license` range are in bounds. - match unsafe { hay.get_unchecked(i + 1) } { - // spellchecker:off - b'l' - // SAFETY: The candidate bound proves the full `@license` range is in bounds. - if unsafe { hay.get_unchecked(i + 2..i + LICENSE_LEN) } == b"icense" => - { - return true; - } - b'p' if hay.len() - i >= PRESERVE_LEN - // SAFETY: The preceding guard proves the full `@preserve` range is in bounds. - && unsafe { hay.get_unchecked(i + 2..i + PRESERVE_LEN) } == b"reserve" => - { - return true; - } - // spellchecker:on - _ => {} - } +/// Bytes which can be the first byte of a comment, after whitespace, where the comment is +/// something other than prose: an annotation, or a directive for a tool. +/// All bytes of Unicode characters are included, as Unicode whitespace may precede an annotation. +static ANNOTATION_START_TABLE: [bool; 256] = { + let mut table = [false; 256]; + let mut i = 0; + while i < 256 { + #[expect(clippy::cast_possible_truncation)] + let byte = i as u8; + table[i] = matches!(byte, b'@' | b'#' | b'w' | b't' | b'v' | b'c' | b'n' | b'i') + || !byte.is_ascii(); + i += 1; } + table +}; - false +#[inline] +fn is_property_key_annotation(source: &str) -> bool { + matches!(source.trim().strip_prefix(['@', '#']), Some("__KEY__")) } fn is_coverage_ignore_file(source: &[u8]) -> bool { @@ -554,7 +743,7 @@ mod test { use crate::Parser; - use super::TriviaBuilder; + use super::{PendingToken, TriviaBuilder}; #[test] fn annotation_flags_restored_when_replaying_comments() { @@ -566,18 +755,23 @@ mod test { let source_end = u32::try_from(source.len()).unwrap(); let allocator = Allocator::default(); let mut builder = TriviaBuilder::new_in(&allocator); + let mut pending = PendingToken::START_OF_FILE; builder.add_block_comment( 0, annotation_end, CommentKind::SingleLineBlock, + false, &source, + &mut pending, ); if !suffix.is_empty() { builder.add_block_comment( annotation_end, source_end, CommentKind::SingleLineBlock, + false, &source, + &mut pending, ); } @@ -600,7 +794,9 @@ mod test { 0, annotation_end, CommentKind::SingleLineBlock, + false, &source, + &mut pending, ); assert_eq!(builder.previous_token_pure_comments(), pure); assert_eq!(builder.previous_token_no_side_effects_comments(), no_side_effects); @@ -794,13 +990,18 @@ token /* Trailing 1 */ ("a /* trailing */\n+ b", CommentPosition::Trailing, 1), ("a\n/* leading */ +b", CommentPosition::Leading, 16), ("void /* leading */ +value", CommentPosition::Leading, 19), + ("x = a < b < c >> /*x*/ + d;", CommentPosition::Leading, 23), ("a /* webpackFoo: 1 */ + b", CommentPosition::Trailing, 1), ("foo(); /* trailing */", CommentPosition::Trailing, 6), ] { - let comments = get_comments(source_text); - assert_eq!(comments.len(), 1, "{source_text}"); - assert_eq!(comments[0].position, position, "{source_text}"); - assert_eq!(comments[0].attached_to, attached_to, "{source_text}"); + for (language, comments) in [ + ("JavaScript", get_comments(source_text)), + ("TypeScript", get_comments_typescript(source_text)), + ] { + assert_eq!(comments.len(), 1, "{language}: {source_text}"); + assert_eq!(comments[0].position, position, "{language}: {source_text}"); + assert_eq!(comments[0].attached_to, attached_to, "{language}: {source_text}"); + } } } @@ -1246,9 +1447,7 @@ function bar() {}"; ("/* foo @license*/", CommentContent::Legal), ("/* foo @licensed*/", CommentContent::Legal), ("/* foo @License*/", CommentContent::None), - // spellchecker:disable-next-line ("/* foo @licens*/", CommentContent::None), - // spellchecker:disable-next-line ("/* foo @preserv*/", CommentContent::None), ("/* @foo @preserve */", CommentContent::Legal), ("/* @foo @license */", CommentContent::Legal), diff --git a/vendor/oxc_parser/src/lexer/typescript.rs b/vendor/oxc_parser/src/lexer/typescript.rs index f1d59a504..823612000 100644 --- a/vendor/oxc_parser/src/lexer/typescript.rs +++ b/vendor/oxc_parser/src/lexer/typescript.rs @@ -3,17 +3,13 @@ use crate::config::LexerConfig as Config; use super::{Kind, Lexer, Token}; impl Lexer<'_, C> { - /// Re-tokenize `<<`, `<=`, or `<<=` to `<`. + /// Re-tokenize `<<` or `<<=` to `<`. /// /// Called when the parser encounters a compound token starting with `<` (e.g. `<<`) /// in a position where it could be the start of type arguments (e.g. `foo<()>`). /// The lexer eagerly produces the compound token, but the parser needs a single `<` /// to speculatively try parsing type arguments. /// - /// Only `<<` reaches here in code which parses. `<=` and `<<=` arrive only from the type-context - /// callers in `ts/types.rs` and always go on to fail, for the reason documented on - /// `parse_type_arguments_in_expression`, which rejects them before reaching here. - /// /// The compound token was pushed to the collected token stream *before* `try_parse` /// created its checkpoint (since it was the "current" token at that point), so it is /// the last token in the stream. Overwrite it there with the single `<`. The remaining @@ -24,7 +20,7 @@ impl Lexer<'_, C> { /// as the last collected token, and the caller (`expression.rs`) restores the original /// compound token over it via `rewrite_last_collected_token`. pub(crate) fn re_lex_as_typescript_l_angle(&mut self, offset: u32) -> Token { - self.token.set_start(self.offset() - offset); + self.token_start = self.offset() - offset; self.source.back(offset as usize - 1); let token = self.finish_re_lex(Kind::LAngle); self.rewrite_last_collected_token(token); @@ -46,7 +42,7 @@ impl Lexer<'_, C> { /// the parse. Since both the original push and the Replace are at a post-checkpoint /// position, `truncate(checkpoint.tokens_len)` on rewind removes it automatically. pub(crate) fn re_lex_as_typescript_r_angle(&mut self, offset: u32) -> Token { - self.token.set_start(self.offset() - offset); + self.token_start = self.offset() - offset; self.source.back(offset as usize - 1); self.finish_re_lex(Kind::RAngle) } diff --git a/vendor/oxc_parser/src/lexer/unicode.rs b/vendor/oxc_parser/src/lexer/unicode.rs index 35ef708e1..f6131099b 100644 --- a/vendor/oxc_parser/src/lexer/unicode.rs +++ b/vendor/oxc_parser/src/lexer/unicode.rs @@ -56,16 +56,16 @@ impl<'a, C: Config> Lexer<'a, C> { #[cold] fn handle_irregular_whitespace(&mut self, _c: char) -> Kind { self.consume_char(); - self.trivia_builder.add_irregular_whitespace(self.token.start(), self.offset()); + self.trivia_builder.add_irregular_whitespace(self.token_start, self.offset()); Kind::Skip } #[cold] fn handle_irregular_line_terminator(&mut self, _c: char) -> Kind { self.consume_char(); - self.token.set_is_on_new_line(true); - self.trivia_builder.handle_newline(); - self.trivia_builder.add_irregular_whitespace(self.token.start(), self.offset()); + self.pending.set_is_on_new_line(); + self.trivia_builder.handle_newline(&mut self.pending); + self.trivia_builder.add_irregular_whitespace(self.token_start, self.offset()); Kind::Skip } @@ -135,9 +135,8 @@ impl<'a, C: Config> Lexer<'a, C> { /// \u{ `CodePoint` } fn string_unicode_escape_sequence( &mut self, - text: &mut JSStrBuilder<'a>, is_valid_escape_sequence: &mut bool, - ) { + ) -> Option { let value = match self.peek_byte() { Some(b'{') => { self.consume_char(); @@ -149,14 +148,14 @@ impl<'a, C: Config> Lexer<'a, C> { let Some(value) = value else { // error raised within the parser by `diagnostics::template_literal` *is_valid_escape_sequence = false; - return; + return None; }; match value { - UnicodeEscape::CodePoint(ch) | UnicodeEscape::SurrogatePair(ch) => text.push(ch), + UnicodeEscape::CodePoint(ch) | UnicodeEscape::SurrogatePair(ch) => Some(ch.into()), UnicodeEscape::LoneSurrogate(code_point) => { // Escape decoding restricts this value to the surrogate range. - text.push_js_char(JSChar::from_u32(code_point).unwrap()); + Some(JSChar::from_u32(code_point).unwrap()) } } } @@ -297,98 +296,115 @@ impl<'a, C: Config> Lexer<'a, C> { in_template: bool, is_valid_escape_sequence: &mut bool, ) { - match self.next_char() { - None => { - self.error(diagnostics::unterminated_string(self.unterminated_range())); + if let Some(value) = + self.decode_string_escape_sequence(in_template, is_valid_escape_sequence) + { + if let Some(c) = value.to_char() { + text.push(c); + } else { + text.push_js_char(value); } - Some(c) => match c { - // \ LineTerminatorSequence - // LineTerminatorSequence :: - // - // [lookahead ≠ ] - // - // - // - LF | LS | PS => {} - CR => { - self.next_ascii_byte_eq(b'\n'); - } - // SingleEscapeCharacter :: one of - // ' " \ b f n r t v - '\'' | '"' | '\\' => text.push(c), - 'b' => text.push('\u{8}'), - 'f' => text.push(FF), - 'n' => text.push(LF), - 'r' => text.push(CR), - 't' => text.push(TAB), - 'v' => text.push(VT), - // HexEscapeSequence - 'x' => { - self.hex_digit() - .and_then(|value1| { - let value2 = self.hex_digit()?; - Some((value1, value2)) - }) - .map(|(value1, value2)| { - #[expect( - clippy::cast_possible_truncation, - reason = "Two hex digits are at most 0xFF" - )] - let value = ((value1 << 4) | value2) as u8; - char::from(value) - }) - .map_or_else( - || { - *is_valid_escape_sequence = false; - }, - |c| { - text.push(c); - }, - ); - } - // UnicodeEscapeSequence - 'u' => { - self.string_unicode_escape_sequence(text, is_valid_escape_sequence); - } - // 0 [lookahead ∉ DecimalDigit] - '0' if !self.peek_byte().is_some_and(|b| b.is_ascii_digit()) => text.push('\0'), - // Section 12.9.4 String Literals - // LegacyOctalEscapeSequence - // NonOctalDecimalEscapeSequence - c @ '0'..='7' if !in_template => { - let first_digit = c as u8 - b'0'; - let mut value = first_digit; - - if matches!(self.peek_byte(), Some(b'0'..=b'7')) { + } + } + + /// Decode an escape without allocating storage for its value. + /// Line continuations and invalid escapes produce no text. + pub(super) fn decode_string_escape_sequence( + &mut self, + in_template: bool, + is_valid_escape_sequence: &mut bool, + ) -> Option { + let Some(c) = self.next_char() else { + self.error(diagnostics::unterminated_string(self.unterminated_range())); + return None; + }; + let value = match c { + // \ LineTerminatorSequence + // LineTerminatorSequence :: + // + // [lookahead ≠ ] + // + // + // + LF | LS | PS => return None, + CR => { + self.next_ascii_byte_eq(b'\n'); + return None; + } + // SingleEscapeCharacter :: one of + // ' " \ b f n r t v + '\'' | '"' | '\\' => c, + 'b' => '\u{8}', + 'f' => FF, + 'n' => LF, + 'r' => CR, + 't' => TAB, + 'v' => VT, + // HexEscapeSequence + 'x' => { + let value = self + .hex_digit() + .and_then(|value1| { + let value2 = self.hex_digit()?; + Some((value1, value2)) + }) + .map(|(value1, value2)| { + #[expect( + clippy::cast_possible_truncation, + reason = "Two hex digits are at most 0xFF" + )] + let value = ((value1 << 4) | value2) as u8; + char::from(value) + }); + let Some(value) = value else { + *is_valid_escape_sequence = false; + return None; + }; + value + } + // UnicodeEscapeSequence + 'u' => { + return self.string_unicode_escape_sequence(is_valid_escape_sequence); + } + // 0 [lookahead ∉ DecimalDigit] + '0' if !self.peek_byte().is_some_and(|b| b.is_ascii_digit()) => '\0', + // Section 12.9.4 String Literals + // LegacyOctalEscapeSequence + // NonOctalDecimalEscapeSequence + c @ '0'..='7' if !in_template => { + let first_digit = c as u8 - b'0'; + let mut value = first_digit; + + if matches!(self.peek_byte(), Some(b'0'..=b'7')) { + let digit = self.consume_char() as u8 - b'0'; + value = value * 8 + digit; + if first_digit < 4 && matches!(self.peek_byte(), Some(b'0'..=b'7')) { let digit = self.consume_char() as u8 - b'0'; value = value * 8 + digit; - if first_digit < 4 && matches!(self.peek_byte(), Some(b'0'..=b'7')) { - let digit = self.consume_char() as u8 - b'0'; - value = value * 8 + digit; - } } - - text.push(char::from(value)); - } - '0' => { - // The previous zero and octal arms handled every other case. - debug_assert!( - in_template && self.peek_byte().is_some_and(|b| b.is_ascii_digit()) - ); - self.consume_char(); - // error raised within the parser by `diagnostics::template_literal` - *is_valid_escape_sequence = false; - } - // NotEscapeSequence :: DecimalDigit but not 0 - '1'..='9' if in_template => { - // error raised within the parser by `diagnostics::template_literal` - *is_valid_escape_sequence = false; } - other => { - // NonOctalDecimalEscapeSequence \8 \9 in strict mode - text.push(other); - } - }, - } + + char::from(value) + } + '0' => { + // The previous zero and octal arms handled every other case. + debug_assert!(in_template && self.peek_byte().is_some_and(|b| b.is_ascii_digit())); + self.consume_char(); + // error raised within the parser by `diagnostics::template_literal` + *is_valid_escape_sequence = false; + return None; + } + // NotEscapeSequence :: DecimalDigit but not 0 + '1'..='9' if in_template => { + // error raised within the parser by `diagnostics::template_literal` + *is_valid_escape_sequence = false; + return None; + } + other => { + // NonOctalDecimalEscapeSequence \8 \9 in strict mode + other + } + }; + Some(value.into()) } } diff --git a/vendor/oxc_parser/src/lexer/whitespace.rs b/vendor/oxc_parser/src/lexer/whitespace.rs index c171ae6f4..3f7bb3049 100644 --- a/vendor/oxc_parser/src/lexer/whitespace.rs +++ b/vendor/oxc_parser/src/lexer/whitespace.rs @@ -1,7 +1,8 @@ use crate::config::LexerConfig as Config; use super::{ - Kind, Lexer, + Kind, Lexer, PendingToken, SourcePosition, Token, byte_handlers, + identifier::is_identifier_start_ascii_byte, search::{SafeByteMatchTable, byte_search, safe_byte_match_table}, }; @@ -11,7 +12,7 @@ static NOT_REGULAR_WHITESPACE_TABLE: SafeByteMatchTable = static NOT_REGULAR_WHITESPACE_OR_LINE_BREAK_TABLE: SafeByteMatchTable = safe_byte_match_table!(|b| !matches!(b, b' ' | b'\t' | b'\r' | b'\n')); -impl Lexer<'_, C> { +impl<'a, C: Config> Lexer<'a, C> { pub(super) fn whitespace_handler(&mut self) -> Kind { // Single spaces between tokens are consumed directly by `read_next_token`. // Scan additional spaces and tabs in one pass to avoid repeated token-loop @@ -27,20 +28,113 @@ impl Lexer<'_, C> { Kind::Skip } - pub(super) fn line_break_handler(&mut self) -> Kind { - self.token.set_is_on_new_line(true); - self.trivia_builder.handle_newline(); + /// Skip regular whitespace after a line break, returning the next byte or `None` at EOF. + pub(super) fn line_break_handler(&mut self) -> Option { + self.pending.set_is_on_new_line(); + self.trivia_builder.handle_newline(&mut self.pending); // Indentation is common after a line break. // Consume it, along with any further line breaks. // Irregular line breaks and whitespace are not consumed. // They're uncommon, so leave them for the next call to `handle_byte` to take care of. - byte_search! { + let byte = byte_search! { lexer: self, table: NOT_REGULAR_WHITESPACE_OR_LINE_BREAK_TABLE, - handle_eof: 0, // Fall through to below + handle_eof: return None, }; - Kind::Skip + Some(byte) + } + + /// Read the next token, where the first trivia seen since the previous token is the line break + /// at `pos`. + /// + /// A line break is usually followed by indentation, then a keyword, an identifier or `}`. + /// Those tokens are finished here, without the work which `finish_next_inner` does + /// for flags and comments. All that needs to be recorded is that they are on a new line. + /// + /// # SAFETY + /// * `pos` must be the position of a `\r` or `\n` byte. + /// * No trivia must have been seen since the previous token, other than one space. + #[expect(clippy::inline_always)] + #[inline(always)] + pub(super) unsafe fn line_break_token(&mut self, pos: SourcePosition<'a>) -> Token { + // SAFETY: Caller guarantees `pos` is the position of an ASCII byte + let after_line_break = unsafe { pos.add(1) }; + + // Consume indentation, along with any further line breaks + let byte = byte_search! { + lexer: self, + table: NOT_REGULAR_WHITESPACE_OR_LINE_BREAK_TABLE, + start: after_line_break, + // A byte which does not start a token, so that EOF takes the general path below + handle_eof: b' ', + }; + let pos = self.source.position(); + + if is_identifier_start_ascii_byte(byte) { + // Keywords are more common than identifiers at the start of a line, + // so check for a keyword whatever the first letter is. + // SAFETY: `byte` is the byte at `pos`, and it is ASCII + return unsafe { self.identifier_token::(pos) }; + } + + if let Some(kind) = byte_handlers::single_byte_token(byte) { + // SAFETY: `byte` is the byte at `pos`, and single-byte tokens are ASCII + let end = unsafe { pos.add(1) }; + self.source.set_position(end); + return self.finish_fresh_token_on_new_line(kind, pos, end); + } + + // Strings, comments, and everything else. + // SAFETY: `pos` is the current position of source. `byte` is the byte at `pos`, + // or a space if `pos` is the end of source. + unsafe { self.next_token_after_line_break(pos, byte) } + } + + /// Read the next token, where the first trivia seen since the previous token is line breaks + /// and regular whitespace, and they are followed by `byte` at `pos`, which does not start + /// an identifier or a single-byte token. + /// + /// This is not inlined into `line_break_token`, so the tokens which that finishes do not pay + /// for the stack frame which this requires. + /// + /// # SAFETY + /// * `pos` must be the current position of source. + /// * `byte` must be the byte at `pos`, or a space if `pos` is the end of source. + #[inline(never)] + unsafe fn next_token_after_line_break(&mut self, pos: SourcePosition<'a>, byte: u8) -> Token { + debug_assert_eq!(pos, self.source.position()); + debug_assert_eq!(self.pending, PendingToken::NONE); + + // A string which starts a line is usually an element of an array, or a directive + let plain_string = match byte { + // SAFETY: `byte` is the byte at `pos`, and it is `"` + b'"' => Some(unsafe { self.read_plain_string_literal_double_quote(pos) }), + // SAFETY: `byte` is the byte at `pos`, and it is `'` + b'\'' => Some(unsafe { self.read_plain_string_literal_single_quote(pos) }), + _ => None, + }; + if let Some(Ok(end)) = plain_string { + return self.finish_fresh_token_on_new_line(Kind::Str, pos, end); + } + + // No trivia was seen before the line break, so this is all that needs to be recorded + self.pending = PendingToken::AFTER_LINE_BREAK; + + if let Some(Err(next_byte)) = plain_string { + // SAFETY: `byte` is the byte at `pos`, and it is the quote which the method called + // is for. Position of source has not been altered since the plain string was read. + return unsafe { + if byte == b'"' { + self.string_token_rest_double_quote(pos, next_byte) + } else { + self.string_token_rest_single_quote(pos, next_byte) + } + }; + } + + // Comments, and everything else + self.next_token_after_trivia() } } diff --git a/vendor/oxc_parser/src/lib.rs b/vendor/oxc_parser/src/lib.rs index b515a8b3c..0241e356c 100644 --- a/vendor/oxc_parser/src/lib.rs +++ b/vendor/oxc_parser/src/lib.rs @@ -64,13 +64,14 @@ //! //! See [full linter example](https://github.com/Boshen/oxc/blob/ab2ef4f89ba3ca50c68abb2ca43e36b7793f3673/crates/oxc_linter/examples/linter.rs#L38-L39) -use std::any::Any; +use std::{any::Any, cell::Cell}; mod ast_builder; pub mod config; mod context; mod cursor; mod error_handler; +mod list; mod modifiers; mod module_record; mod state; @@ -93,6 +94,7 @@ use oxc_ast::{ ast::{Expression, Program, Statement}, builder::{AstBuilder, GetAstBuilder}, }; +use oxc_data_structures::brands::{BrandOrigin, BrandScope, Unbranded}; use oxc_diagnostics::Diagnostics; use oxc_span::{SourceType, Span}; use oxc_syntax::module_record::ModuleRecord; @@ -128,7 +130,7 @@ use crate::{ // so they can be stored as `u32`s without any possibility of overflow. // 3. No real `Span` can have `start` or `end` of `u32::MAX`, so such a `Span` can be used as a sentinel. // `oxc_transformer`'s styled-components plugin relies on this. -pub(crate) const MAX_LEN: usize = if size_of::() >= 8 { +const MAX_LEN: usize = if size_of::() >= 8 { // 64-bit systems u32::MAX as usize - 256 } else { @@ -136,6 +138,12 @@ pub(crate) const MAX_LEN: usize = if size_of::() >= 8 { isize::MAX as usize }; +const MAX_LEN_ERROR: &str = if size_of::() >= 8 { + "Source length exceeds 4 GiB limit" +} else { + "Source length exceeds 2 GiB limit" +}; + /// Return value of [`Parser::parse`] consisting of AST, errors and comments /// /// ## AST Validity @@ -224,6 +232,22 @@ pub struct ParserReturn<'a> { pub speculation_budget_exhausted: bool, } +// `ParserReturn` is the output of `ParserImpl::parse`. +// It's created inside a closure, with the closure's `'brand` lifetime. +// `BrandScope::extend_lifetime` changes that lifetime to the lifetime of the allocator +// and source text. +// That's only allowed for types which implement `Unbranded`. +// +// SAFETY: `ParserReturn` meets `Unbranded`'s contract. +// - It doesn't name `BrandOrigin` or `Brand`, or any type which does. In this crate, +// those types are `Source` and `SourcePosition`, and the types which contain them +// (`Lexer`, `LexerCheckpoint`, `ParserCheckpoint`, `ParserState`, `ParserImpl`). +// - It doesn't contain a `dyn Trait + 'a`. +// - Its lifetime is the lifetime of the arena. Nothing uses it as a brand. +unsafe impl Unbranded for ParserReturn<'_> { + type WithLifetime<'a> = ParserReturn<'a>; +} + /// Parse options /// /// You may provide options to the [`Parser`] using [`Parser::with_options`]. @@ -292,14 +316,13 @@ pub struct ParseOptions { /// How much work the parser may spend on speculative parses. /// - /// A speculative parse, such as of a parenthesized list that may be - /// arrow parameters, takes a checkpoint and rewinds to it when it fails, - /// and a lookahead reads a few tokens and rewinds the lexer. Each byte the - /// lexer has read beyond its position after such rewinds costs one, and - /// each lexer diagnostic copied into a checkpoint that can restore them - /// costs 16. When the total passes this budget, the parser stops with a - /// fatal error and [`ParserReturn::speculation_budget_exhausted`] set. A - /// budget proportional to the source's length keeps the work spent on + /// A speculative parse, such as of type arguments that may turn out to be + /// comparisons, takes a checkpoint and rewinds to it when it fails, and a + /// lookahead reads a few tokens and rewinds the lexer. Each byte the lexer + /// has read beyond its position after such rewinds costs one. When the + /// total passes this budget, the parser stops with a fatal error and + /// [`ParserReturn::speculation_budget_exhausted`] set. A budget + /// proportional to the source's length keeps the work spent on /// speculation proportional to it too. /// /// Default: `0`, no limit @@ -366,299 +389,168 @@ impl<'a, C: ParserConfig> Parser<'a, C> { config, } } -} - -mod parser_parse { - use super::*; - /// `UniquePromise` is a way to use the type system to enforce the invariant that only - /// a single `ParserImpl`, `Lexer` and `lexer::Source` can exist at any time on a thread. - /// This constraint is required to guarantee the soundness of some methods of these types - /// e.g. `Source::set_position`. - /// - /// `ParserImpl::new`, `Lexer::new` and `lexer::Source::new` all require a `UniquePromise` - /// to be provided to them. `UniquePromise::new` is not visible outside this module, so only - /// `Parser::parse` can create one, and it only calls `ParserImpl::new` once. - /// This enforces the invariant throughout the entire parser. + /// Main entry point /// - /// `UniquePromise` is a zero-sized type and has no runtime cost. It's purely for the type-checker. + /// Returns an empty `Program` on unrecoverable error, + /// Recoverable errors are stored inside `errors`. /// - /// `UniquePromise::new_for_tests_and_benchmarks` is a backdoor for tests/benchmarks, so they can - /// create a `ParserImpl` or `Lexer`, and manipulate it directly, for testing/benchmarking purposes. - pub struct UniquePromise(()); - - impl UniquePromise { - #[inline] - fn new() -> Self { - Self(()) - } - - /// Backdoor for tests/benchmarks to create a `UniquePromise` (see above). - /// This function must NOT be exposed outside of tests and benchmarks, - /// as it allows circumventing safety invariants of the parser. - #[cfg(any(test, feature = "benchmarking"))] - pub fn new_for_tests_and_benchmarks() -> Self { - Self(()) - } - } - - impl<'a, C: ParserConfig> Parser<'a, C> { - /// Main entry point - /// - /// Returns an empty `Program` on unrecoverable error, - /// Recoverable errors are stored inside `errors`. - /// - /// See the [module-level documentation](crate) for examples and more information. - // - // # Implementation note - // - // Dispatches via `Any` to a non-generic helper for each known `ParserConfig`. - // The dispatch keeps the parser body emitted exactly once in `oxc_parser`'s rlib, - // so consuming crates don't each get a private copy. The `Any::is` / `downcast_ref` - // calls const-fold when `C` is concrete (the trait object is built from a known - // concrete type at every monomorphization site, so LLVM devirtualises the vtable - // call to `Any::type_id` and folds the comparison), leaving each monomorphization - // as a single call into the matching helper. - pub fn parse(self) -> ParserReturn<'a> { - let config: &dyn Any = &self.config; - if config.is::() { - parse_with_no_tokens_config( - self.allocator, - self.source_text, - self.source_type, - self.options, - ) - } else if config.is::() { - parse_with_tokens_config( - self.allocator, - self.source_text, - self.source_type, - self.options, - ) - } else if let Some(&config) = config.downcast_ref::() { - parse_with_runtime_config( - self.allocator, - self.source_text, - self.source_type, - self.options, - config, - ) - } else { - // User-defined `ParserConfig`. Generic codegen here, monomorphized per consuming crate. - // Users using custom configs would need to perform the monomorphization themselves. - ParserImpl::::new( - self.allocator, - self.source_text, - self.source_type, - self.options, - self.config, - UniquePromise::new(), + /// See the [module-level documentation](crate) for examples and more information. + // + // # Implementation note + // + // The parser is generic over `C: ParserConfig`. Rust monomorphizes generic functions + // per consuming crate (the legacy mangled name encodes the instantiating crate's + // disambiguator, and `share-generics` is off at `opt-level >= 2`). + // For a parser that's pulled in by ~15 crates in a real workspace, that means ~15 private + // copies of every parser method in the final cdylib. None of them can be deduped by COMDAT + // (different names) or fat LTO (slightly different inlining contexts). + // + // To avoid that, `parse` and `parse_expression` dispatch via `Any` to a non-generic helper + // for each of the 3 known configs. + // + // - Each helper is non-generic, so it's emitted exactly once in `oxc_parser`'s rlib, + // and shared by all consumers. + // - The helpers are `#[inline(never)]`, to prevent fat LTO from re-inlining the parser body + // across the rlib boundary, which would defeat the purpose. + // - The `Any::is` / `downcast_ref` checks const-fold when `C` is concrete. The trait object + // is built from a known concrete type at every monomorphization site, so LLVM devirtualises + // the vtable call to `Any::type_id`, and folds the comparison. That leaves + // each monomorphization of the dispatch as a single call into the matching helper. + // - A user-defined `ParserConfig` (rare) falls through to a generic body, which is + // monomorphized per consuming crate. That's the same cost the parser had without + // this pattern. It's just contained to the rare custom-config case. + pub fn parse(self) -> ParserReturn<'a> { + let Self { allocator, source_text, source_type, options, config } = self; + + let config_any: &dyn Any = &config; + if config_any.is::() { + #[inline(never)] + fn parse<'a>( + allocator: &'a Allocator, + source_text: &'a str, + source_type: SourceType, + options: ParseOptions, + ) -> ParserReturn<'a> { + ParserImpl::parse( + allocator, + source_text, + source_type, + options, + NoTokensParserConfig, ) - .parse() } + parse(allocator, source_text, source_type, options) + } else if config_any.is::() { + #[inline(never)] + fn parse<'a>( + allocator: &'a Allocator, + source_text: &'a str, + source_type: SourceType, + options: ParseOptions, + ) -> ParserReturn<'a> { + ParserImpl::parse(allocator, source_text, source_type, options, TokensParserConfig) + } + parse(allocator, source_text, source_type, options) + } else if let Some(&config) = config_any.downcast_ref::() { + #[inline(never)] + fn parse<'a>( + allocator: &'a Allocator, + source_text: &'a str, + source_type: SourceType, + options: ParseOptions, + config: RuntimeParserConfig, + ) -> ParserReturn<'a> { + ParserImpl::parse(allocator, source_text, source_type, options, config) + } + parse(allocator, source_text, source_type, options, config) + } else { + // User-defined `ParserConfig`. Generic codegen here, monomorphized per consuming crate. + // Users using custom configs would need to perform the monomorphization themselves. + ParserImpl::parse(allocator, source_text, source_type, options, config) } + } - /// Parse a single [`Expression`]. - /// - /// Every node receives a unique, nonzero node ID. IDs follow construction - /// order and may have gaps from discarded nodes. - /// - /// # Example - /// - /// ```rust - /// use oxc_allocator::Allocator; - /// use oxc_ast::ast::Expression; - /// use oxc_parser::Parser; - /// use oxc_span::SourceType; - /// - /// let src = "1 + 2"; - /// let allocator = Allocator::new(); - /// let source_type = SourceType::default(); - /// - /// let expr: Expression<'_> = Parser::new(&allocator, src, source_type).parse_expression().unwrap(); - /// ``` - /// - /// # Errors - /// If the source code being parsed has syntax errors. - // - // # Implementation note - // Dispatches via `Any`, same as `parse` does. - pub fn parse_expression(self) -> Result, Diagnostics> { - let config: &dyn Any = &self.config; - if config.is::() { - parse_expression_with_no_tokens_config( - self.allocator, - self.source_text, - self.source_type, - self.options, - ) - } else if config.is::() { - parse_expression_with_tokens_config( - self.allocator, - self.source_text, - self.source_type, - self.options, - ) - } else if let Some(&config) = config.downcast_ref::() { - parse_expression_with_runtime_config( - self.allocator, - self.source_text, - self.source_type, - self.options, - config, + /// Parse a single [`Expression`]. + /// + /// Every node receives a unique, nonzero node ID. IDs follow construction + /// order and may have gaps from discarded nodes. + /// + /// # Example + /// + /// ```rust + /// use oxc_allocator::Allocator; + /// use oxc_ast::ast::Expression; + /// use oxc_parser::Parser; + /// use oxc_span::SourceType; + /// + /// let src = "1 + 2"; + /// let allocator = Allocator::new(); + /// let source_type = SourceType::default(); + /// + /// let expr: Expression<'_> = Parser::new(&allocator, src, source_type).parse_expression().unwrap(); + /// ``` + /// + /// # Errors + /// If the source code being parsed has syntax errors. + // + // # Implementation note + // Dispatches via `Any`, same as `parse` does. + pub fn parse_expression(self) -> Result, Diagnostics> { + let Self { allocator, source_text, source_type, options, config } = self; + + let config_any: &dyn Any = &config; + if config_any.is::() { + #[inline(never)] + fn parse<'a>( + allocator: &'a Allocator, + source_text: &'a str, + source_type: SourceType, + options: ParseOptions, + ) -> Result, Diagnostics> { + ParserImpl::parse_expression( + allocator, + source_text, + source_type, + options, + NoTokensParserConfig, ) - } else { - ParserImpl::::new( - self.allocator, - self.source_text, - self.source_type, - self.options, - self.config, - UniquePromise::new(), + } + parse(allocator, source_text, source_type, options) + } else if config_any.is::() { + #[inline(never)] + fn parse<'a>( + allocator: &'a Allocator, + source_text: &'a str, + source_type: SourceType, + options: ParseOptions, + ) -> Result, Diagnostics> { + ParserImpl::parse_expression( + allocator, + source_text, + source_type, + options, + TokensParserConfig, ) - .parse_expression() } + parse(allocator, source_text, source_type, options) + } else if let Some(&config) = config_any.downcast_ref::() { + #[inline(never)] + fn parse<'a>( + allocator: &'a Allocator, + source_text: &'a str, + source_type: SourceType, + options: ParseOptions, + config: RuntimeParserConfig, + ) -> Result, Diagnostics> { + ParserImpl::parse_expression(allocator, source_text, source_type, options, config) + } + parse(allocator, source_text, source_type, options, config) + } else { + ParserImpl::parse_expression(allocator, source_text, source_type, options, config) } } - - // =========================================================================== - // Non-generic parse helpers, one per known `ParserConfig`. - // - // The parser is generic over `C: ParserConfig`. By default Rust monomorphizes - // generic functions per consuming crate (the legacy mangled name encodes the - // instantiating crate's disambiguator, and `share-generics` is off at - // `opt-level >= 2`). For a parser that's pulled in by ~15 crates in a real - // workspace, that means ~15 private copies of every parser method in the - // final cdylib — none of which can be deduped by COMDAT (different names) - // or fat LTO (slightly different inlining contexts). - // - // To avoid that, `Parser::parse` and `Parser::parse_expression` dispatch - // via `Any` to one of the helpers below for the three known configs. - // Each helper is non-generic, so it's emitted exactly once in `oxc_parser`'s - // rlib and shared by all consumers. The `Any::is` / `downcast_ref` checks fold - // at compile time when `C` is concrete, so each monomorphization of the dispatch - // shrinks to a single call into the matching helper. - // - // The helpers are `#[inline(never)]` to prevent fat LTO from re-inlining the - // parser body across the rlib boundary, which would defeat the purpose. - // - // For user-defined `ParserConfig` impls (rare), the dispatch falls through - // to a generic body that monomorphizes per consuming crate. That's the same - // cost the parser had without this pattern; we just keep that cost contained - // to the rare custom-config case. - // =========================================================================== - - #[inline(never)] - fn parse_with_no_tokens_config<'a>( - allocator: &'a Allocator, - source_text: &'a str, - source_type: SourceType, - options: ParseOptions, - ) -> ParserReturn<'a> { - ParserImpl::::new( - allocator, - source_text, - source_type, - options, - NoTokensParserConfig, - UniquePromise::new(), - ) - .parse() - } - - #[inline(never)] - fn parse_with_tokens_config<'a>( - allocator: &'a Allocator, - source_text: &'a str, - source_type: SourceType, - options: ParseOptions, - ) -> ParserReturn<'a> { - ParserImpl::::new( - allocator, - source_text, - source_type, - options, - TokensParserConfig, - UniquePromise::new(), - ) - .parse() - } - - #[inline(never)] - fn parse_with_runtime_config<'a>( - allocator: &'a Allocator, - source_text: &'a str, - source_type: SourceType, - options: ParseOptions, - config: RuntimeParserConfig, - ) -> ParserReturn<'a> { - ParserImpl::::new( - allocator, - source_text, - source_type, - options, - config, - UniquePromise::new(), - ) - .parse() - } - - #[inline(never)] - fn parse_expression_with_no_tokens_config<'a>( - allocator: &'a Allocator, - source_text: &'a str, - source_type: SourceType, - options: ParseOptions, - ) -> Result, Diagnostics> { - ParserImpl::::new( - allocator, - source_text, - source_type, - options, - NoTokensParserConfig, - UniquePromise::new(), - ) - .parse_expression() - } - - #[inline(never)] - fn parse_expression_with_tokens_config<'a>( - allocator: &'a Allocator, - source_text: &'a str, - source_type: SourceType, - options: ParseOptions, - ) -> Result, Diagnostics> { - ParserImpl::::new( - allocator, - source_text, - source_type, - options, - TokensParserConfig, - UniquePromise::new(), - ) - .parse_expression() - } - - #[inline(never)] - fn parse_expression_with_runtime_config<'a>( - allocator: &'a Allocator, - source_text: &'a str, - source_type: SourceType, - options: ParseOptions, - config: RuntimeParserConfig, - ) -> Result, Diagnostics> { - ParserImpl::::new( - allocator, - source_text, - source_type, - options, - config, - UniquePromise::new(), - ) - .parse_expression() - } } -use parser_parse::UniquePromise; /// Implementation of parser. /// `Parser` is just a public wrapper, the guts of the implementation is in this type. @@ -710,37 +602,42 @@ struct ParserImpl<'a, C: ParserConfig> { /// Precomputed typescript detection is_ts: bool, - /// Parsing reached [`ParseOptions::stack_floor`]. - stack_exhausted: bool, + /// Parsing reached [`ParseOptions::stack_floor`]. A `Cell`, so that a + /// check that reads no token and borrows the parser can record it. + stack_exhausted: Cell, /// [`ParseOptions::speculation_budget`], with `u64::MAX` for no limit. speculation_limit: u64, - /// Lexer diagnostics copied into checkpoints so far. - diagnostics_copied: u64, - /// Parsing reached [`ParseOptions::speculation_budget`]. speculation_budget_exhausted: bool, } impl<'a, C: ParserConfig> ParserImpl<'a, C> { - /// Create a new `ParserImpl`. + /// Create a new [`ParserImpl`]. /// - /// Requiring a `UniquePromise` to be provided guarantees only 1 `ParserImpl` can exist - /// on a single thread at one time. + /// `brand_origin` is for the `Source` in the `ParserImpl`'s [`Lexer`] (see [`brands`]). + /// + /// [`brands`]: oxc_data_structures::brands #[inline] #[expect(clippy::needless_pass_by_value)] - pub fn new( + fn new( allocator: &'a Allocator, source_text: &'a str, source_type: SourceType, options: ParseOptions, config: C, - unique: UniquePromise, + brand_origin: BrandOrigin<'a>, ) -> Self { Self { options, - lexer: Lexer::new(allocator, source_text, source_type, config.lexer_config(), unique), + lexer: Lexer::new( + allocator, + source_text, + source_type, + config.lexer_config(), + brand_origin, + ), source_type, source_text, errors: vec![], @@ -748,18 +645,17 @@ impl<'a, C: ParserConfig> ParserImpl<'a, C> { fatal_error: None, token: Token::default(), prev_token_end: 0, - state: ParserState::new(), + state: ParserState::new(allocator), ctx: Self::default_context(source_type, options), ast: ParserAstBuilder::new(allocator), module_record_builder: ModuleRecordBuilder::new(allocator, source_type), is_ts: source_type.is_typescript(), - stack_exhausted: false, + stack_exhausted: Cell::new(false), speculation_limit: if options.speculation_budget == 0 { u64::MAX } else { options.speculation_budget }, - diagnostics_copied: 0, speculation_budget_exhausted: false, } } @@ -768,8 +664,32 @@ impl<'a, C: ParserConfig> ParserImpl<'a, C> { /// /// Returns an empty `Program` on unrecoverable error, /// Recoverable errors are stored inside `errors`. + fn parse( + allocator: &'a Allocator, + source_text: &'a str, + source_type: SourceType, + options: ParseOptions, + config: C, + ) -> ParserReturn<'a> { + // The `ParserImpl` is created inside the closure, with the closure's lifetime `'brand`. + // The closure must accept any `'brand`, so code in it can't treat `'brand` as the same + // as any other lifetime. That makes `'brand` a brand (see `oxc_data_structures::brands`). + // + // The `ParserImpl` is created and consumed in this one closure. Passing it by value + // into a 2nd closure would copy the whole `ParserImpl`, which is large. + BrandOrigin::scope_within(|brand_origin, brand_scope: BrandScope<'_, 'a>| { + // `allocator` and `source_text` are shortened from `'a` to `'brand` here + let parser = + ParserImpl::new(allocator, source_text, source_type, options, config, brand_origin); + let ret = parser.parse_impl(); + + // Change lifetime of the output from `'brand` back to `'a` + brand_scope.extend_lifetime::(ret) + }) + } + #[inline] - pub fn parse(mut self) -> ParserReturn<'a> { + fn parse_impl(mut self) -> ParserReturn<'a> { let mut program = self.parse_program(); let mut has_fatal_error = false; @@ -844,7 +764,7 @@ impl<'a, C: ParserConfig> ParserImpl<'a, C> { self.lexer.finalize_tokens() }; - program.comments = self.lexer.trivia_builder.comments; + program.comments = self.lexer.trivia_builder.comments.take_vec(&self.ast); ParserReturn { program, @@ -854,19 +774,51 @@ impl<'a, C: ParserConfig> ParserImpl<'a, C> { tokens, fatal_error: has_fatal_error, is_flow_language, - stack_exhausted: self.stack_exhausted, + stack_exhausted: self.stack_exhausted.get(), speculation_budget_exhausted: self.speculation_budget_exhausted, } } - pub fn parse_expression(mut self) -> Result, Diagnostics> { - // initialize cur_token and prev_token by moving onto the first token - self.bump_any(); + fn parse_expression( + allocator: &'a Allocator, + source_text: &'a str, + source_type: SourceType, + options: ParseOptions, + config: C, + ) -> Result, Diagnostics> { + /// Wrapper around `Result, Diagnostics>`. + /// `Result` is only [`Unbranded`] if `T` and `E` are. `Expression` and `Diagnostics` + /// are from other crates, so this crate can't implement `Unbranded` for them. + struct ExpressionParserReturn<'a>(Result, Diagnostics>); + + // SAFETY: `ExpressionParserReturn` meets `Unbranded`'s contract. + // `Expression` and `Diagnostics` don't name `BrandOrigin` or `Brand`, + // or any type which does, and they don't contain a `dyn Trait + 'a`. + // `Expression`'s lifetime is the lifetime of the arena. Nothing uses it as a brand. + unsafe impl Unbranded for ExpressionParserReturn<'_> { + type WithLifetime<'a> = ExpressionParserReturn<'a>; + } + + // See comments in `parse` + BrandOrigin::scope_within(|brand_origin, brand_scope: BrandScope<'_, 'a>| { + let parser = + ParserImpl::new(allocator, source_text, source_type, options, config, brand_origin); + let ret = parser.parse_expression_impl(); + + // Change lifetime of the output from `'brand` back to `'a` + brand_scope.extend_lifetime::(ExpressionParserReturn(ret)).0 + }) + } + + fn parse_expression_impl(mut self) -> Result, Diagnostics> { + // Initialize by moving onto the first token + self.token = self.lexer.first_token_without_hashbang(); let expr = self.parse_expr(); if !self.at(Kind::Eof) { self.set_unexpected(); } if let Some(FatalError { error, .. }) = self.fatal_error.take() { + let error = self.overlong_error().unwrap_or(error); return Err(error.into_diagnostic().into()); } self.check_unfinished_errors(); @@ -942,7 +894,8 @@ impl<'a, C: ParserConfig> ParserImpl<'a, C> { self, ); for (stmt_index, checkpoint) in checkpoints { - self.rewind(checkpoint); + // Only the statement is parsed again, so trivia after it is not lexed again. + self.rewind_keeping_trivia(checkpoint); let replacement_start = replacements.len(); if self.lexer.config.tokens() { @@ -1136,6 +1089,90 @@ mod test { } } + #[test] + fn asserted_exponentiation_preserve_parens() { + for preserve_parens in [true, false] { + for source in [ + "(-value) as number ** 2", + "(-value as number) ** 2", + "(-value) as any satisfies number ** 2", + "(value) satisfies number ** 2", + "async () => (await value) as number ** 2", + ] { + let allocator = Allocator::default(); + let result = Parser::new(&allocator, source, SourceType::ts()) + .with_options(ParseOptions { preserve_parens, ..ParseOptions::default() }) + .parse_expression(); + assert!(result.is_ok(), "{source}, preserve_parens={preserve_parens}"); + } + + for (source, operand) in [ + ("-value as any satisfies number ** 2", "-value"), + ("value as number ** 2", "value"), + ("async () => await value as number ** 2", "await value"), + ] { + let allocator = Allocator::default(); + let diagnostics = Parser::new(&allocator, source, SourceType::ts()) + .with_options(ParseOptions { preserve_parens, ..ParseOptions::default() }) + .parse_expression() + .unwrap_err(); + assert_eq!(diagnostics.len(), 1, "{source}, preserve_parens={preserve_parens}"); + let label = &diagnostics[0].labels[0]; + let start = label.offset() as usize; + let end = start + label.len() as usize; + assert_eq!(&source[start..end], operand); + } + } + } + + /// An unparenthesized instantiation gives its type arguments to the call, `new`, tag or superclass. + /// A parenthesized one stays whole as in TypeScript, also when the parentheses are not preserved. + #[test] + fn parenthesized_instantiation_expression() { + for preserve_parens in [true, false] { + // (source, keeps instantiation, outer has type arguments) + for (source, expected) in [ + ("a()", (false, true)), + ("(a)()", (true, false)), + ("new a()", (false, true)), + ("new a", (false, true)), + ("new (a)()", (true, false)), + ("new (a)", (true, false)), + ("a``", (false, true)), + ("(a)``", (true, false)), + ("class extends B {}", (false, true)), + ("class extends (B) {}", (true, false)), + ("class extends (B) {}", (true, true)), + ] { + let allocator = Allocator::default(); + let expr = Parser::new(&allocator, source, SourceType::ts()) + .with_options(ParseOptions { preserve_parens, ..ParseOptions::default() }) + .parse_expression() + .unwrap_or_else(|_| panic!("{source}, preserve_parens={preserve_parens}")); + let (target, type_arguments) = match &expr { + Expression::CallExpression(call) => (&call.callee, &call.type_arguments), + Expression::NewExpression(new) => (&new.callee, &new.type_arguments), + Expression::TaggedTemplateExpression(tagged) => { + (&tagged.tag, &tagged.type_arguments) + } + Expression::ClassExpression(class) => { + let heritage = class.heritage.as_ref().unwrap(); + (&heritage.expression, &heritage.type_arguments) + } + _ => unreachable!("{source}"), + }; + let actual = ( + matches!( + target.without_parentheses(), + Expression::TSInstantiationExpression(_) + ), + type_arguments.is_some(), + ); + assert_eq!(actual, expected, "{source}, preserve_parens={preserve_parens}"); + } + } + } + #[test] fn simple_arrow_no_side_effects_annotations() { for source in [ @@ -1315,11 +1352,16 @@ mod test { ("import x from 'foo'; 'use strict';", 2), ("export {x} from 'foo'; 'use strict';", 2), (";'use strict';", 2), + ("('use strict'); 'use strict';", 2), ]; - for (source, body_length) in sources { - let ret = Parser::new(&allocator, source, source_type).parse(); - assert!(ret.program.directives.is_empty(), "{source}"); - assert_eq!(ret.program.body.len(), body_length, "{source}"); + for preserve_parens in [true, false] { + for (source, body_length) in sources { + let ret = Parser::new(&allocator, source, source_type) + .with_options(ParseOptions { preserve_parens, ..ParseOptions::default() }) + .parse(); + assert!(ret.program.directives.is_empty(), "{source}"); + assert_eq!(ret.program.body.len(), body_length, "{source}"); + } } } @@ -1506,21 +1548,26 @@ mod test { let zeroed_string = ZeroedString::new(); let source_text = zeroed_string.as_str(); - // Attempt to parse the source text let allocator = Allocator::default(); + + // Attempt to parse the source text as a program - parsing should fail let ret = Parser::new(&allocator, source_text, SourceType::default()).parse(); - // Parsing should fail assert!(ret.program.is_empty()); assert!(ret.fatal_error); assert_eq!(ret.diagnostics.len(), 1); - assert_eq!( - ret.diagnostics.first().unwrap().to_string(), - "Source length exceeds 4 GiB limit" - ); + assert_eq!(ret.diagnostics.first().unwrap().to_string(), MAX_LEN_ERROR); + + // Attempt to parse the source text as an expression - parsing should fail + let ret = Parser::new(&allocator, source_text, SourceType::default()).parse_expression(); + + assert!(ret.is_err()); + let diagnostics = ret.err().unwrap(); + assert_eq!(diagnostics.len(), 1); + assert_eq!(diagnostics.first().unwrap().to_string(), MAX_LEN_ERROR); } - // Source with length MAX_LEN parses OK. + // Source with length `MAX_LEN` parses OK. // This test takes over 1 minute on an M1 Macbook Pro unless compiled in release mode. // `not(debug_assertions)` is a proxy for detecting release mode. // Also skip running under Miri since it takes so long. @@ -1529,18 +1576,26 @@ mod test { #[test] fn legal_length_source() { // Build a string MAX_LEN bytes long which doesn't take too long to parse - let head = "const x = 1;\n/*"; - let foot = "*/\nconst y = 2;\n"; + let head = "x(/*"; + let foot = "*/)"; let mut source = "x".repeat(MAX_LEN); source.replace_range(..head.len(), head); source.replace_range(MAX_LEN - foot.len().., foot); assert_eq!(source.len(), MAX_LEN); let allocator = Allocator::default(); + + // Parse as a program let ret = Parser::new(&allocator, &source, SourceType::default()).parse(); assert!(!ret.fatal_error); assert!(ret.diagnostics.is_empty()); - assert_eq!(ret.program.body.len(), 2); + assert_eq!(ret.program.body.len(), 1); + + // Parse as an expression + let ret = Parser::new(&allocator, &source, SourceType::default()).parse_expression(); + assert!(ret.is_ok()); + let expr = ret.ok().unwrap(); + assert!(matches!(expr, Expression::CallExpression(_))); } // Where the lexer cannot lex any further it emits `Undetermined`, and no `Eof` follows. diff --git a/vendor/oxc_parser/src/list.rs b/vendor/oxc_parser/src/list.rs new file mode 100644 index 000000000..b93a4c317 --- /dev/null +++ b/vendor/oxc_parser/src/list.rs @@ -0,0 +1,253 @@ +//! Combinators for parsing lists of syntax elements. + +use std::ops::ControlFlow; + +use oxc_allocator::{ArenaBox, ArenaVec}; +use oxc_ast::ast::BindingRestElement; +use oxc_span::{GetSpan, Span}; + +use crate::{ + ParserConfig as Config, ParserImpl, + diagnostics::{self, ParserDiagnostic}, + lexer::Kind, +}; + +impl<'a, C: Config> ParserImpl<'a, C> { + /// Collect a parser list with one exact allocation for up to four elements. + /// Small elements in longer lists use a separate buffer before spilling into the arena. + #[inline] + pub(crate) fn collect_list( + &mut self, + mut next: impl FnMut(&mut Self) -> Option, + ) -> ArenaVec<'a, T> { + let Some(first) = next(self) else { return ArenaVec::new_in(self) }; + let Some(second) = next(self) else { return ArenaVec::from_value_in(first, self) }; + let Some(third) = next(self) else { + return ArenaVec::from_array_in([first, second], self); + }; + let Some(fourth) = next(self) else { + return ArenaVec::from_array_in([first, second, third], self); + }; + let Some(fifth) = next(self) else { + return ArenaVec::from_array_in([first, second, third, fourth], self); + }; + let prefix = [first, second, third, fourth, fifth]; + if size_of::() <= 16 { + return self.collect_long_list(prefix, next); + } + let mut list = ArenaVec::with_capacity_in(8, self); + list.extend(prefix); + while let Some(element) = next(self) { + list.push(element); + } + list + } + + /// Buffer small list elements separately from the common short-list path so + /// recursive parsing only pays for this stack space when a list is longer. + #[inline(never)] + fn collect_long_list( + &mut self, + prefix: [T; 5], + mut next: impl FnMut(&mut Self) -> Option, + ) -> ArenaVec<'a, T> { + let mut tail: [Option; 11] = std::array::from_fn(|_| None); + for (index, slot) in tail.iter_mut().enumerate() { + let Some(element) = next(self) else { + let mut list = ArenaVec::with_capacity_in(5 + index, self); + list.extend(prefix); + list.extend(tail.into_iter().flatten()); + return list; + }; + *slot = Some(element); + } + let extra = next(self); + let mut list = ArenaVec::with_capacity_in(if extra.is_some() { 32 } else { 16 }, self); + list.extend(prefix); + list.extend(tail.into_iter().flatten()); + if let Some(extra) = extra { + list.push(extra); + while let Some(element) = next(self) { + list.push(element); + } + } + list + } + + pub(crate) fn parse_normal_list( + &mut self, + open: Kind, + close: Kind, + mut f: F, + ) -> ArenaVec<'a, T> + where + F: FnMut(&mut Self) -> T, + { + self.parse_normal_list_breakable(open, close, |p| Some(f(p))) + } + + pub(crate) fn parse_normal_list_breakable( + &mut self, + open: Kind, + close: Kind, + mut parse_element: F, + ) -> ArenaVec<'a, T> + where + F: FnMut(&mut Self) -> Option, + { + let opening_span = self.cur_token().span(); + self.expect(open); + let list = self.collect_list(|p| { + if p.at(close) || p.has_fatal_error() { None } else { parse_element(p) } + }); + self.expect_closing(close, opening_span); + list + } + + pub(crate) fn parse_delimited_list( + &mut self, + close: Kind, + separator: Kind, + opening_span: Span, + parse_element: F, + ) -> (ArenaVec<'a, T>, Option) + where + F: FnMut(&mut Self) -> T, + { + self.parse_delimited_list_with_prefix(None, close, separator, opening_span, parse_element) + } + + /// Include an already parsed prefix without consuming a separator for it. + pub(crate) fn parse_delimited_list_with_prefix( + &mut self, + mut first: Option, + close: Kind, + separator: Kind, + opening_span: Span, + mut parse_element: F, + ) -> (ArenaVec<'a, T>, Option) + where + F: FnMut(&mut Self) -> T, + { + let mut finished = self.at(close) || self.has_fatal_error(); + let mut trailing_separator = None; + let list = self.collect_list(|p| { + if let Some(first) = first.take() { + return Some(first); + } + if finished { + return None; + } + let element = parse_element(p); + if let ControlFlow::Break(trailing) = + p.parse_delimited_list_separator(close, separator, opening_span) + { + trailing_separator = trailing; + finished = true; + } + Some(element) + }); + (list, trailing_separator) + } + + #[inline] + fn parse_delimited_list_separator( + &mut self, + close: Kind, + separator: Kind, + opening_span: Span, + ) -> ControlFlow> { + let kind = self.cur_kind(); + if kind == close || self.has_fatal_error() { + return ControlFlow::Break(None); + } + if kind != separator { + self.set_fatal_error(diagnostics::expect_closing_or_separator( + close.to_str(), + separator.to_str(), + kind.to_str(), + self.cur_token().span(), + opening_span, + )); + return ControlFlow::Break(None); + } + self.advance(separator); + let kind = self.cur_kind(); + if kind == close { + let trailing_separator = self.prev_token_end - 1; + return ControlFlow::Break(Some(trailing_separator)); + } + if matches!(kind, Kind::Eof | Kind::Undetermined) { + return ControlFlow::Break(None); + } + ControlFlow::Continue(()) + } + + pub(crate) fn parse_delimited_list_with_rest( + &mut self, + close: Kind, + opening_span: Span, + parse_element: E, + parse_rest: R, + rest_last_diagnostic: D, + ) -> (ArenaVec<'a, A>, Option>>) + where + E: Fn(&mut Self) -> A, + R: Fn(&mut Self) -> ArenaBox<'a, BindingRestElement<'a>>, + D: Fn(Span) -> ParserDiagnostic<'a>, + { + let mut rest: Option>> = None; + let mut first = true; + let list = self.collect_list(|p| { + loop { + let kind = p.cur_kind(); + if kind == close || p.has_fatal_error() { + return None; + } + + if first { + first = false; + } else { + let comma_span = p.cur_token().span(); + if kind != Kind::Comma { + let error = diagnostics::expect_closing_or_separator( + close.to_str(), + Kind::Comma.to_str(), + kind.to_str(), + comma_span, + opening_span, + ); + p.set_fatal_error(error); + return None; + } + p.bump_any(); + let kind = p.cur_kind(); + if kind == close { + if rest.is_some() && !p.ctx.has_ambient() { + p.error(diagnostics::rest_element_trailing_comma(comma_span)); + } + return None; + } + if matches!(kind, Kind::Eof | Kind::Undetermined) { + return None; + } + } + + if let Some(r) = &rest { + p.set_fatal_error(rest_last_diagnostic(r.span())); + return None; + } + + // Re-capture kind to get the current token (may have changed after else branch) + let kind = p.cur_kind(); + if kind == Kind::Dot3 { + rest.replace(parse_rest(p)); + } else { + return Some(parse_element(p)); + } + } + }); + + (list, rest) + } +} diff --git a/vendor/oxc_parser/src/modifiers.rs b/vendor/oxc_parser/src/modifiers.rs index bcfa5cf59..7aac7eec4 100644 --- a/vendor/oxc_parser/src/modifiers.rs +++ b/vendor/oxc_parser/src/modifiers.rs @@ -493,32 +493,30 @@ pub use modifier_kinds::ModifierKinds; impl ParserImpl<'_, C> { pub(crate) fn eat_modifiers_before_declaration(&mut self) -> Modifiers { let mut modifiers = Modifiers::empty(); - while let Some(modifier_kind) = self.get_modifier() { - let modifier = Modifier::new(self.cur_start(), modifier_kind); - self.bump_any(); + while let Some(modifier) = self.eat_modifier_before_declaration() { self.check_modifier(modifiers.kinds(), modifier); modifiers.add(modifier.kind, modifier.start); } modifiers } - fn get_modifier(&mut self) -> Option { + fn eat_modifier_before_declaration(&mut self) -> Option { let cur_kind = self.cur_kind(); let modifier_kind = ModifierKind::try_from(cur_kind).ok()?; - // Peek the token after the modifier keyword to decide whether the keyword really is a - // modifier (e.g. distinguish `static x` from `static` used as an identifier). - // `peek_token` performs a single lexer-level re-lex, avoiding the heavier parser-level - // `lookahead` (checkpoint + `bump_any` + rewind) that this previously used. - let next = self.lexer.peek_token(); - let next_kind = next.kind(); - let is_modifier = match cur_kind { - Kind::Const => next_kind == Kind::Enum, - // These modifiers can cross line. - Kind::Accessor | Kind::Static => Self::can_follow_modifier(next_kind), - // Rest modifiers cannot cross line - _ => Self::can_follow_modifier(next_kind) && !next.is_on_new_line(), - }; - if is_modifier { Some(modifier_kind) } else { None } + let start = self.cur_start(); + // The token after the keyword decides whether the keyword really is a modifier + // (e.g. distinguish `static x` from `static` used as an identifier). + let is_modifier = self.eat_if_next(|next| { + let next_kind = next.kind(); + match cur_kind { + Kind::Const => next_kind == Kind::Enum, + // These modifiers can cross line. + Kind::Accessor | Kind::Static => Self::can_follow_modifier(next_kind), + // Rest modifiers cannot cross line + _ => Self::can_follow_modifier(next_kind) && !next.is_on_new_line(), + } + }); + if is_modifier { Some(Modifier::new(start, modifier_kind)) } else { None } } fn modifier(&mut self, kind: Kind, start: u32) -> Modifier { @@ -583,25 +581,24 @@ impl ParserImpl<'_, C> { // We need to ensure that any subsequent modifiers appear on the same line // so that when 'const' is a standalone declaration, we don't issue // an error. - if !self.next_token_is_on_same_line_and_can_follow_modifier() { + if !self.eat_if_next(|next| { + !next.is_on_new_line() && Self::can_follow_modifier(next.kind()) + }) { return None; } - self.bump_any(); } else if kind == Kind::Static { // ClassStaticBlock : `static { ClassStaticBlockBody }` e.g. `static { x = 1; }` // member named `static` e.g. `static() {}`, `static = 1`, `static;` // repeated `static` e.g. `static static x` - // - // Peek once and reuse it — `peek_token` is not cached, so checking `== LCurly` separately - // from the peek inside `next_token_can_follow_modifier` re-lexed this token twice. - let next_kind = self.lexer.peek_token().kind(); - if (stop_on_start_of_class_static_block && next_kind == Kind::LCurly) - || seen_modifier_kinds.contains(ModifierKind::Static) - || !Self::can_follow_modifier(next_kind) + if seen_modifier_kinds.contains(ModifierKind::Static) + || !self.eat_if_next(|next| { + let next_kind = next.kind(); + !(stop_on_start_of_class_static_block && next_kind == Kind::LCurly) + && Self::can_follow_modifier(next_kind) + }) { return None; } - self.bump_any(); } else if !self.parse_any_contextual_modifier() { // next token is not a modifier return None; @@ -610,47 +607,27 @@ impl ParserImpl<'_, C> { } pub(crate) fn parse_contextual_modifier(&mut self, kind: Kind) -> bool { - if self.at(kind) && !self.cur_token().escaped() && self.next_token_can_follow_modifier() { - self.bump_any(); - true - } else { - false - } + self.at(kind) && !self.cur_token().escaped() && self.eat_if_next_can_follow_modifier() } fn parse_any_contextual_modifier(&mut self) -> bool { - if self.cur_kind().is_modifier_kind() && self.next_token_can_follow_modifier() { - self.bump_any(); - true - } else { - false - } + self.cur_kind().is_modifier_kind() && self.eat_if_next_can_follow_modifier() } - /// Returns `true` if the token following the current (modifier) token can follow a modifier, - /// i.e. the current token really is a modifier rather than an identifier/expression. - /// - /// Inspects the single peeked next token via `peek_token` (one lexer-level re-lex) instead of - /// the heavier parser-level `lookahead` (checkpoint + `bump_any` + rewind). The result is - /// identical: the speculative `bump_any` in the old form could push an escaped-keyword error, - /// but `lookahead`'s rewind always discarded it, and the real error still fires on the - /// non-speculative bump performed by the caller once this returns `true`. - pub(crate) fn next_token_can_follow_modifier(&mut self) -> bool { + /// Consume the current keyword if the token after it shows that the keyword is a modifier + /// rather than a name: `readonly x` but not `readonly: T`, `get x() {}` but not `get() {}`. + fn eat_if_next_can_follow_modifier(&mut self) -> bool { let cur_kind = self.cur_kind(); - let next = self.lexer.peek_token(); - let next_kind = next.kind(); - match cur_kind { - Kind::Const => next_kind == Kind::Enum, - Kind::Static => Self::can_follow_modifier(next_kind), - Kind::Get | Kind::Set => Self::can_follow_get_or_set_keyword(next_kind), - // Other modifiers cannot cross a line. - _ => !next.is_on_new_line() && Self::can_follow_modifier(next_kind), - } - } - - fn next_token_is_on_same_line_and_can_follow_modifier(&mut self) -> bool { - let next = self.lexer.peek_token(); - !next.is_on_new_line() && Self::can_follow_modifier(next.kind()) + self.eat_if_next(|next| { + let next_kind = next.kind(); + match cur_kind { + Kind::Const => next_kind == Kind::Enum, + Kind::Static => Self::can_follow_modifier(next_kind), + Kind::Get | Kind::Set => Self::can_follow_get_or_set_keyword(next_kind), + // Other modifiers cannot cross a line. + _ => !next.is_on_new_line() && Self::can_follow_modifier(next_kind), + } + }) } fn can_follow_modifier(kind: Kind) -> bool { @@ -731,9 +708,11 @@ const fn get_illegal_preceding_modifiers(kind: ModifierKind) -> ModifierKinds { ModifierKind::Abstract, ModifierKind::Async, ]), - ModifierKind::Declare => { - ModifierKinds::new([ModifierKind::Declare, ModifierKind::Override]) - } + ModifierKind::Declare => ModifierKinds::new([ + ModifierKind::Declare, + ModifierKind::Override, + ModifierKind::Abstract, + ]), _ => ModifierKinds::new([kind]), } } diff --git a/vendor/oxc_parser/src/module_record.rs b/vendor/oxc_parser/src/module_record.rs index 15f5417d8..a6660743e 100644 --- a/vendor/oxc_parser/src/module_record.rs +++ b/vendor/oxc_parser/src/module_record.rs @@ -1,5 +1,6 @@ use oxc_allocator::{Allocator, ArenaVec}; use oxc_ast::ast::*; +use oxc_data_structures::buffered_vec::BufferedVec; use oxc_diagnostics::OxcDiagnostic; use oxc_ecmascript::BoundNames; use oxc_span::{GetSpan, Span}; @@ -11,7 +12,10 @@ pub struct ModuleRecordBuilder<'a> { allocator: &'a Allocator, source_type: SourceType, module_record: ModuleRecord<'a>, - export_entries: ArenaVec<'a, ExportEntry<'a>>, + import_entries: BufferedVec>, 4>, + dynamic_imports: BufferedVec, 4>, + import_metas: BufferedVec, 4>, + export_entries: BufferedVec>, 4>, exported_bindings_duplicated: ArenaVec<'a, NameSpan<'a>>, /// `default` exports of declarations skipped because their module request is not UTF-8. /// They still count towards the duplicate default export check. @@ -24,18 +28,41 @@ impl<'a> ModuleRecordBuilder<'a> { allocator, source_type, module_record: ModuleRecord::new(allocator), - export_entries: ArenaVec::new_in(&allocator), + import_entries: BufferedVec::new(ArenaVec::new_in(&allocator)), + dynamic_imports: BufferedVec::new(ArenaVec::new_in(&allocator)), + import_metas: BufferedVec::new(ArenaVec::new_in(&allocator)), + export_entries: BufferedVec::new(ArenaVec::new_in(&allocator)), exported_bindings_duplicated: ArenaVec::new_in(&allocator), skipped_default_exports: ArenaVec::new_in(&allocator), } } - pub fn build(mut self) -> (ModuleRecord<'a>, Vec) { + pub fn build(self) -> (ModuleRecord<'a>, Vec) { + let Self { + allocator, + source_type, + mut module_record, + import_entries, + dynamic_imports, + import_metas, + export_entries, + exported_bindings_duplicated, + skipped_default_exports, + } = self; + // The `ParseModule` algorithm requires `importedBoundNames` (import entries) to be // resolved before resolving export entries. - self.resolve_export_entries(); - let errors = self.errors(); - (self.module_record, errors) + module_record.import_entries = import_entries.into_vec(); + Self::resolve_export_entries(allocator, &mut module_record, export_entries.into_vec()); + let errors = Self::errors( + source_type, + &module_record, + &exported_bindings_duplicated, + &skipped_default_exports, + ); + module_record.dynamic_imports = dynamic_imports.into_vec(); + module_record.import_metas = import_metas.into_vec(); + (module_record, errors) } /// Returns true if the file contains module syntax (import/export declarations or import.meta). @@ -43,15 +70,18 @@ impl<'a> ModuleRecordBuilder<'a> { self.module_record.has_module_syntax } - pub fn errors(&self) -> Vec { + fn errors( + source_type: SourceType, + module_record: &ModuleRecord<'a>, + exported_bindings_duplicated: &[NameSpan<'a>], + skipped_default_exports: &[Span], + ) -> Vec { let mut errors = vec![]; - let module_record = &self.module_record; - // Skip checking for exports in TypeScript - if !self.source_type.is_typescript() { + if !source_type.is_typescript() { // It is a Syntax Error if the ExportedNames of ModuleItemList contains any duplicate entries. - for name_span in &self.exported_bindings_duplicated { + for name_span in exported_bindings_duplicated { let old_span = module_record.exported_bindings[&name_span.name]; errors.push(diagnostics::duplicate_export( &name_span.name, @@ -73,7 +103,7 @@ impl<'a> ModuleRecordBuilder<'a> { .iter() .filter_map(|export_entry| export_entry.export_name.default_export_span()), ) - .chain(self.skipped_default_exports.iter().copied()); + .chain(skipped_default_exports.iter().copied()); if default_exports.clone().count() > 1 { errors.push(diagnostics::duplicate_default_export(default_exports.collect())); } @@ -91,25 +121,13 @@ impl<'a> ModuleRecordBuilder<'a> { } fn add_import_entry(&mut self, entry: ImportEntry<'a>) { - self.module_record.import_entries.push(entry); + self.import_entries.push(entry); } fn add_export_entry(&mut self, entry: ExportEntry<'a>) { self.export_entries.push(entry); } - fn append_local_export_entry(&mut self, entry: ExportEntry<'a>) { - self.module_record.local_export_entries.push(entry); - } - - fn append_indirect_export_entry(&mut self, entry: ExportEntry<'a>) { - self.module_record.indirect_export_entries.push(entry); - } - - fn append_star_export_entry(&mut self, entry: ExportEntry<'a>) { - self.module_record.star_export_entries.push(entry); - } - fn add_export_binding(&mut self, name: Str<'a>, span: Span) { if let Some(old_node) = self.module_record.exported_bindings.insert(name, span) { self.exported_bindings_duplicated.push(NameSpan::new(name, old_node)); @@ -118,87 +136,88 @@ impl<'a> ModuleRecordBuilder<'a> { /// [ParseModule](https://tc39.es/ecma262/#sec-parsemodule) /// Step 10. - fn resolve_export_entries(&mut self) { - // let export_entries = self.export_entries.drain(..).collect::>(); - let export_entries = - std::mem::replace(&mut self.export_entries, ArenaVec::new_in(&self.allocator)); + fn resolve_export_entries( + allocator: &'a Allocator, + module_record: &mut ModuleRecord<'a>, + mut export_entries: ArenaVec<'a, ExportEntry<'a>>, + ) { + if let Some(first) = export_entries.first() { + let is_star = first.import_name.is_all_but_default(); + if export_entries.iter().all(|entry| { + entry.module_request.is_some() && entry.import_name.is_all_but_default() == is_star + }) { + // Reuse the original buffer when every export has the same non-local destination. + if is_star { + debug_assert!(export_entries.iter().all(|entry| entry.export_name.is_null())); + module_record.star_export_entries = export_entries; + } else { + module_record.indirect_export_entries = export_entries; + } + return; + } + } + + // Retain local exports in their original buffer, avoiding a second arena allocation. // 10. For each ExportEntry Record ee of exportEntries, do - for ee in export_entries { + export_entries.retain_mut(|entry| { // a. If ee.[[ModuleRequest]] is null, then - if ee.module_request.is_none() { - let found_import_entry = match &ee.local_name { - ExportLocalName::Name(name) => self - .module_record - .import_entries - .iter() - .find(|entry| entry.local_name.name == name.name), - _ => None, + if entry.module_request.is_none() { + let ExportLocalName::Name(local_name) = &entry.local_name else { + // i. If ee.[[LocalName]] is not an element of importedBoundNames, then + // 1. Append ee to localExportEntries. + return true; }; - match found_import_entry { + let Some(import) = module_record + .import_entries + .iter() + .find(|import| import.local_name.name == local_name.name) + else { // i. If ee.[[LocalName]] is not an element of importedBoundNames, then - None => { - // 1. Append ee to localExportEntries. - self.append_local_export_entry(ee); - } - // ii. Else, - // 1. Let ie be the element of importEntries whose [[LocalName]] is the same as ee.[[LocalName]]. - Some(ie) => { - match &ie.import_name { - // 2. If ie.[[ImportName]] is namespace-object, then - ImportImportName::NamespaceObject => { - // a. NOTE: This is a re-export of an imported module namespace object. - // b. Append ee to localExportEntries. - self.append_local_export_entry(ee); - } - // 3. Else, - // a. NOTE: This is a re-export of a single name. - // Append the ExportEntry Record { [[ModuleRequest]]: ie.[[ModuleRequest]], [[ImportName]]: ie.[[ImportName]], [[LocalName]]: null, [[ExportName]]: ee.[[ExportName]] } - // to indirectExportEntries. - ImportImportName::Name(_) | ImportImportName::Default(_) => { - let export_entry = ExportEntry { - statement_span: ie.statement_span, - span: ee.span, - module_request: Some(ie.module_request.clone()), - import_name: match &ie.import_name { - ImportImportName::Name(name) => { - ExportImportName::Name(name.clone()) - } - ImportImportName::Default(span) => ExportImportName::Name( - NameSpan::new("default".into(), *span), - ), - ImportImportName::NamespaceObject => unreachable!(), - }, - export_name: ee.export_name.clone(), - local_name: ExportLocalName::default(), - is_type: ie.is_type, - }; - self.append_indirect_export_entry(export_entry); - } - } - } - } - // b. Else if ee.[[ImportName]] is all-but-default, then - } else if ee.import_name.is_all_but_default() { + // 1. Append ee to localExportEntries. + return true; + }; + // ii. Else, + // 1. Let ie be the element of importEntries whose [[LocalName]] is the same as ee.[[LocalName]]. + let import_name = match &import.import_name { + ImportImportName::Name(name) => ExportImportName::Name(name.clone()), + ImportImportName::Default(span) => ExportImportName::Name(NameSpan::new( + allocator.alloc_str("default").into(), + *span, + )), + // ParseModule 10.a.ii.3: normalize to `export * as name from 'mod'`. + ImportImportName::NamespaceObject => ExportImportName::All, + }; + // Append the ExportEntry Record { [[ModuleRequest]]: ie.[[ModuleRequest]], [[ImportName]]: ie.[[ImportName]], [[LocalName]]: null, [[ExportName]]: ee.[[ExportName]] } + // to indirectExportEntries. + entry.statement_span = import.statement_span; + entry.module_request = Some(import.module_request.clone()); + entry.import_name = import_name; + entry.local_name = ExportLocalName::default(); + entry.is_type |= import.is_type; + } + + // b. Else if ee.[[ImportName]] is all-but-default, then + if entry.import_name.is_all_but_default() { // i. Assert: ee.[[ExportName]] is null. - debug_assert!(ee.export_name.is_null()); - self.append_star_export_entry(ee); - // c. Else, + debug_assert!(entry.export_name.is_null()); + module_record.star_export_entries.push(std::mem::take(entry)); } else { + // c. Else, // i. Append ee to indirectExportEntries. - self.append_indirect_export_entry(ee); + module_record.indirect_export_entries.push(std::mem::take(entry)); } - } + false + }); + module_record.local_export_entries = export_entries; } pub fn visit_import_expression(&mut self, e: &ImportExpression<'a>) { - self.module_record - .dynamic_imports - .push(DynamicImport { span: e.span, module_request: e.source.span() }); + self.dynamic_imports.push(DynamicImport { span: e.span, module_request: e.source.span() }); } pub fn visit_import_meta(&mut self, span: Span) { self.module_record.has_module_syntax = true; - self.module_record.import_metas.push(span); + self.import_metas.push(span); } pub fn visit_import_declaration(&mut self, decl: &ImportDeclaration<'a>) { @@ -208,6 +227,7 @@ impl<'a> ModuleRecordBuilder<'a> { let module_request = NameSpan::new(source.into(), decl.source.span); if let Some(specifiers) = &decl.specifiers { + self.import_entries.reserve(specifiers.len()); for specifier in specifiers { let local = specifier.local(); let local_name = NameSpan::new(local.name.into(), local.span); @@ -345,6 +365,7 @@ impl<'a> ModuleRecordBuilder<'a> { } pub fn visit_export_named_declaration(&mut self, decl: &ExportNamedDeclaration<'a>) { + self.export_entries.reserve(decl.specifiers.len()); for specifier in &decl.specifiers { let export_name = ExportExportName::Name(NameSpan::new( specifier.exported.name(), @@ -396,6 +417,7 @@ impl<'a> ModuleRecordBuilder<'a> { }, ); + self.export_entries.reserve(decl.specifiers.len()); for specifier in &decl.specifiers { let export_name = ExportExportName::Name(NameSpan::new( specifier.exported.name(), @@ -421,6 +443,11 @@ impl<'a> ModuleRecordBuilder<'a> { pub fn set_module_syntax(&mut self) { self.module_record.has_module_syntax = true; } + + /// Forget module syntax that only a discarded parse has seen. + pub fn unset_module_syntax(&mut self) { + self.module_record.has_module_syntax = false; + } } fn iter_binding_identifiers_of_declaration<'a, F>(decl: &Declaration<'a>, f: &mut F) @@ -736,6 +763,56 @@ mod module_record_tests { } } + #[test] + fn reexported_import_preserves_type_only_flags() { + let allocator = Allocator::default(); + for (source, is_type) in [ + ("import { T } from 'mod'; export { T };", false), + ("import { T } from 'mod'; export type { T };", true), + ("import { T } from 'mod'; export { type T };", true), + ("import type { T } from 'mod'; export { T };", true), + ("import { type T } from 'mod'; export { T };", true), + ("import type { T } from 'mod'; export type { T };", true), + ("import T from 'mod'; export type { T as default };", true), + ] { + let record = build(&allocator, source); + assert!(record.local_export_entries.is_empty(), "{source}"); + assert_eq!(record.indirect_export_entries.len(), 1, "{source}"); + assert_eq!(record.indirect_export_entries[0].is_type, is_type, "{source}"); + } + } + + #[test] + fn reexported_namespace_is_indirect() { + let allocator = Allocator::default(); + for (source, exported, is_type) in [ + ("import * as ns from 'mod'; export { ns };", "ns", false), + ("export { ns as renamed }; import * as ns from 'mod';", "renamed", false), + ("import * as ns from 'mod'; export { ns as default };", "default", false), + ("import * as ns from 'mod'; export type { ns };", "ns", true), + ("import * as ns from 'mod'; export { type ns };", "ns", true), + ("import type * as ns from 'mod'; export { ns };", "ns", true), + ] { + let record = build(&allocator, source); + assert!(record.local_export_entries.is_empty(), "{source}"); + assert_eq!(record.indirect_export_entries.len(), 1, "{source}"); + let import = &record.import_entries[0]; + let entry = &record.indirect_export_entries[0]; + assert_eq!(entry.statement_span, import.statement_span); + assert_eq!(entry.module_request.as_ref(), Some(&import.module_request)); + assert_eq!(entry.import_name, ExportImportName::All); + assert_eq!(entry.local_name, ExportLocalName::Null); + let ExportExportName::Name(name) = &entry.export_name else { panic!() }; + assert_eq!(name.name, exported); + assert_eq!(entry.is_type, is_type); + } + + // A default export expression creates a local binding, unlike `export { ns as default }`. + let record = build(&allocator, "import * as ns from 'mod'; export default ns;"); + assert_eq!(record.local_export_entries.len(), 1); + assert!(record.indirect_export_entries.is_empty()); + } + #[test] fn indirect_export_entries() { let allocator = Allocator::default(); @@ -768,6 +845,53 @@ mod module_record_tests { ); } + #[test] + fn mixed_export_entries_preserve_source_order() { + let allocator = Allocator::default(); + let source = " + export const first = 1; + export * from 'star1'; + export { imported as indirect1 }; + export const second = 2; + export { value as indirect2 } from 'other'; + export * from 'star2'; + export { ns }; + export const third = 3; + import { imported } from 'mod'; + import * as ns from 'namespace'; + "; + let ret = Parser::new(&allocator, source, SourceType::mjs()).parse(); + assert!(ret.diagnostics.is_empty()); + let module_record = ret.module_record; + assert_eq!( + module_record + .local_export_entries + .iter() + .map(|entry| entry.local_name.name().unwrap()) + .collect::>(), + ["first", "second", "third"] + ); + assert_eq!( + module_record + .indirect_export_entries + .iter() + .map(|entry| { + let ExportExportName::Name(name) = &entry.export_name else { panic!() }; + name.name + }) + .collect::>(), + ["indirect1", "indirect2", "ns"] + ); + assert_eq!( + module_record + .star_export_entries + .iter() + .map(|entry| entry.module_request.as_ref().unwrap().name) + .collect::>(), + ["star1", "star2"] + ); + } + #[test] fn import_meta() { let allocator = Allocator::default(); diff --git a/vendor/oxc_parser/src/state.rs b/vendor/oxc_parser/src/state.rs index 10bb8f120..d782a7ce8 100644 --- a/vendor/oxc_parser/src/state.rs +++ b/vendor/oxc_parser/src/state.rs @@ -1,9 +1,10 @@ use rustc_hash::{FxHashMap, FxHashSet}; +use oxc_allocator::{Allocator, ArenaVec}; use oxc_ast::ast::Expression; use oxc_span::Span; -use crate::cursor::ParserCheckpoint; +use crate::{cursor::ParserCheckpoint, js::CoverElement, ts::TypeArgumentLookahead}; /// The initializer and diagnostic span of a shorthand property awaiting cover validation. pub struct CoverInitializedName<'a> { @@ -12,8 +13,42 @@ pub struct CoverInitializedName<'a> { } pub struct ParserState<'a> { + /// Positions of `(` tokens whose `( … ) : Type =>` continuation was rejected as an arrow + /// function, so that enclosing speculation does not try the same return type twice. pub not_parenthesized_arrow: FxHashSet, + /// Elements of the `CoverParenthesizedExpressionAndArrowParameterList`s being parsed. + /// + /// A stack shared by nested cover lists: each list owns the elements above the length it + /// recorded when it started, and removes them once the token after `)` decides whether + /// they are arrow function parameters or a parenthesized expression. + /// + /// Kept in the arena, like `cover_parenthesized`, so that parsing a small file does not + /// pay for heap allocations. + pub cover_elements: ArenaVec<'a, CoverElement<'a>>, + + /// Whether an identifier named `await` was checked where `await` is not reserved. + /// Tells whether the arguments of `async(…)` have to be parsed again as parameters. + pub mentions_await: bool, + + /// Number of cover lists whose elements are currently being parsed. + pub cover_depth: u32, + + /// Start offsets of the expressions directly inside parentheses that were parsed while an + /// enclosing cover list was still undecided, in source order. + /// + /// `([(a)]) => 0` and `([(a) = 1]) => 0` are Syntax Errors, but the parentheses do not + /// survive in the AST: `ParenthesizedExpression` is omitted without `preserve_parens`, + /// and assignment targets never keep it. + /// Like `cover_elements`, each cover list owns the entries above its recorded length. + pub cover_parenthesized: ArenaVec<'a, u32>, + + /// Zero outside speculative expression type arguments; otherwise their nesting depth. + pub type_argument_depth: u32, + + /// Allocated only after nested speculation fails or needs delimiter lookahead. + pub type_argument_lookahead: Option>, + /// Temporary storage for `CoverInitializedName` `({ foo = bar })`. /// Keyed by `ObjectProperty`'s span.start. pub cover_initialized_name: FxHashMap>, @@ -38,10 +73,16 @@ pub struct ParserState<'a> { pub encountered_await_identifier: bool, } -impl ParserState<'_> { - pub fn new() -> Self { +impl<'a> ParserState<'a> { + pub fn new(allocator: &'a Allocator) -> Self { Self { not_parenthesized_arrow: FxHashSet::default(), + cover_elements: ArenaVec::new_in(&allocator), + mentions_await: false, + cover_depth: 0, + cover_parenthesized: ArenaVec::new_in(&allocator), + type_argument_depth: 0, + type_argument_lookahead: None, cover_initialized_name: FxHashMap::default(), trailing_commas: FxHashMap::default(), potential_await_reparse: Vec::new(), diff --git a/vendor/oxc_parser/src/ts/mod.rs b/vendor/oxc_parser/src/ts/mod.rs index 93468556d..4edf34668 100644 --- a/vendor/oxc_parser/src/ts/mod.rs +++ b/vendor/oxc_parser/src/ts/mod.rs @@ -1,2 +1,5 @@ mod statement; +mod type_arguments; mod types; + +pub use type_arguments::TypeArgumentLookahead; diff --git a/vendor/oxc_parser/src/ts/statement.rs b/vendor/oxc_parser/src/ts/statement.rs index 8ab2d3281..62d6658df 100644 --- a/vendor/oxc_parser/src/ts/statement.rs +++ b/vendor/oxc_parser/src/ts/statement.rs @@ -1,5 +1,6 @@ use oxc_allocator::{ArenaBox, ArenaVec}; use oxc_ast::ast::*; +use oxc_data_structures::buffered_vec::BufferedVec; use oxc_span::{FileExtension, GetSpan, SPAN}; use crate::{ @@ -236,7 +237,8 @@ impl<'a, C: Config> ParserImpl<'a, C> { } } } - let (extends, implements) = self.parse_ts_interface_heritage_clause(); + let (extends, implements) = + self.parse_heritage_clause(Self::parse_ts_interface_extends_clause); let body = self.parse_ts_interface_body(); let extends = extends.unwrap_or_else(|| ArenaVec::new_in(self)); self.verify_modifiers( @@ -262,24 +264,14 @@ impl<'a, C: Config> ParserImpl<'a, C> { ) } - #[expect(clippy::type_complexity)] - fn parse_ts_interface_heritage_clause( - &mut self, - ) -> ( - Option>>, - Option<(Span, ArenaVec<'a, TSClassImplements<'a>>)>, - ) { - self.parse_heritage_clause(Self::parse_ts_interface_extends_clause) - } - fn parse_ts_interface_extends_clause(&mut self) -> ArenaVec<'a, TSInterfaceHeritage<'a>> { let extends_span = self.cur_token().span(); self.bump_any(); // bump `extends` - let mut extends = ArenaVec::with_capacity_in(1, self); + let mut extends = BufferedVec::<_, 1>::new(ArenaVec::new_in(self)); if self.at(Kind::LCurly) { self.error(diagnostics::empty_extends_clause(extends_span)); - return extends; + return extends.into_vec(); } loop { let start = self.cur_start(); @@ -325,7 +317,7 @@ impl<'a, C: Config> ParserImpl<'a, C> { } } - extends + extends.into_vec() } fn parse_ts_interface_heritage_type_name(&mut self, start: u32) -> TSTypeName<'a> { @@ -465,7 +457,8 @@ impl<'a, C: Config> ParserImpl<'a, C> { } let body = if self.at(Kind::LCurly) { // External module body (`declare module "x" {}`); `import`/`export` are allowed here. - Some(self.parse_ts_module_block(/* in_ts_namespace_body */ false)) + let block = self.parse_ts_module_block(/* in_ts_namespace_body */ false); + Some(self.alloc(block)) } else { self.asi(); None @@ -536,10 +529,7 @@ impl<'a, C: Config> ParserImpl<'a, C> { } } - fn parse_ts_module_block( - &mut self, - in_ts_namespace_body: bool, - ) -> ArenaBox<'a, TSModuleBlock<'a>> { + fn parse_ts_module_block(&mut self, in_ts_namespace_body: bool) -> TSModuleBlock<'a> { let start = self.cur_start(); self.expect(Kind::LCurly); // Remove TopLevel context for module block @@ -547,7 +537,7 @@ impl<'a, C: Config> ParserImpl<'a, C> { p.parse_directives_and_statements(in_ts_namespace_body) }); self.expect(Kind::RCurly); - TSModuleBlock::boxed(self.end_span(start), directives, statements, self) + TSModuleBlock::new(self.end_span(start), directives, statements, self) } fn parse_module_or_namespace_declaration( @@ -565,7 +555,7 @@ impl<'a, C: Config> ParserImpl<'a, C> { // Internal namespace body — validate each statement inline as it is parsed // (see `check_namespace_body_statement`), avoiding a second pass over the body. let block = self.parse_ts_module_block(/* in_ts_namespace_body */ true); - TSNamespaceDeclarationBody::TSModuleBlock(block) + TSNamespaceDeclarationBody::TSModuleBlock(self.alloc(block)) }; self.verify_modifiers( modifiers, @@ -592,7 +582,7 @@ impl<'a, C: Config> ParserImpl<'a, C> { self.expect(Kind::Global); let keyword_span = self.end_span(keyword_start); - let body = self.parse_ts_module_block(/* in_ts_namespace_body */ false).unbox(); + let body = self.parse_ts_module_block(/* in_ts_namespace_body */ false); self.verify_modifiers( modifiers, @@ -803,6 +793,10 @@ impl<'a, C: Config> ParserImpl<'a, C> { self.expect(Kind::LParen); let expression = self.parse_literal_string(); self.expect(Kind::RParen); + // `import x = require("x")` makes a TypeScript source a module, like `export =`. + if self.ctx.has_top_level() { + self.module_record_builder.set_module_syntax(); + } TSModuleReference::new_external_module_reference( self.end_span(reference_start), expression, diff --git a/vendor/oxc_parser/src/ts/type_arguments.rs b/vendor/oxc_parser/src/ts/type_arguments.rs new file mode 100644 index 000000000..02ad1c61e --- /dev/null +++ b/vendor/oxc_parser/src/ts/type_arguments.rs @@ -0,0 +1,236 @@ +//! Bound repeated parsing of nested speculative type arguments. +//! +//! A comparison list such as `[a < b, a < b, ...]` can look like nested generic types. +//! Cache delimiter proofs so rewinding does not repeatedly parse the same unclosed suffix. +//! Regexes, templates and JSX can make lookahead inconclusive; cache actual parse failures +//! with their grammar context to avoid retrying those paths as well. Both caches are lazy, +//! keeping ordinary shallow type arguments on the existing parser path. +//! +//! The relevant TypeScript list has the shape `< Type (',' Type)* ','? >`. A type can +//! itself contain type arguments, generic function parameters, tuples, object members, +//! conditional types, and expressions in computed property names. Commas, whitespace, +//! and line breaks within the list therefore cannot prove that speculation must fail. +//! The grammar parser also handles diagnostics such as an empty `<>`; this scan does not. +//! +//! This is a necessary-delimiter check: `false` proves that an opening `<` cannot close +//! before its containing construct ends; `true` only means to try the grammar parser. +//! In particular, counting angles cannot distinguish nested generics from the relational +//! operators in `a < b > c`. Expression type arguments additionally need a suitable +//! following token, and can form a standalone instantiation expression such as `f`. +//! Requiring a call's `(` would reject that syntax. +//! +//! References: [ECMAScript relational operators], TypeScript's [type-argument parsing] +//! and [instantiation expressions]. Delimiter rejection below is an optimization inferred +//! from those rules; lexical or grammatical uncertainty must remain inconclusive. +//! +//! [ECMAScript relational operators]: https://tc39.es/ecma262/#sec-relational-operators +//! [type-argument parsing]: https://github.com/microsoft/TypeScript/blob/v5.9.3/src/compiler/parser.ts#L6459-L6503 +//! [instantiation expressions]: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-4-7.html#instantiation-expressions + +use rustc_hash::{FxHashMap, FxHashSet}; + +use crate::{Context, ParserConfig as Config, ParserImpl, lexer::Kind}; + +/// Let ordinary generics parse without an extra scan, but bound the recursive prefix +/// before checking whether deeper speculation can actually close. +/// This is a performance threshold, not a grammar limit on valid nesting. +pub(super) const TYPE_ARGUMENT_LOOKAHEAD_DEPTH: u32 = 128; + +/// Failed nested speculation can repeat even without deep native-stack recursion. +const FAILURE_CACHE_DEPTH: u32 = 4; + +#[derive(Clone, Copy, PartialEq, Eq)] +pub(super) enum TypeArgumentFailure { + /// The list itself failed under the recorded context, regardless of its use site. + Type, + /// Expression speculation failed, possibly only because of the token after `>`. + Expression, +} + +#[derive(Default)] +pub struct TypeArgumentLookahead { + /// Do not repeat lookahead before this frontier. Absence of a delimiter rejection + /// is inconclusive; the grammar still decides whether a candidate parses. + /// Store the last token's start, not its end: a token that stopped the scan may + /// need a different lexical goal, so its contents have not been examined safely. + scanned_until: u32, + /// Delimiter proofs are independent of grammar context. + unclosed: FxHashSet, + /// A failed type list also rules out expression type arguments, but an expression's + /// follow-token check does not rule out a list in a type. Source type and options are + /// fixed for this parser; grammar flags can change when the same position is revisited. + /// For example, `DisallowConditionalTypes` changes whether `extends` starts a + /// conditional type; expression-bearing types can also depend on `In`/`Yield`/`Await`. + failed: FxHashMap<(u32, Context), TypeArgumentFailure>, +} + +impl TypeArgumentLookahead { + pub(crate) fn cannot_close(&self, start: u32) -> bool { + self.unclosed.contains(&start) + } + + pub(super) fn has_failed( + &self, + start: u32, + context: Context, + rule: TypeArgumentFailure, + ) -> bool { + self.failed + .get(&(start, context)) + .is_some_and(|&failure| failure == TypeArgumentFailure::Type || failure == rule) + } + + pub(super) fn record_failure( + &mut self, + start: u32, + context: Context, + rule: TypeArgumentFailure, + ) { + if rule == TypeArgumentFailure::Type { + // A list failure is stronger than rejection by the expression follow-token rule. + self.failed.insert((start, context), rule); + } else { + self.failed.entry((start, context)).or_insert(rule); + } + } +} + +impl ParserImpl<'_, C> { + pub(super) fn record_type_argument_failure( + &mut self, + start: u32, + context: Context, + rule: TypeArgumentFailure, + depth: u32, + ) { + let cache = if depth >= FAILURE_CACHE_DEPTH { + self.state.type_argument_lookahead.get_or_insert_with(Box::default) + } else if let Some(cache) = &mut self.state.type_argument_lookahead { + cache + } else { + return; + }; + cache.record_failure(start, context, rule); + } + + pub(super) fn speculative_type_arguments_can_close(&mut self) -> bool { + let start = self.cur_start(); + if let Some(cache) = &self.state.type_argument_lookahead { + if cache.cannot_close(start) { + return false; + } + if start < cache.scanned_until { + return true; + } + } + + // The parser's current token already consumed the opening angle from the lexer. + // Seed it explicitly, then inspect subsequent tokens without committing lexer state. + let checkpoint = self.lexer.checkpoint(); + let errors_len = self.lexer.errors.len(); + let mut angles = vec![start]; + if matches!(self.cur_kind(), Kind::ShiftLeft | Kind::ShiftLeftEq) { + // `f<() => T>()` starts with two openings in one lexer token. + angles.push(start + 1); + } + // Types contain (), [] and {} (function/parenthesized types, tuples/indexed + // accesses, and object/mapped types). Computed keys can contain expressions too. + // Each group saves the first angle opened inside it: `>` in `{ [x > y]: T }` + // cannot close an outer type argument, and `<` in `[x < y]` cannot escape `]`. + let mut groups = Vec::new(); + let jsx = self.source_type.is_jsx(); + let cache = self.state.type_argument_lookahead.get_or_insert_with(Box::default); + let mut scanned_until; + let can_close = loop { + let token = self.lexer.next_token(); + scanned_until = token.start(); + if self.lexer.errors.len() != errors_len { + // Recovery tokenization is not evidence about the intended delimiters. + break true; + } + let kind = token.kind(); + match kind { + // A computed key can contain `/[<>]/` (or a regex starting `/=`), whose + // punctuation is not type syntax. `${...}` in template types/expressions + // requires the parser to re-lex `}` as a template continuation. Stop before + // either lexical goal can make subsequent ordinary tokens misleading. + // An undetermined token likewise cannot support a delimiter proof. + Kind::Slash | Kind::SlashEq | Kind::TemplateHead | Kind::Undetermined => { + break true; + } + Kind::LAngle | Kind::ShiftLeft | Kind::ShiftLeftEq => { + if jsx && !groups.is_empty() { + // A computed-key expression may start JSX: its tag/text scanner + // gives `<` and `>` different roles. Without parsing the group we + // cannot distinguish this from nested generics or a comparison. + break true; + } + // Count every leading `<`, including generic function type parameters. + angles.push(token.start()); + if matches!(kind, Kind::ShiftLeft | Kind::ShiftLeftEq) { + angles.push(token.start() + 1); + } + } + Kind::LParen | Kind::LBrack | Kind::LCurly => { + groups.push((kind, angles.len())); + } + Kind::RParen | Kind::RBrack | Kind::RCurly => { + // With no group opened by this scan, the closer ends the construct + // containing the candidate. Its required `>` has not appeared. + let Some((opening, first_angle)) = groups.pop() else { break false }; + if !matches!( + (opening, kind), + (Kind::LParen, Kind::RParen) + | (Kind::LBrack, Kind::RBrack) + | (Kind::LCurly, Kind::RCurly) + ) { + // Mismatched groups need the parser's own diagnostic/recovery path. + break true; + } + // Only openings inside this group are ruled out. Outer angles may + // still close later, as in `f<{ [x < y]: T }>()`. + cache.unclosed.extend(angles.drain(first_angle..)); + } + Kind::Semicolon => { + // A semicolon cannot occur directly in a type-argument list. Within + // a group it can separate object-type members or statements in a + // computed-key function body, so retain openings outside that group: + // `f<{ a: T; b: U }>()` still has a possible closing angle. + let first_angle = groups.last().map_or(0, |&(_, first_angle)| first_angle); + cache.unclosed.extend(angles.drain(first_angle..)); + if groups.is_empty() { + break false; + } + } + Kind::RAngle => { + // Ordinary lexing yields individual `>` tokens even in `>>`, `>>>` + // and `>=`; expression parsing re-lexes the operators later. This + // deliberately leaves their disambiguation to the grammar parser. + // The `>` in a function type's `=>` is part of an Arrow token instead. + let first_angle = groups.last().map_or(0, |&(_, first_angle)| first_angle); + if angles.len() > first_angle { + angles.pop(); + } + if angles.is_empty() { + // Balanced delimiters are necessary, but contents and following + // tokens may still make this a comparison rather than type arguments. + break true; + } + } + // No later token can provide the missing closing angle. + Kind::Eof => break false, + // The lexer skips comments/trivia and consumes strings and templates + // without substitutions as whole tokens, hiding their punctuation. Other + // tokens (commas, unions, intersections, `extends`, `?`, `=>`, etc.) can be + // part of a type or an embedded expression; leave them to the real parser. + _ => {} + } + }; + cache.scanned_until = cache.scanned_until.max(scanned_until); + if !can_close { + cache.unclosed.extend(angles); + } + self.lexer.rewind(checkpoint); + can_close + } +} diff --git a/vendor/oxc_parser/src/ts/types.rs b/vendor/oxc_parser/src/ts/types.rs index c2ac1928c..bb9650982 100644 --- a/vendor/oxc_parser/src/ts/types.rs +++ b/vendor/oxc_parser/src/ts/types.rs @@ -1,5 +1,6 @@ use oxc_allocator::{ArenaBox, ArenaVec}; use oxc_ast::ast::*; +use oxc_data_structures::buffered_vec::BufferedVec; use oxc_span::{GetSpan, SPAN, Span}; use oxc_str::Ident; use oxc_syntax::operator::UnaryOperator; @@ -10,7 +11,11 @@ use crate::{ modifiers::{ModifierKind, ModifierKinds, Modifiers}, }; -use super::{super::js::FunctionKind, statement::CallOrConstructorSignature}; +use super::{ + super::js::{FunctionKind, kind_to_precedence}, + statement::CallOrConstructorSignature, + type_arguments::{TYPE_ARGUMENT_LOOKAHEAD_DEPTH, TypeArgumentFailure}, +}; impl<'a, C: Config> ParserImpl<'a, C> { pub(crate) fn parse_ts_type(&mut self) -> TSType<'a> { @@ -221,12 +226,10 @@ impl<'a, C: Config> ParserImpl<'a, C> { pub(crate) fn parse_ts_implements_clause(&mut self) -> ArenaVec<'a, TSClassImplements<'a>> { self.expect(Kind::Implements); - let first = self.parse_ts_implement_name(); - let mut implements = ArenaVec::from_value_in(first, self); - while self.eat(Kind::Comma) { - implements.push(self.parse_ts_implement_name()); - } - implements + let mut first = Some(self.parse_ts_implement_name()); + self.collect_list(|p| { + first.take().or_else(|| p.eat(Kind::Comma).then(|| p.parse_ts_implement_name())) + }) } fn parse_ts_type_parameter(&mut self, allow_variance: bool) -> TSTypeParameter<'a> { @@ -308,11 +311,10 @@ impl<'a, C: Config> ParserImpl<'a, C> { where F: Fn(&mut Self) -> TSType<'a>, { - let mut types = ArenaVec::from_value_in(ty, self); - while self.eat(kind) { - let ty = parse_constituent_type(self); - types.push(ty); - } + let mut first = Some(ty); + let types = self.collect_list(|p| { + first.take().or_else(|| p.eat(kind).then(|| parse_constituent_type(p))) + }); let span = self.end_span(start); match kind { Kind::Pipe => TSType::new_ts_union_type(span, types, self), @@ -464,9 +466,14 @@ impl<'a, C: Config> ParserImpl<'a, C> { | Kind::Boolean | Kind::Undefined | Kind::Never - | Kind::Object + | Kind::Object => self.parse_keyword_type(), // Parse `null` as `TSNullKeyword` instead of null literal to align with typescript eslint. - | Kind::Null => self.parse_keyword_type(), + // Unlike the keywords above, it cannot begin a qualified name: `null.x`. + Kind::Null => { + let span = self.cur_token().span(); + self.bump_any(); + TSType::new_ts_null_keyword(span, self) + } // TODO: js doc types: `JSDocAllType`, `JSDocFunctionType` // Kind::StarEq => { // scanner.reScanAsteriskEqualsToken(); @@ -489,7 +496,11 @@ impl<'a, C: Config> ParserImpl<'a, C> { let start = self.cur_start(); let literal = self.parse_template_literal(false); let span = self.end_span(start); - TSType::new_ts_literal_type(span, TSLiteral::TemplateLiteral(self.alloc(literal)), self) + TSType::new_ts_literal_type( + span, + TSLiteral::TemplateLiteral(self.alloc(literal)), + self, + ) } Kind::Minus => { if self.lexer.peek_token().kind().is_number() { @@ -515,9 +526,7 @@ impl<'a, C: Config> ParserImpl<'a, C> { TSType::TSThisType(this_type) } } - Kind::Typeof => { - self.parse_type_query() - } + Kind::Typeof => self.parse_type_query(), Kind::LCurly => { let opening_span = self.cur_token().span(); self.bump_any(); @@ -574,7 +583,6 @@ impl<'a, C: Config> ParserImpl<'a, C> { Kind::Symbol => TSType::new_ts_symbol_keyword(span, self), Kind::Undefined => TSType::new_ts_undefined_keyword(span, self), Kind::Unknown => TSType::new_ts_unknown_keyword(span, self), - Kind::Null => TSType::new_ts_null_keyword(span, self), _ => unreachable!(), } } @@ -724,8 +732,13 @@ impl<'a, C: Config> ParserImpl<'a, C> { } fn parse_type_literal(&mut self, opening_span: Span) -> TSType<'a> { - let mut member_list = ArenaVec::new_in(self); - self.parse_normal_list_into(&mut member_list, Kind::RCurly, Self::parse_ts_type_signature); + let member_list = self.collect_list(|p| { + if p.at(Kind::RCurly) || p.has_fatal_error() { + None + } else { + Some(p.parse_ts_type_signature()) + } + }); self.expect_closing(Kind::RCurly, opening_span); TSType::new_ts_type_literal(self.end_span(opening_span.start), member_list, self) } @@ -790,8 +803,8 @@ impl<'a, C: Config> ParserImpl<'a, C> { fn parse_template_type(&mut self, tagged: bool) -> TSType<'a> { let start = self.cur_start(); - let mut types = ArenaVec::new_in(self); - let mut quasis = ArenaVec::new_in(self); + let mut types = BufferedVec::<_, 4>::new(ArenaVec::new_in(self)); + let mut quasis = BufferedVec::<_, 4>::new(ArenaVec::new_in(self)); match self.cur_kind() { Kind::NoSubstitutionTemplate => { quasis.push(self.parse_template_element(tagged)); @@ -823,7 +836,12 @@ impl<'a, C: Config> ParserImpl<'a, C> { _ => unreachable!("parse_template_literal"), } - TSType::new_ts_template_literal_type(self.end_span(start), quasis, types, self) + TSType::new_ts_template_literal_type( + self.end_span(start), + quasis.into_vec(), + types.into_vec(), + self, + ) } fn parse_asserts_type_predicate(&mut self, asserts_start: u32) -> TSType<'a> { @@ -895,8 +913,21 @@ impl<'a, C: Config> ParserImpl<'a, C> { left_name } + /// Parse `TypeArguments` if the cursor is at their `<`. + #[inline] // Most callers are not at `<`. Decide that without a call. pub(crate) fn try_parse_type_arguments( &mut self, + ) -> Option>> { + // The tokens which `re_lex_ts_l_angle` accepts. + if matches!(self.cur_kind(), Kind::LAngle | Kind::ShiftLeft | Kind::ShiftLeftEq) { + self.try_parse_type_arguments_at_l_angle() + } else { + None + } + } + + fn try_parse_type_arguments_at_l_angle( + &mut self, ) -> Option>> { if self.re_lex_ts_l_angle() { let start = self.cur_start(); @@ -907,7 +938,7 @@ impl<'a, C: Config> ParserImpl<'a, C> { Kind::RAngle, Kind::Comma, opening_span, - Self::parse_ts_type, + Self::parse_type_argument, ); self.expect(Kind::RAngle); let span = self.end_span(start); @@ -926,11 +957,10 @@ impl<'a, C: Config> ParserImpl<'a, C> { pub(crate) fn parse_type_arguments_of_type_reference( &mut self, ) -> Option>> { + // Type references attach `<...>` only when `<` is on the same line as the name. + // The contents of the list may span lines. The expression rule below is separate. if self.cur_token().is_on_new_line() - || !matches!( - self.cur_kind(), - Kind::LAngle | Kind::ShiftLeft | Kind::LtEq | Kind::ShiftLeftEq - ) + || !matches!(self.cur_kind(), Kind::LAngle | Kind::ShiftLeft | Kind::ShiftLeftEq) { return None; } @@ -939,6 +969,40 @@ impl<'a, C: Config> ParserImpl<'a, C> { fn parse_type_arguments_of_type_reference_impl( &mut self, + ) -> Option>> { + let depth = self.state.type_argument_depth; + if depth == 0 || self.fatal_error.is_some() { + // Committed type syntax must keep its normal diagnostics. Also do not cache + // a failure inherited from an earlier token as a failure of this type list. + return self.parse_type_arguments_of_type_reference_worker(); + } + let start = self.cur_start(); + let context = self.ctx; + if self.state.type_argument_lookahead.as_ref().is_some_and(|lookahead| { + lookahead.has_failed(start, context, TypeArgumentFailure::Type) + }) || (depth >= TYPE_ARGUMENT_LOOKAHEAD_DEPTH + && !self.speculative_type_arguments_can_close()) + { + // We are still at an opening `<`, so expecting `>` marks this attempt fatal. + // It belongs to an enclosing speculative expression parse, which rewinds it; + // returning None alone would allow the enclosing type to appear successful. + self.expect(Kind::RAngle); + return None; + } + self.state.type_argument_depth = depth + 1; + let result = self.parse_type_arguments_of_type_reference_worker(); + self.state.type_argument_depth = depth; + // Recoverable diagnostics (for example an empty list) do not reject speculation. + if self.fatal_error.is_some() { + self.record_type_argument_failure(start, context, TypeArgumentFailure::Type, depth); + } + result + } + + #[expect(clippy::inline_always)] + #[inline(always)] // Avoid an extra call on the ordinary generic-type path. + fn parse_type_arguments_of_type_reference_worker( + &mut self, ) -> Option>> { if self.re_lex_ts_l_angle() { let start = self.cur_start(); @@ -949,7 +1013,7 @@ impl<'a, C: Config> ParserImpl<'a, C> { Kind::RAngle, Kind::Comma, opening_span, - Self::parse_ts_type, + Self::parse_type_argument, ); self.expect(Kind::RAngle); let span = self.end_span(start); @@ -961,23 +1025,69 @@ impl<'a, C: Config> ParserImpl<'a, C> { None } + /// Parse one type in a `TypeArguments` list. + /// + /// TypeScript parses a type argument only from a token which can start a type. A type + /// reference otherwise accepts any identifier name, as in `let a: class`, but `A` + /// is not a type-argument list. + fn parse_type_argument(&mut self) -> TSType<'a> { + if is_reserved_non_type_start(self.cur_kind()) { + return self.unexpected(); + } + self.parse_ts_type() + } + /// Speculatively parse a `` type-argument list in an expression - /// position (e.g. `foo(arg)` vs `foo < T`). Returns `None` and rewinds - /// any parser/lexer state when the upcoming tokens turn out not to be a - /// valid type-argument list. + /// position (e.g. `foo(arg)` vs `foo < T`). Returns `None` if a cached failure + /// rules it out, or rewinds to the checkpoint when a fresh attempt fails. pub(crate) fn parse_type_arguments_in_expression( &mut self, ) -> Option>> { // A type-argument list can only open with `<`, or `<<` for nested generics like // `f<() => U>()`. This mirrors TypeScript's `reScanLessThanToken`, which re-scans only - // `<`/`<<`. `<=`/`<<=` can never open one — splitting off the leading `<` leaves a `=`, and - // no type starts with `=` — so although `re_lex_ts_l_angle` would accept them (it is shared - // with type-context callers), speculating here can only fail and rewind to `None`. Bail - // before the checkpoint for any non-`<`-opening token (the common `a?.(`, `a?.b` paths), - // avoiding a checkpoint/rewind round-trip that returns `None` anyway. + // `<`/`<<`. if !matches!(self.cur_kind(), Kind::LAngle | Kind::ShiftLeft) { return None; } + // Most `<` in expressions are relational operators (`i < items.length`) and most `<<` are + // shifts (`1 << 2`). The grammar rules those out within a few tokens, so decide from the + // tokens alone rather than building a type and a diagnostic only to discard both. + if !self.can_start_type_arguments_in_expression() { + return None; + } + if self.state.type_argument_lookahead.as_ref().is_some_and(|lookahead| { + // Missing delimiters rule out both contexts. Actual parse failures must also + // match the grammar flags, and can include the expression-only follow rule. + lookahead.cannot_close(self.cur_start()) + || lookahead.has_failed(self.cur_start(), self.ctx, TypeArgumentFailure::Expression) + }) { + return None; + } + let depth = self.state.type_argument_depth; + if depth >= TYPE_ARGUMENT_LOOKAHEAD_DEPTH && !self.speculative_type_arguments_can_close() { + return None; + } + let start = self.cur_start(); + let context = self.ctx; + self.state.type_argument_depth = depth + 1; + let result = self.parse_type_arguments_in_expression_worker(); + self.state.type_argument_depth = depth; + if result.is_none() { + self.record_type_argument_failure( + start, + context, + TypeArgumentFailure::Expression, + depth, + ); + } + result + } + + #[expect(clippy::inline_always)] + #[inline(always)] // Keep the existing grammar body inside the speculation wrapper. + fn parse_type_arguments_in_expression_worker( + &mut self, + ) -> Option>> { let checkpoint = self.checkpoint(); let start = self.cur_start(); if !self.re_lex_ts_l_angle() { @@ -987,9 +1097,15 @@ impl<'a, C: Config> ParserImpl<'a, C> { let opening_span = self.cur_token().span(); debug_assert!(self.at(Kind::LAngle)); self.advance(Kind::LAngle); - let (params, _) = - self.parse_delimited_list(Kind::RAngle, Kind::Comma, opening_span, Self::parse_ts_type); - // `a < b> = c` is valid but `a < b >= c` is BinaryExpression + let (params, _) = self.parse_delimited_list( + Kind::RAngle, + Kind::Comma, + opening_span, + Self::parse_type_argument, + ); + // A contiguous `>=` remains a relational operator: `a < b >= c`. A separated + // `> =` can end an instantiation before `=`; assignment validity is checked later. + // Re-lex before consuming `>` so whitespace between these spellings matters. if matches!(self.re_lex_right_angle(), Kind::GtEq) { self.rewind(checkpoint); return None; @@ -1007,11 +1123,140 @@ impl<'a, C: Config> ParserImpl<'a, C> { Some(TSTypeParameterInstantiation::boxed(span, params, self)) } + /// Whether the tokens after the current `<` or `<<` can begin a `TypeArguments` production. + /// + /// ```text + /// TypeArguments : `<` TypeArgumentList `>` + /// TypeArgumentList : Type (`,` Type)* + /// ``` + /// + /// Returns `false` only when [`Self::parse_type_arguments_in_expression`] is certain to fail, + /// so that it need not speculate. Every shape not recognized here is left to that parse. + /// Only lexer state changes, and it is restored. + fn can_start_type_arguments_in_expression(&mut self) -> bool { + let checkpoint = self.lexer.checkpoint(); + let first = self.lexer.next_token().kind(); + let can_start = if self.at(Kind::ShiftLeft) { + self.can_start_type_parameters_after(first) + } else { + self.can_start_type_argument_after(first) + }; + self.lexer.rewind(checkpoint); + can_start + } + + /// Whether a type argument can begin with `first`, the token after `<`. + /// + /// A `Type` which begins with a name, a literal or `this` is complete after that primary type + /// unless the next token continues it, and a complete type argument is followed by `,` or `>`: + /// + /// ```text + /// TypeReference : TypeName [no LineTerminator here] TypeArguments? + /// TypeName : IdentifierReference | TypeName `.` IdentifierName + /// ArrayType : PrimaryType [no LineTerminator here] `[` `]` + /// IndexedAccessType : PrimaryType [no LineTerminator here] `[` Type `]` + /// IntersectionType : Type `&` Type + /// UnionType : Type `|` Type + /// ConditionalType : Type `extends` Type `?` Type `:` Type + /// TypePredicate : `this` `is` Type + /// ``` + /// + /// plus the JSDoc postfix `!` and `?`, which the type parser accepts in order to report them. + /// Any other token ends the list early: `a < b;`, `a < b.c)`, `a < 0 &&`, `a < this.b`. + /// A reserved word which cannot start a type rules out the list at once: `a < class {}`. + /// + /// The lexer is positioned after `first`. The checks mirror `parse_non_array_type`, + /// `parse_postfix_type_rest`, `parse_type_argument` and their callers, and must be kept in + /// step with them. + fn can_start_type_argument_after(&mut self, first: Kind) -> bool { + let is_name = matches!( + first, + Kind::Ident + | Kind::Any + | Kind::Unknown + | Kind::String + | Kind::Number + | Kind::BigInt + | Kind::Symbol + | Kind::Boolean + | Kind::Undefined + | Kind::Never + | Kind::Object + ); + if !is_name + && !matches!(first, Kind::Null | Kind::This | Kind::Str | Kind::True | Kind::False) + && !first.is_number() + { + return !is_reserved_non_type_start(first); + } + let mut next = self.lexer.next_token().kind(); + while is_name && next == Kind::Dot { + if !self.lexer.next_token().kind().is_identifier_name() { + return false; + } + next = self.lexer.next_token().kind(); + } + match next { + Kind::RAngle + | Kind::Comma + | Kind::LAngle + | Kind::ShiftLeft + | Kind::ShiftLeftEq + | Kind::LBrack + | Kind::Bang + | Kind::Amp + | Kind::Pipe + | Kind::Extends + | Kind::Is => true, + // JSDoc `T?` ends the primary type, so what follows it cannot start another type. + // This tells it apart from a conditional expression: `a < b ? c : d`. + Kind::Question => { + matches!(self.lexer.next_token().kind(), Kind::RAngle | Kind::Comma | Kind::Extends) + } + _ => false, + } + } + + /// Whether a type parameter list can begin with `first`, the token after `<<`. + /// + /// The first type argument starts with the second `<`, so it must be a generic function + /// type, whose type parameter list opens with a `TypeParameter`: + /// + /// ```text + /// TypeParameter : Modifiers? BindingIdentifier (`extends` Type)? (`=` Type)? + /// ``` + /// + /// which rules out `1 << 2` at the first token, and `a << b;` at the second. + /// + /// The lexer is positioned after `first`. The checks mirror `parse_ts_type_parameter` and + /// its callers, and must be kept in step with them. + fn can_start_type_parameters_after(&mut self, first: Kind) -> bool { + match first { + Kind::Ident => matches!( + self.lexer.next_token().kind(), + Kind::Extends | Kind::Eq | Kind::Comma | Kind::RAngle + ), + // An empty list is only a recoverable error: `f<<>() => void>()`. + Kind::RAngle => true, + // Keywords may be modifiers (`const T`) or contextual names (`of`). + kind => kind.is_identifier_name(), + } + } + fn can_follow_type_arguments_in_expr(&mut self) -> bool { match self.cur_kind() { + // Prefer generic calls and tagged templates over relational expressions: + // `f(x)`, ``f`text` `` and ``f`text${x}` ``. Kind::LParen | Kind::NoSubstitutionTemplate | Kind::TemplateHead => true, + // `<` cannot continue an instantiation here; `>` may belong to a shift. + // In `a < b > +c` / `a < b > -c`, preserve the unary operand of the comparison. + // These exclusions take precedence even when there is a line break. Kind::LAngle | Kind::RAngle | Kind::Plus | Kind::Minus => false, _ => { + // Instantiations need not be called: `const g = f;` is valid. A line + // break, another binary operator, or a token that cannot start an operand + // favors that interpretation. A same-line operand as in `a < b > c` + // instead leaves `<` and `>` to the relational-expression parser. self.cur_token().is_on_new_line() || self.is_binary_operator() || !self.is_start_of_expression() @@ -1300,7 +1545,6 @@ impl<'a, C: Config> ParserImpl<'a, C> { value, false, false, - false, self, ); @@ -1342,7 +1586,7 @@ impl<'a, C: Config> ParserImpl<'a, C> { let prop_start = self.cur_start(); - let (key, value, computed) = if self.at(Kind::LBrack) { + let (key, value) = if self.at(Kind::LBrack) { let bracket_span = self.cur_token().span(); self.error(diagnostics::ts_import_type_options_invalid_key(bracket_span)); // Parse as computed to recover @@ -1352,18 +1596,18 @@ impl<'a, C: Config> ParserImpl<'a, C> { self.expect(Kind::Colon); let value = self.parse_assignment_expression_or_higher(); let key = PropertyKey::new_string_literal(bracket_span, "", None, self); - (key, value, true) + (key, value) } else { let key = if self.at(Kind::Str) { let string_literal = self.parse_known_literal_string(); - PropertyKey::StringLiteral(self.alloc(string_literal)) + PropertyKey::StaticStringLiteral(self.alloc(string_literal)) } else { let ident = self.parse_identifier_name(); PropertyKey::StaticIdentifier(self.alloc(ident)) }; self.expect(Kind::Colon); let value = self.parse_assignment_expression_or_higher(); - (key, value, false) + (key, value) }; let property = ObjectPropertyKind::new_object_property( @@ -1373,7 +1617,6 @@ impl<'a, C: Config> ParserImpl<'a, C> { value, false, false, - computed, self, ); properties.push(property); @@ -1495,7 +1738,7 @@ impl<'a, C: Config> ParserImpl<'a, C> { start: u32, kind: TSMethodSignatureKind, ) -> TSSignature<'a> { - let (key, computed) = self.parse_property_name(); + let key = self.parse_property_name(); let (this_param, params) = self.parse_formal_parameters(FunctionKind::Declaration, FormalParameterKind::Signature); let return_type = self.parse_ts_return_type_annotation(); @@ -1537,7 +1780,6 @@ impl<'a, C: Config> ParserImpl<'a, C> { TSSignature::new_ts_method_signature( self.end_span(start), key, - computed, /* optional */ false, kind, None, @@ -1553,7 +1795,7 @@ impl<'a, C: Config> ParserImpl<'a, C> { start: u32, modifiers: &Modifiers, ) -> TSSignature<'a> { - let (key, computed) = self.parse_property_name(); + let key = self.parse_property_name(); let optional = self.eat(Kind::Question); let kind = self.cur_kind(); @@ -1573,7 +1815,6 @@ impl<'a, C: Config> ParserImpl<'a, C> { TSSignature::new_ts_method_signature( self.end_span(start), key, - computed, optional, TSMethodSignatureKind::Method, type_parameters, @@ -1587,7 +1828,6 @@ impl<'a, C: Config> ParserImpl<'a, C> { self.parse_type_member_semicolon(); TSSignature::new_ts_property_signature( self.end_span(start), - computed, optional, modifiers.contains_readonly(), key, @@ -1733,7 +1973,7 @@ impl<'a, C: Config> ParserImpl<'a, C> { if !self.ctx.has_in() && self.at(Kind::In) { return false; } - self.cur_kind().is_binary_operator() + kind_to_precedence(self.cur_kind()).is_some() } fn is_start_of_expression(&mut self) -> bool { @@ -1745,7 +1985,7 @@ impl<'a, C: Config> ParserImpl<'a, C> { kind if kind.is_update_operator() => true, Kind::LAngle | Kind::Await | Kind::Yield | Kind::Private | Kind::At => true, _ if self.is_binary_operator() => true, - kind => kind.is_ts_identifier(self.ctx.has_yield(), self.ctx.has_await()), + kind => kind.is_identifier_reference(self.ctx.has_yield(), self.ctx.has_await()), } } @@ -1766,7 +2006,28 @@ impl<'a, C: Config> ParserImpl<'a, C> { Kind::Import => { matches!(self.lexer.peek_token().kind(), Kind::LParen | Kind::LAngle | Kind::Dot) } - _ => false, + kind => kind.is_identifier_reference(self.ctx.has_yield(), self.ctx.has_await()), } } } + +/// Whether `kind` is a reserved word which cannot start a type. +/// +/// `await` and `yield` are excluded because outside their own contexts they are identifiers. +const fn is_reserved_non_type_start(kind: Kind) -> bool { + kind.is_reserved_keyword() + && !matches!( + kind, + Kind::Await + | Kind::False + | Kind::Function + | Kind::Import + | Kind::New + | Kind::Null + | Kind::This + | Kind::True + | Kind::Typeof + | Kind::Void + | Kind::Yield + ) +} From 46fcd7a027f7f0e453b100890b60e554ba548436 Mon Sep 17 00:00:00 2001 From: Tolga Ergin Date: Wed, 25 Nov 2026 01:34:54 +0000 Subject: [PATCH 2/4] Parse nested parentheses in linear time, and check the budget at every lexer rewind MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit oxc 0.160 walked every parenthesis inside a closing one to find where the expression innermost in them starts, so `((((…a…))))` was quadratic without speculating: 80,000 levels, which fit on a 64 MiB stack, took four seconds in a release build. ParserState::last_parenthesized keeps the innermost start of the ParenthesizedExpression built last, so each level reads it instead of walking the chain. 80,000 levels now take 3 ms. The speculation budget was compared only at the parser's rewinds, so a lookahead that rewinds only the lexer, such as deciding whether `(` starts a function type, could pass the budget without the parse stopping or reporting it. The lexer now compares at every rewind and keeps the stop, and a parse that reached the stack floor still reports only that. The budget tests now assert that their sources exhaust the budget, not only that they end up read without parsing. Co-Authored-By: Claude Opus 5.5 --- crates/lpm-security/src/behavioral/mod.rs | 2 + crates/lpm-security/src/behavioral/syntax.rs | 73 ++++++++ vendor/oxc_parser/LPM-PATCH.md | 38 ++-- vendor/oxc_parser/lpm-stack-floor.patch | 186 ++++++++++++++----- vendor/oxc_parser/src/cursor.rs | 16 +- vendor/oxc_parser/src/js/arrow.rs | 1 + vendor/oxc_parser/src/js/cover.rs | 18 +- vendor/oxc_parser/src/js/expression.rs | 1 + vendor/oxc_parser/src/lexer/mod.rs | 28 ++- vendor/oxc_parser/src/lib.rs | 22 +-- vendor/oxc_parser/src/state.rs | 8 + 11 files changed, 300 insertions(+), 93 deletions(-) diff --git a/crates/lpm-security/src/behavioral/mod.rs b/crates/lpm-security/src/behavioral/mod.rs index 9c2faedc3..2c1346df3 100644 --- a/crates/lpm-security/src/behavioral/mod.rs +++ b/crates/lpm-security/src/behavioral/mod.rs @@ -3495,6 +3495,7 @@ mod tests { // as one and, when no `=>` follows its parameters, parsed again as a // type assertion, with every head nested in its defaults. let source = format!("x={};eval(y);", nested("(a=y,b=", "0", ")", 3_000)); + assert!(syntax::exhausts_the_speculation_budget("index.ts", &source)); let flat = format!("{}eval(y);", "x;".repeat(source.len() / 2)); let started = std::time::Instant::now(); let flat_result = analyze_on_a_worker_stack("index.ts", flat); @@ -3554,6 +3555,7 @@ mod tests { 2_000 ) ); + assert!(syntax::exhausts_the_speculation_budget("index.ts", &source)); let flat = format!("{}eval(y);", "x;".repeat(source.len() / 2)); let started = std::time::Instant::now(); let flat_result = analyze_on_a_worker_stack("index.ts", flat); diff --git a/crates/lpm-security/src/behavioral/syntax.rs b/crates/lpm-security/src/behavioral/syntax.rs index d0e742259..1054ac219 100644 --- a/crates/lpm-security/src/behavioral/syntax.rs +++ b/crates/lpm-security/src/behavioral/syntax.rs @@ -561,6 +561,30 @@ impl<'s> SourceContext<'s> { } } +/// Whether parsing `source`, named `filename`, on a stack deep enough for +/// it, stops at the speculation budget [`parse`] gives it. +#[cfg(test)] +pub(super) fn exhausts_the_speculation_budget(filename: &str, source: &str) -> bool { + let source_type = SourceType::from_path(filename).unwrap(); + let source = source.to_owned(); + std::thread::Builder::new() + .stack_size(256 * 1024 * 1024) + .spawn(move || { + let allocator = Allocator::default(); + Parser::new(&allocator, &source, source_type) + .with_options(ParseOptions { + stack_floor: current_stack_floor().unwrap(), + speculation_budget: parse_speculation_budget(&source), + ..ParseOptions::default() + }) + .parse() + .speculation_budget_exhausted + }) + .unwrap() + .join() + .unwrap() +} + #[cfg(test)] mod tests { use super::*; @@ -646,6 +670,55 @@ mod tests { } } + #[test] + fn lookahead_that_reads_past_the_speculation_budget_stops_the_parse() { + // Deciding whether `(` starts a function type reads tokens ahead and + // rewinds only the lexer; no speculative parse follows to check the + // budget. + let allocator = Allocator::default(); + let parsed = Parser::new(&allocator, "type T = (LongTypeName);", SourceType::ts()) + .with_options(ParseOptions { + speculation_budget: 1, + ..ParseOptions::default() + }) + .parse(); + assert!(parsed.speculation_budget_exhausted); + assert!(parsed.fatal_error); + } + + #[test] + fn parentheses_nested_tens_of_thousands_of_levels_deep_parse_in_linear_time() { + // Each closing parenthesis records where the expression innermost in + // it starts, and must not walk every parenthesis inside it to find it. + let time_to_parse = |source: String| { + 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()) + .with_options(ParseOptions { + stack_floor: current_stack_floor().unwrap(), + ..ParseOptions::default() + }) + .parse(); + let elapsed = started.elapsed(); + assert!(!parsed.stack_exhausted && !parsed.fatal_error); + elapsed + }) + .unwrap() + .join() + .unwrap() + }; + 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)); + assert!( + nested < flat * 5 + std::time::Duration::from_millis(200), + "nested {nested:?}, flat {flat:?}" + ); + } + /// Visits `source` with the floor `room` bytes below where the visit /// starts, on a stack deep enough to parse it, and returns whether the /// visitor stopped at the floor and whether it unwound. diff --git a/vendor/oxc_parser/LPM-PATCH.md b/vendor/oxc_parser/LPM-PATCH.md index d89fc6f83..3612f9a44 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 two changes: the parser can stop at a stack -floor instead of overflowing its thread's stack, and at a budget for the -work it spends on speculative parses. The workspace uses it through -`[patch.crates-io]` in the root `Cargo.toml`. +licensed (see `LICENSE`), with three changes: the parser can stop at a +stack floor instead of overflowing its thread's stack, and at a budget for +the work it spends on speculative parses, and nested parentheses take it +linear time. The workspace uses it through `[patch.crates-io]` in the root +`Cargo.toml`. ## Why @@ -23,6 +24,11 @@ Nested speculation can make a parse take time quadratic in the source's length: `x=(a=(a=…0)));` reads 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. + ## What changed `lpm-stack-floor.patch` is the whole change against the published crate: @@ -66,13 +72,20 @@ around it. skips without reading when a fatal error moves it to the end of the 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 parser compares them with the budget at each - of its rewinds, so a parse pays nothing for them per token. A parse - already stopped at the floor is unwinding and isn't checked against the - budget, so it can still be retried on a larger stack. Going past the - budget stops the parse the same way the floor does, sticky across later - rewinds, and `ParserReturn::speculation_budget_exhausted` reports it. The - default, `0`, never stops. + 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 + `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. +- `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. `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 @@ -95,7 +108,8 @@ more than 30% of its budget. 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. - `lpm-security`'s + Look for walks over nodes already built, like the one through nested + parentheses, that run once per level of nesting. `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 diff --git a/vendor/oxc_parser/lpm-stack-floor.patch b/vendor/oxc_parser/lpm-stack-floor.patch index 440b25faa..4dc714811 100644 --- a/vendor/oxc_parser/lpm-stack-floor.patch +++ b/vendor/oxc_parser/lpm-stack-floor.patch @@ -33,7 +33,7 @@ + #[inline] + fn check_parse_limits(&mut self) { + if self.stack_exhausted.get() -+ || self.speculation_budget_exhausted ++ || self.lexer.speculation_budget_exhausted() + || self.below_stack_floor() + { + self.stop_at_parse_limit(); @@ -59,7 +59,7 @@ + #[cold] + #[inline(never)] + fn stop_at_parse_limit(&mut self) { -+ if self.speculation_budget_exhausted && !self.stack_exhausted.get() { ++ if self.lexer.speculation_budget_exhausted() && !self.stack_exhausted.get() { + self.set_fatal_error(diagnostics::speculation_budget_exhausted(self.token.span())); + } else { + self.stop_at_stack_floor(); @@ -120,29 +120,6 @@ self.prev_token_end = self.token.end(); self.token = self.lexer.next_jsx_attribute_value(); } -@@ -373,10 +451,22 @@ - self.lexer.errors.push(fatal_error.error); - } - self.lexer.rewind(lexer); -+ self.check_speculation_budget(); - self.token = cur_token; - self.prev_token_end = prev_token_end; - self.errors.truncate(errors_pos); - self.state.cover_parenthesized.truncate(cover_parenthesized_len); -+ } -+ -+ /// Sets the budget's stop once the work spent on speculation passes it: -+ /// the bytes the lexer has read beyond its position, which a rewind made -+ /// it read or will make it read again. A parse already stopped at the -+ /// stack floor is unwinding, and reads nothing again. -+ #[inline] -+ fn check_speculation_budget(&mut self) { -+ if !self.stack_exhausted.get() && self.lexer.bytes_read_ahead() > self.speculation_limit { -+ self.speculation_budget_exhausted = true; -+ } - } - - /// Rewind to `checkpoint`, keeping the comments and irregular whitespace lexed after it. --- a/src/diagnostics.rs +++ b/src/diagnostics.rs @@ -94,6 +94,16 @@ @@ -162,6 +139,61 @@ file_appears_to_be_binary() => { ts_error("1490", "File appears to be binary.") }; +--- a/src/js/arrow.rs ++++ b/src/js/arrow.rs +@@ -185,6 +185,7 @@ + } + let expression = Expression::new_identifier(span, name, self); + let expression = if self.options.preserve_parens { ++ self.state.last_parenthesized = (start, span.start); + Expression::new_parenthesized_expression(self.end_span(start), expression, self) + } else { + expression +--- a/src/js/cover.rs ++++ b/src/js/cover.rs +@@ -797,15 +797,31 @@ + // Record where the innermost expression starts, which is what an enclosing check + // finds: inner parentheses leave no node without `preserve_parens`, and an assignment + // target drops them in `((a)) = b`. ++ let innermost = self.innermost_parenthesized_start(&expression); + self.state.cover_parenthesized.truncate(parenthesized_base); + if self.state.cover_depth > 0 { +- self.state.cover_parenthesized.push(expression.without_parentheses().span().start); ++ self.state.cover_parenthesized.push(innermost); + } + + if self.options.preserve_parens { ++ self.state.last_parenthesized = (start, innermost); + Expression::new_parenthesized_expression(self.end_span(start), expression, self) + } else { + expression ++ } ++ } ++ ++ /// Where the expression innermost in the parentheses around `expression` starts: the ++ /// start of `expression` without the `ParenthesizedExpression`s that wrap it. ++ #[inline] ++ pub(super) fn innermost_parenthesized_start(&self, expression: &Expression<'a>) -> u32 { ++ match expression { ++ Expression::ParenthesizedExpression(inner) ++ if inner.span.start == self.state.last_parenthesized.0 => ++ { ++ self.state.last_parenthesized.1 ++ } ++ expression => expression.without_parentheses().span().start, + } + } + +--- a/src/js/expression.rs ++++ b/src/js/expression.rs +@@ -408,6 +408,7 @@ + } + + if self.options.preserve_parens { ++ self.state.last_parenthesized = (start, self.innermost_parenthesized_start(&expression)); + Expression::new_parenthesized_expression(self.end_span(start), expression, self) + } else { + expression --- a/src/js/grammar.rs +++ b/src/js/grammar.rs @@ -14,6 +14,11 @@ @@ -221,7 +253,7 @@ BindingPattern::new_binding_identifier(ident.span, ident.name, self) --- a/src/lexer/mod.rs +++ b/src/lexer/mod.rs -@@ -130,6 +130,13 @@ +@@ -130,6 +130,20 @@ /// Config pub(crate) config: C, @@ -232,39 +264,68 @@ + /// Bytes the lexer has skipped without reading, by moving to the end of + /// the source after a fatal error. + bytes_skipped: u64, ++ ++ /// `ParseOptions::speculation_budget`, with `u64::MAX` for no limit. ++ speculation_limit: u64, ++ ++ /// 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,6 +183,8 @@ +@@ -176,9 +190,27 @@ escaped_templates: FxHashMap::default(), tokens, config, + bytes_rewound: 0, + bytes_skipped: 0, ++ speculation_limit: u64::MAX, ++ speculation_budget_exhausted: false, } } -@@ -239,10 +248,19 @@ ++ /// 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 { ++ self.speculation_limit = if budget == 0 { u64::MAX } else { budget }; ++ self ++ } ++ ++ /// 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] ++ pub(crate) fn speculation_budget_exhausted(&self) -> bool { ++ self.speculation_budget_exhausted ++ } ++ + /// 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 @@ self.errors.truncate(checkpoint.errors_len); self.tokens.truncate(checkpoint.tokens_len); + let from = self.offset(); self.source.set_position(checkpoint.source_position); + self.bytes_rewound += u64::from(from.saturating_sub(self.offset())); ++ if self.bytes_read_ahead() > self.speculation_limit { ++ self.speculation_budget_exhausted = true; ++ } self.trivia_builder.rewind(checkpoint.trivia); } + /// Bytes the lexer has read beyond its current position: those it read + /// and then rewound over, less those it skipped without reading. In all + /// it has read at most its position plus this many bytes. -+ pub(crate) fn bytes_read_ahead(&self) -> u64 { ++ fn bytes_read_ahead(&self) -> u64 { + self.bytes_rewound.saturating_sub(self.bytes_skipped) + } + /// 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 +588,9 @@ +@@ -570,7 +614,9 @@ /// Advance source cursor to end of file. #[inline] pub fn advance_to_end(&mut self) { @@ -285,7 +346,7 @@ mod ast_builder; pub mod config; -@@ -221,6 +221,15 @@ +@@ -221,6 +221,17 @@ /// Whether the file is [flow](https://flow.org). pub is_flow_language: bool, @@ -296,12 +357,14 @@ + pub stack_exhausted: bool, + + /// Whether parsing stopped at [`ParseOptions::speculation_budget`]. -+ /// [`fatal_error`](ParserReturn::fatal_error) is set too. ++ /// [`fatal_error`](ParserReturn::fatal_error) is set too. A parse that ++ /// reached [`ParseOptions::stack_floor`] reports only that: on a larger ++ /// stack it is checked against the budget again. + pub speculation_budget_exhausted: bool, } // `ParserReturn` is the output of `ParserImpl::parse`. -@@ -291,6 +300,33 @@ +@@ -291,6 +302,33 @@ /// /// Default: `true` pub enable_ident_hashes: bool, @@ -335,7 +398,7 @@ } impl Default for ParseOptions { -@@ -302,6 +338,8 @@ +@@ -302,6 +340,8 @@ preserve_parens: true, allow_v8_intrinsics: false, enable_ident_hashes: true, @@ -344,7 +407,7 @@ } } } -@@ -563,6 +601,16 @@ +@@ -563,6 +603,10 @@ /// Precomputed typescript detection is_ts: bool, @@ -352,35 +415,58 @@ + /// Parsing reached [`ParseOptions::stack_floor`]. A `Cell`, so that a + /// check that reads no token and borrows the parser can record it. + stack_exhausted: Cell, -+ -+ /// [`ParseOptions::speculation_budget`], with `u64::MAX` for no limit. -+ speculation_limit: u64, -+ -+ /// Parsing reached [`ParseOptions::speculation_budget`]. -+ speculation_budget_exhausted: bool, } impl<'a, C: ParserConfig> ParserImpl<'a, C> { -@@ -602,6 +650,13 @@ +@@ -589,7 +633,8 @@ + source_type, + config.lexer_config(), + brand_origin, +- ), ++ ) ++ .with_speculation_budget(options.speculation_budget), + source_type, + source_text, + errors: vec![], +@@ -602,6 +647,7 @@ ast: ParserAstBuilder::new(allocator), module_record_builder: ModuleRecordBuilder::new(allocator, source_type), is_ts: source_type.is_typescript(), + stack_exhausted: Cell::new(false), -+ speculation_limit: if options.speculation_budget == 0 { -+ u64::MAX -+ } else { -+ options.speculation_budget -+ }, -+ speculation_budget_exhausted: false, } } -@@ -719,6 +774,8 @@ +@@ -719,6 +765,9 @@ tokens, fatal_error: has_fatal_error, is_flow_language, + stack_exhausted: self.stack_exhausted.get(), -+ speculation_budget_exhausted: self.speculation_budget_exhausted, ++ speculation_budget_exhausted: self.lexer.speculation_budget_exhausted() ++ && !self.stack_exhausted.get(), } } +--- a/src/state.rs ++++ b/src/state.rs +@@ -43,6 +43,13 @@ + /// Like `cover_elements`, each cover list owns the entries above its recorded length. + pub cover_parenthesized: ArenaVec<'a, u32>, + ++ /// The start of the `ParenthesizedExpression` built last, and the start of the expression ++ /// innermost in its parentheses. A chain of parentheses, `((a))`, reads its innermost ++ /// expression's start from here instead of walking the chain at each level, which is ++ /// 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), ++ + /// Zero outside speculative expression type arguments; otherwise their nesting depth. + pub type_argument_depth: u32, + +@@ -81,6 +88,7 @@ + mentions_await: false, + cover_depth: 0, + cover_parenthesized: ArenaVec::new_in(&allocator), ++ last_parenthesized: (u32::MAX, u32::MAX), + 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 071a4d24d..d595db26e 100644 --- a/vendor/oxc_parser/src/cursor.rs +++ b/vendor/oxc_parser/src/cursor.rs @@ -123,7 +123,7 @@ impl<'a, C: Config> ParserImpl<'a, C> { #[inline] fn check_parse_limits(&mut self) { if self.stack_exhausted.get() - || self.speculation_budget_exhausted + || self.lexer.speculation_budget_exhausted() || self.below_stack_floor() { self.stop_at_parse_limit(); @@ -149,7 +149,7 @@ impl<'a, C: Config> ParserImpl<'a, C> { #[cold] #[inline(never)] fn stop_at_parse_limit(&mut self) { - if self.speculation_budget_exhausted && !self.stack_exhausted.get() { + if self.lexer.speculation_budget_exhausted() && !self.stack_exhausted.get() { self.set_fatal_error(diagnostics::speculation_budget_exhausted(self.token.span())); } else { self.stop_at_stack_floor(); @@ -451,24 +451,12 @@ impl<'a, C: Config> ParserImpl<'a, C> { self.lexer.errors.push(fatal_error.error); } self.lexer.rewind(lexer); - self.check_speculation_budget(); self.token = cur_token; self.prev_token_end = prev_token_end; self.errors.truncate(errors_pos); self.state.cover_parenthesized.truncate(cover_parenthesized_len); } - /// Sets the budget's stop once the work spent on speculation passes it: - /// the bytes the lexer has read beyond its position, which a rewind made - /// it read or will make it read again. A parse already stopped at the - /// stack floor is unwinding, and reads nothing again. - #[inline] - fn check_speculation_budget(&mut self) { - if !self.stack_exhausted.get() && self.lexer.bytes_read_ahead() > self.speculation_limit { - self.speculation_budget_exhausted = true; - } - } - /// Rewind to `checkpoint`, keeping the comments and irregular whitespace lexed after it. /// Only for when the source after `checkpoint` is not all lexed again. pub(crate) fn rewind_keeping_trivia(&mut self, mut checkpoint: ParserCheckpoint<'a>) { diff --git a/vendor/oxc_parser/src/js/arrow.rs b/vendor/oxc_parser/src/js/arrow.rs index b4aa6b7a2..7771585b4 100644 --- a/vendor/oxc_parser/src/js/arrow.rs +++ b/vendor/oxc_parser/src/js/arrow.rs @@ -185,6 +185,7 @@ impl<'a, C: Config> ParserImpl<'a, C> { } let expression = Expression::new_identifier(span, name, self); let expression = if self.options.preserve_parens { + self.state.last_parenthesized = (start, span.start); Expression::new_parenthesized_expression(self.end_span(start), expression, self) } else { expression diff --git a/vendor/oxc_parser/src/js/cover.rs b/vendor/oxc_parser/src/js/cover.rs index ed42b8c99..ac283dd9e 100644 --- a/vendor/oxc_parser/src/js/cover.rs +++ b/vendor/oxc_parser/src/js/cover.rs @@ -797,18 +797,34 @@ impl<'a, C: Config> ParserImpl<'a, C> { // Record where the innermost expression starts, which is what an enclosing check // finds: inner parentheses leave no node without `preserve_parens`, and an assignment // target drops them in `((a)) = b`. + let innermost = self.innermost_parenthesized_start(&expression); self.state.cover_parenthesized.truncate(parenthesized_base); if self.state.cover_depth > 0 { - self.state.cover_parenthesized.push(expression.without_parentheses().span().start); + self.state.cover_parenthesized.push(innermost); } if self.options.preserve_parens { + self.state.last_parenthesized = (start, innermost); Expression::new_parenthesized_expression(self.end_span(start), expression, self) } else { expression } } + /// Where the expression innermost in the parentheses around `expression` starts: the + /// start of `expression` without the `ParenthesizedExpression`s that wrap it. + #[inline] + pub(super) fn innermost_parenthesized_start(&self, expression: &Expression<'a>) -> u32 { + match expression { + Expression::ParenthesizedExpression(inner) + if inner.span.start == self.state.last_parenthesized.0 => + { + self.state.last_parenthesized.1 + } + expression => expression.without_parentheses().span().start, + } + } + /// Refine the elements of a cover list to the sequence expression `a, b`. #[inline(never)] fn cover_elements_to_sequence_expression( diff --git a/vendor/oxc_parser/src/js/expression.rs b/vendor/oxc_parser/src/js/expression.rs index f0d5f7715..2a3cd103d 100644 --- a/vendor/oxc_parser/src/js/expression.rs +++ b/vendor/oxc_parser/src/js/expression.rs @@ -408,6 +408,7 @@ impl<'a, C: Config> ParserImpl<'a, C> { } if self.options.preserve_parens { + self.state.last_parenthesized = (start, self.innermost_parenthesized_start(&expression)); Expression::new_parenthesized_expression(self.end_span(start), expression, self) } else { expression diff --git a/vendor/oxc_parser/src/lexer/mod.rs b/vendor/oxc_parser/src/lexer/mod.rs index 2e6c9d275..952831620 100644 --- a/vendor/oxc_parser/src/lexer/mod.rs +++ b/vendor/oxc_parser/src/lexer/mod.rs @@ -137,6 +137,13 @@ pub struct Lexer<'a, C: Config> { /// Bytes the lexer has skipped without reading, by moving to the end of /// the source after a fatal error. bytes_skipped: u64, + + /// `ParseOptions::speculation_budget`, with `u64::MAX` for no limit. + speculation_limit: u64, + + /// 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> { @@ -185,9 +192,25 @@ impl<'a, C: Config> Lexer<'a, C> { config, bytes_rewound: 0, bytes_skipped: 0, + speculation_limit: u64::MAX, + 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 { + self.speculation_limit = if budget == 0 { u64::MAX } else { budget }; + self + } + + /// 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] + pub(crate) fn speculation_budget_exhausted(&self) -> bool { + self.speculation_budget_exhausted + } + /// 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` @@ -251,13 +274,16 @@ impl<'a, C: Config> Lexer<'a, C> { let from = self.offset(); self.source.set_position(checkpoint.source_position); self.bytes_rewound += u64::from(from.saturating_sub(self.offset())); + if self.bytes_read_ahead() > self.speculation_limit { + self.speculation_budget_exhausted = true; + } self.trivia_builder.rewind(checkpoint.trivia); } /// Bytes the lexer has read beyond its current position: those it read /// and then rewound over, less those it skipped without reading. In all /// it has read at most its position plus this many bytes. - pub(crate) fn bytes_read_ahead(&self) -> u64 { + fn bytes_read_ahead(&self) -> u64 { self.bytes_rewound.saturating_sub(self.bytes_skipped) } diff --git a/vendor/oxc_parser/src/lib.rs b/vendor/oxc_parser/src/lib.rs index 0241e356c..88385cd74 100644 --- a/vendor/oxc_parser/src/lib.rs +++ b/vendor/oxc_parser/src/lib.rs @@ -228,7 +228,9 @@ pub struct ParserReturn<'a> { pub stack_exhausted: bool, /// Whether parsing stopped at [`ParseOptions::speculation_budget`]. - /// [`fatal_error`](ParserReturn::fatal_error) is set too. + /// [`fatal_error`](ParserReturn::fatal_error) is set too. A parse that + /// reached [`ParseOptions::stack_floor`] reports only that: on a larger + /// stack it is checked against the budget again. pub speculation_budget_exhausted: bool, } @@ -605,12 +607,6 @@ struct ParserImpl<'a, C: ParserConfig> { /// Parsing reached [`ParseOptions::stack_floor`]. A `Cell`, so that a /// check that reads no token and borrows the parser can record it. stack_exhausted: Cell, - - /// [`ParseOptions::speculation_budget`], with `u64::MAX` for no limit. - speculation_limit: u64, - - /// Parsing reached [`ParseOptions::speculation_budget`]. - speculation_budget_exhausted: bool, } impl<'a, C: ParserConfig> ParserImpl<'a, C> { @@ -637,7 +633,8 @@ impl<'a, C: ParserConfig> ParserImpl<'a, C> { source_type, config.lexer_config(), brand_origin, - ), + ) + .with_speculation_budget(options.speculation_budget), source_type, source_text, errors: vec![], @@ -651,12 +648,6 @@ impl<'a, C: ParserConfig> ParserImpl<'a, C> { module_record_builder: ModuleRecordBuilder::new(allocator, source_type), is_ts: source_type.is_typescript(), stack_exhausted: Cell::new(false), - speculation_limit: if options.speculation_budget == 0 { - u64::MAX - } else { - options.speculation_budget - }, - speculation_budget_exhausted: false, } } @@ -775,7 +766,8 @@ impl<'a, C: ParserConfig> ParserImpl<'a, C> { fatal_error: has_fatal_error, is_flow_language, stack_exhausted: self.stack_exhausted.get(), - speculation_budget_exhausted: self.speculation_budget_exhausted, + speculation_budget_exhausted: self.lexer.speculation_budget_exhausted() + && !self.stack_exhausted.get(), } } diff --git a/vendor/oxc_parser/src/state.rs b/vendor/oxc_parser/src/state.rs index d782a7ce8..3215914b0 100644 --- a/vendor/oxc_parser/src/state.rs +++ b/vendor/oxc_parser/src/state.rs @@ -43,6 +43,13 @@ pub struct ParserState<'a> { /// Like `cover_elements`, each cover list owns the entries above its recorded length. pub cover_parenthesized: ArenaVec<'a, u32>, + /// The start of the `ParenthesizedExpression` built last, and the start of the expression + /// innermost in its parentheses. A chain of parentheses, `((a))`, reads its innermost + /// expression's start from here instead of walking the chain at each level, which is + /// 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), + /// Zero outside speculative expression type arguments; otherwise their nesting depth. pub type_argument_depth: u32, @@ -81,6 +88,7 @@ impl<'a> ParserState<'a> { mentions_await: false, cover_depth: 0, cover_parenthesized: ArenaVec::new_in(&allocator), + last_parenthesized: (u32::MAX, u32::MAX), type_argument_depth: 0, type_argument_lookahead: None, cover_initialized_name: FxHashMap::default(), From b7199b3956cd1421f79583f71ce2e410ed2859b6 Mon Sep 17 00:00:00 2001 From: Tolga Ergin Date: Wed, 25 Nov 2026 01:41:48 +0000 Subject: [PATCH 3/4] Walk member chains in loops, check the floor in SimpleAssignmentTarget::cover, and test the async speculation MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The parser reads a member chain in a loop, so it uses no stack per member. Two functions then recursed once per member: 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, and a release build relied on the optimizer turning the tail calls into loops. Both are loops now. SimpleAssignmentTarget::cover, which nested parentheses recurse through without passing AssignmentTarget::cover, checks the floor too. The arguments of an `async(…)` that mention `await` are parsed again as parameters when `=>` follows, so nesting such heads in their defaults still makes JavaScript speculate quadratically: 500 bytes read again per byte at 1,000 levels. The budget stops it. A test now covers it, and the budget's documentation no longer says only TypeScript speculates. Co-Authored-By: Claude Opus 5.5 --- crates/lpm-security/src/behavioral/mod.rs | 27 ++++ crates/lpm-security/src/behavioral/syntax.rs | 48 ++++++- vendor/oxc_parser/LPM-PATCH.md | 25 +++- vendor/oxc_parser/lpm-stack-floor.patch | 133 ++++++++++++++++++- vendor/oxc_parser/src/js/expression.rs | 50 +++---- vendor/oxc_parser/src/js/grammar.rs | 4 + vendor/oxc_parser/src/jsx/mod.rs | 42 +++--- 7 files changed, 271 insertions(+), 58 deletions(-) diff --git a/crates/lpm-security/src/behavioral/mod.rs b/crates/lpm-security/src/behavioral/mod.rs index 2c1346df3..c26ca08cf 100644 --- a/crates/lpm-security/src/behavioral/mod.rs +++ b/crates/lpm-security/src/behavioral/mod.rs @@ -3512,6 +3512,33 @@ mod tests { ); } + #[test] + fn async_arrow_heads_that_mention_await_nested_in_defaults_are_read_without_parsing_in_linear_time() + { + // The arguments of an `async(…)` that mention `await` are parsed + // again as parameters when `=>` follows, with every head nested in + // their defaults. + let source = format!( + "x={};eval(y);", + nested("async(a=", "await 0", ")=>0", 3_000) + ); + assert!(syntax::exhausts_the_speculation_budget("index.js", &source)); + let flat = format!("{}eval(y);", "x;".repeat(source.len() / 2)); + let started = std::time::Instant::now(); + let flat_result = analyze_on_a_worker_stack("index.js", flat); + let flat_time = started.elapsed(); + let started = std::time::Instant::now(); + let result = analyze_on_a_worker_stack("index.js", source); + let nested_time = started.elapsed(); + assert_eq!(flat_result.unparsed_files, 0); + assert!(result.source.eval); + assert_eq!(result.unparsed_files, 1); + assert!( + nested_time < flat_time * 5 + std::time::Duration::from_millis(200), + "nested {nested_time:?}, flat {flat_time:?}" + ); + } + #[test] fn arrow_heads_after_many_lexer_errors_are_analyzed_in_linear_time() { // A checkpoint taken at each parenthesized list that may be arrow diff --git a/crates/lpm-security/src/behavioral/syntax.rs b/crates/lpm-security/src/behavioral/syntax.rs index 1054ac219..9b299b80a 100644 --- a/crates/lpm-security/src/behavioral/syntax.rs +++ b/crates/lpm-security/src/behavioral/syntax.rs @@ -67,9 +67,10 @@ const RESOLUTION_LOOKUPS_FLOOR: u64 = 1 << 20; /// Work the parser may spend on speculative parses, per byte of source and /// for any source: the bytes it reads again after rewinds. A TypeScript `<` /// that may open a generic arrow function or type arguments is parsed one -/// way and, when that fails, parsed again the other way with all it holds, -/// so nested speculation can make parsing quadratic. Real code spends under -/// one per byte. +/// way and, when that fails, parsed again the other way with all it holds. +/// The arguments of an `async(…)` that mention `await` are parsed again as +/// parameters when `=>` follows. Nested speculation can make parsing +/// quadratic. Real code spends under one per byte. const PARSE_SPECULATION_PER_BYTE: u64 = 2; const PARSE_SPECULATION_FLOOR: u64 = 64 * 1024; @@ -617,13 +618,14 @@ mod tests { // through them without reading a token. At the deepest nesting the // parse fits above the floor, that recursion must fit too. let (js, ts) = (SourceType::cjs(), SourceType::ts()); - let shapes: [(SourceType, &str, &str, &str, &str, &str); 16] = [ + let shapes: [(SourceType, &str, &str, &str, &str, &str); 17] = [ (js, "x=(", "[", "a", "]", ");"), (js, "x=(", "[", "a", "]", "=0);"), (js, "x=(", "{a:", "b", "}", ");"), (js, "x=(", "{a:", "b", "}", "=0);"), (js, "x=(", "[a=", "0", "]", ");"), (js, "x=(", "[", "a", "]", ",b);"), + (js, "x=", "(", "a", ")", "=0;"), (js, "x=(", "[", "a", "]", ")=>0;"), (js, "x=(", "[", "a", "]", "=0)=>0;"), (js, "x=(", "{a:", "b", "}", ")=>0;"), @@ -670,6 +672,44 @@ mod tests { } } + #[test] + fn pure_comments_and_jsx_names_on_member_chains_of_any_length_parse_without_overflowing() { + // The parser reads a member chain without recursing, so what runs + // over the chain afterwards must not recurse once per member either. + for (filename, source) in [ + ( + "index.js", + format!("x=/*#__PURE__*/a{};", ".a".repeat(200_000)), + ), + ( + "index.jsx", + format!("x=;", ".b".repeat(200_000)), + ), + ] { + let parsed = std::thread::Builder::new() + .stack_size(8 * 1024 * 1024) + .spawn(move || { + let allocator = Allocator::default(); + let source_type = SourceType::from_path(filename).unwrap(); + let parsed = Parser::new(&allocator, &source, source_type) + .with_options(ParseOptions { + stack_floor: current_stack_floor().unwrap(), + ..ParseOptions::default() + }) + .parse(); + ( + parsed.stack_exhausted, + parsed.fatal_error, + parsed.diagnostics.has_errors(), + ) + }) + .unwrap() + .join() + .unwrap(); + assert_eq!(parsed, (false, false, false), "{filename}"); + } + } + #[test] fn lookahead_that_reads_past_the_speculation_budget_stops_the_parse() { // Deciding whether `(` starts a function type reads tokens ahead and diff --git a/vendor/oxc_parser/LPM-PATCH.md b/vendor/oxc_parser/LPM-PATCH.md index 3612f9a44..82223331f 100644 --- a/vendor/oxc_parser/LPM-PATCH.md +++ b/vendor/oxc_parser/LPM-PATCH.md @@ -3,9 +3,9 @@ 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, and at a budget for -the work it spends on speculative parses, and nested parentheses take it -linear time. The workspace uses it through `[patch.crates-io]` in the root +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 `Cargo.toml`. ## Why @@ -19,9 +19,11 @@ registry's release scan. The parser also speculates. In TypeScript, a `<` that may open a generic arrow function or type arguments is parsed one way and, when that fails, -rewound and parsed again the other way, with everything nested in it. -Nested speculation can make a parse take time quadratic in the source's -length: `x=(a=(a=…0)));` reads each level again for every level +rewound and parsed again the other way, with everything nested in it. The +arguments of an `async(…)` that mention `await` are parsed again as +parameters when `=>` follows. Nested speculation can make a parse take time +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 @@ -47,7 +49,9 @@ stack, took four seconds. the floor once per level themselves, because their frames per level can be larger than those of the parse that built the nodes: - the cover grammar that turns an expression into a destructuring - assignment target (`AssignmentTarget::cover` in `js/grammar.rs`); + assignment target (`AssignmentTarget::cover` in `js/grammar.rs`, and + `SimpleAssignmentTarget::cover`, which nested parentheses recurse + through on their own); - the conversions that turn the elements of a parenthesized list into arrow parameters once `=>` follows it (`cover_expression_to_binding_pattern` and @@ -79,6 +83,13 @@ stack, took four seconds. `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::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 diff --git a/vendor/oxc_parser/lpm-stack-floor.patch b/vendor/oxc_parser/lpm-stack-floor.patch index 4dc714811..f94efc95b 100644 --- a/vendor/oxc_parser/lpm-stack-floor.patch +++ b/vendor/oxc_parser/lpm-stack-floor.patch @@ -194,6 +194,67 @@ Expression::new_parenthesized_expression(self.end_span(start), expression, self) } else { expression +@@ -1939,34 +1940,36 @@ + } + } + +- fn set_pure_on_call_or_new_expr(expr: &mut Expression<'a>) -> bool { +- match expr.get_inner_expression_mut() { +- Expression::CallExpression(call_expr) => { +- call_expr.pure = true; +- true +- } +- Expression::NewExpression(new_expr) => { +- new_expr.pure = true; +- true +- } +- expr @ match_member_expression!(Expression) => { +- Self::set_pure_on_call_or_new_expr(expr.to_member_expression_mut().object_mut()) +- } +- 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() { ++ Expression::CallExpression(call_expr) => { + call_expr.pure = true; +- true ++ return true; + } +- element @ match_member_expression!(ChainElement) => { +- Self::set_pure_on_call_or_new_expr( +- element.to_member_expression_mut().object_mut(), +- ) ++ Expression::NewExpression(new_expr) => { ++ new_expr.pure = true; ++ return true; + } +- ChainElement::TSNonNullExpression(non_null_expr) => { +- Self::set_pure_on_call_or_new_expr(&mut non_null_expr.expression) ++ expr @ match_member_expression!(Expression) => { ++ expr.to_member_expression_mut().object_mut() + } +- }, +- _ => false, ++ Expression::ChainExpression(chain_expr) => match &mut chain_expr.expression { ++ ChainElement::CallExpression(call_expr) => { ++ call_expr.pure = true; ++ return true; ++ } ++ element @ match_member_expression!(ChainElement) => { ++ element.to_member_expression_mut().object_mut() ++ } ++ ChainElement::TSNonNullExpression(non_null_expr) => { ++ &mut non_null_expr.expression ++ } ++ }, ++ _ => return false, ++ }; + } + } + --- a/src/js/grammar.rs +++ b/src/js/grammar.rs @@ -14,6 +14,11 @@ @@ -208,7 +269,18 @@ match expr { Expression::ArrayExpression(array_expr) => { let pat = ArrayAssignmentTarget::cover(array_expr.unbox(), p); -@@ -303,6 +308,12 @@ +@@ -30,6 +35,10 @@ + + impl<'a, C: Config> CoverGrammar<'a, Expression<'a>, C> for SimpleAssignmentTarget<'a> { + fn cover(expr: Expression<'a>, p: &mut ParserImpl<'a, C>) -> Self { ++ // Nested parentheses recurse here without passing through `AssignmentTarget::cover`. ++ if p.below_stack_floor() { ++ return p.stopped_at_stack_floor(); ++ } + match expr { + Expression::Identifier(ident) => { + SimpleAssignmentTarget::AssignmentTargetIdentifier(ident) +@@ -303,6 +312,12 @@ /// Check that `expression` covers a `BindingIdentifier` or a `BindingPattern`. pub(super) fn check_cover_binding(&self, expression: &Expression<'a>) -> CoverCheck<'a> { @@ -221,7 +293,7 @@ match expression { Expression::Identifier(ident) if !self.is_cover_parenthesized(ident.span.start) => { Ok(()) -@@ -376,6 +387,9 @@ +@@ -376,6 +391,9 @@ /// Check that an assignment target, which an expression was already refined to, covers /// a `BindingIdentifier` or a `BindingPattern`. fn check_cover_binding_target(&self, target: &AssignmentTarget<'a>) -> CoverCheck<'a> { @@ -231,7 +303,7 @@ match target { AssignmentTarget::AssignmentTargetIdentifier(ident) if !self.is_cover_parenthesized(ident.span.start) => -@@ -452,6 +466,9 @@ +@@ -452,6 +470,9 @@ &mut self, expression: Expression<'a>, ) -> BindingPattern<'a> { @@ -241,7 +313,7 @@ match expression { Expression::Identifier(ident) => { BindingPattern::new_binding_identifier(ident.span, ident.name, self) -@@ -555,6 +572,9 @@ +@@ -555,6 +576,9 @@ &mut self, target: AssignmentTarget<'a>, ) -> BindingPattern<'a> { @@ -251,6 +323,59 @@ match target { AssignmentTarget::AssignmentTargetIdentifier(ident) => { BindingPattern::new_binding_identifier(ident.span, ident.name, self) +--- a/src/jsx/mod.rs ++++ b/src/jsx/mod.rs +@@ -661,27 +661,31 @@ + } + } + ++ /// Compares the names in a loop: the parser reads `` without recursing, so ++ /// recursing once per member here could overflow the stack. + fn jsx_member_expression_eq( +- lhs: &JSXMemberExpression<'a>, +- rhs: &JSXMemberExpression<'a>, ++ mut lhs: &JSXMemberExpression<'a>, ++ mut rhs: &JSXMemberExpression<'a>, + ) -> bool { +- if lhs.property.name != rhs.property.name { +- return false; +- } +- match (&lhs.object, &rhs.object) { +- ( +- JSXMemberExpressionObject::IdentifierReference(lhs), +- JSXMemberExpressionObject::IdentifierReference(rhs), +- ) => lhs.name == rhs.name, +- ( +- JSXMemberExpressionObject::MemberExpression(lhs), +- JSXMemberExpressionObject::MemberExpression(rhs), +- ) => Self::jsx_member_expression_eq(lhs, rhs), +- ( +- JSXMemberExpressionObject::ThisExpression(_), +- JSXMemberExpressionObject::ThisExpression(_), +- ) => true, +- _ => false, ++ loop { ++ if lhs.property.name != rhs.property.name { ++ return false; ++ } ++ (lhs, rhs) = match (&lhs.object, &rhs.object) { ++ ( ++ JSXMemberExpressionObject::IdentifierReference(lhs), ++ JSXMemberExpressionObject::IdentifierReference(rhs), ++ ) => return lhs.name == rhs.name, ++ ( ++ JSXMemberExpressionObject::MemberExpression(lhs), ++ JSXMemberExpressionObject::MemberExpression(rhs), ++ ) => (lhs, rhs), ++ ( ++ JSXMemberExpressionObject::ThisExpression(_), ++ JSXMemberExpressionObject::ThisExpression(_), ++ ) => return true, ++ _ => return false, ++ }; + } + } + } --- a/src/lexer/mod.rs +++ b/src/lexer/mod.rs @@ -130,6 +130,20 @@ diff --git a/vendor/oxc_parser/src/js/expression.rs b/vendor/oxc_parser/src/js/expression.rs index 2a3cd103d..2b1eeb978 100644 --- a/vendor/oxc_parser/src/js/expression.rs +++ b/vendor/oxc_parser/src/js/expression.rs @@ -1940,34 +1940,36 @@ impl<'a, C: Config> ParserImpl<'a, C> { } } - fn set_pure_on_call_or_new_expr(expr: &mut Expression<'a>) -> bool { - match expr.get_inner_expression_mut() { - Expression::CallExpression(call_expr) => { - call_expr.pure = true; - true - } - Expression::NewExpression(new_expr) => { - new_expr.pure = true; - true - } - expr @ match_member_expression!(Expression) => { - Self::set_pure_on_call_or_new_expr(expr.to_member_expression_mut().object_mut()) - } - 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() { + Expression::CallExpression(call_expr) => { call_expr.pure = true; - true + return true; } - element @ match_member_expression!(ChainElement) => { - Self::set_pure_on_call_or_new_expr( - element.to_member_expression_mut().object_mut(), - ) + Expression::NewExpression(new_expr) => { + new_expr.pure = true; + return true; } - ChainElement::TSNonNullExpression(non_null_expr) => { - Self::set_pure_on_call_or_new_expr(&mut non_null_expr.expression) + expr @ match_member_expression!(Expression) => { + expr.to_member_expression_mut().object_mut() } - }, - _ => false, + Expression::ChainExpression(chain_expr) => match &mut chain_expr.expression { + ChainElement::CallExpression(call_expr) => { + call_expr.pure = true; + return true; + } + element @ match_member_expression!(ChainElement) => { + element.to_member_expression_mut().object_mut() + } + ChainElement::TSNonNullExpression(non_null_expr) => { + &mut non_null_expr.expression + } + }, + _ => return false, + }; } } diff --git a/vendor/oxc_parser/src/js/grammar.rs b/vendor/oxc_parser/src/js/grammar.rs index d2b418994..149c4e523 100644 --- a/vendor/oxc_parser/src/js/grammar.rs +++ b/vendor/oxc_parser/src/js/grammar.rs @@ -35,6 +35,10 @@ impl<'a, C: Config> CoverGrammar<'a, Expression<'a>, C> for AssignmentTarget<'a> impl<'a, C: Config> CoverGrammar<'a, Expression<'a>, C> for SimpleAssignmentTarget<'a> { fn cover(expr: Expression<'a>, p: &mut ParserImpl<'a, C>) -> Self { + // Nested parentheses recurse here without passing through `AssignmentTarget::cover`. + if p.below_stack_floor() { + return p.stopped_at_stack_floor(); + } match expr { Expression::Identifier(ident) => { SimpleAssignmentTarget::AssignmentTargetIdentifier(ident) diff --git a/vendor/oxc_parser/src/jsx/mod.rs b/vendor/oxc_parser/src/jsx/mod.rs index b80fd77fa..24417ab12 100644 --- a/vendor/oxc_parser/src/jsx/mod.rs +++ b/vendor/oxc_parser/src/jsx/mod.rs @@ -661,27 +661,31 @@ impl<'a, C: Config> ParserImpl<'a, C> { } } + /// Compares the names in a loop: the parser reads `` without recursing, so + /// recursing once per member here could overflow the stack. fn jsx_member_expression_eq( - lhs: &JSXMemberExpression<'a>, - rhs: &JSXMemberExpression<'a>, + mut lhs: &JSXMemberExpression<'a>, + mut rhs: &JSXMemberExpression<'a>, ) -> bool { - if lhs.property.name != rhs.property.name { - return false; - } - match (&lhs.object, &rhs.object) { - ( - JSXMemberExpressionObject::IdentifierReference(lhs), - JSXMemberExpressionObject::IdentifierReference(rhs), - ) => lhs.name == rhs.name, - ( - JSXMemberExpressionObject::MemberExpression(lhs), - JSXMemberExpressionObject::MemberExpression(rhs), - ) => Self::jsx_member_expression_eq(lhs, rhs), - ( - JSXMemberExpressionObject::ThisExpression(_), - JSXMemberExpressionObject::ThisExpression(_), - ) => true, - _ => false, + loop { + if lhs.property.name != rhs.property.name { + return false; + } + (lhs, rhs) = match (&lhs.object, &rhs.object) { + ( + JSXMemberExpressionObject::IdentifierReference(lhs), + JSXMemberExpressionObject::IdentifierReference(rhs), + ) => return lhs.name == rhs.name, + ( + JSXMemberExpressionObject::MemberExpression(lhs), + JSXMemberExpressionObject::MemberExpression(rhs), + ) => (lhs, rhs), + ( + JSXMemberExpressionObject::ThisExpression(_), + JSXMemberExpressionObject::ThisExpression(_), + ) => return true, + _ => return false, + }; } } } From 6c8467c80fc6d5c67af315b4764c1addabe4ef15 Mon Sep 17 00:00:00 2001 From: Tolga Ergin Date: Wed, 25 Nov 2026 01:52:50 +0000 Subject: [PATCH 4/4] Drop recorded literals by range when async arguments are parsed again, and match template keys MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Before parsing the arguments of an `async(…)` that mention `await` again as parameters, oxc 0.160 walked every entry recorded for a literal ending in a spread and a comma, or for a CoverInitializedName, anywhere before them, while reading almost nothing again. Neither map forgets entries no conversion consumes, so a 4 MiB file of `[...a,];` and `async(await)=>0;` took about 25 seconds without reaching the speculation budget. Both maps are ordered now, and the entries inside the arguments are split off: that file parses in 57 ms. destructured_methods also reads a key written as a template without substitutions, so `const {[`rmSync`]: remove} = require('fs')` keeps its method. Co-Authored-By: Claude Opus 5.5 --- crates/lpm-security/src/behavioral/syntax.rs | 63 +++++++++++++------ crates/lpm-security/src/behavioral/threats.rs | 1 + .../src/behavioral/threats/archive_tests.rs | 2 +- vendor/oxc_parser/LPM-PATCH.md | 13 +++- vendor/oxc_parser/lpm-stack-floor.patch | 52 ++++++++++++++- vendor/oxc_parser/src/js/arrow.rs | 4 +- vendor/oxc_parser/src/state.rs | 17 +++-- 7 files changed, 119 insertions(+), 33 deletions(-) diff --git a/crates/lpm-security/src/behavioral/syntax.rs b/crates/lpm-security/src/behavioral/syntax.rs index 9b299b80a..d73049fa4 100644 --- a/crates/lpm-security/src/behavioral/syntax.rs +++ b/crates/lpm-security/src/behavioral/syntax.rs @@ -726,30 +726,33 @@ mod tests { assert!(parsed.fatal_error); } + /// How long parsing `source`, which is valid, takes on a stack deep + /// enough for it. + fn time_to_parse(source: String) -> 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()) + .with_options(ParseOptions { + stack_floor: current_stack_floor().unwrap(), + ..ParseOptions::default() + }) + .parse(); + let elapsed = started.elapsed(); + assert!(!parsed.stack_exhausted && !parsed.fatal_error); + elapsed + }) + .unwrap() + .join() + .unwrap() + } + #[test] fn parentheses_nested_tens_of_thousands_of_levels_deep_parse_in_linear_time() { // Each closing parenthesis records where the expression innermost in // it starts, and must not walk every parenthesis inside it to find it. - let time_to_parse = |source: String| { - 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()) - .with_options(ParseOptions { - stack_floor: current_stack_floor().unwrap(), - ..ParseOptions::default() - }) - .parse(); - let elapsed = started.elapsed(); - assert!(!parsed.stack_exhausted && !parsed.fatal_error); - elapsed - }) - .unwrap() - .join() - .unwrap() - }; 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)); @@ -759,6 +762,26 @@ mod tests { ); } + #[test] + fn async_arrow_heads_parsed_again_after_many_spread_literals_parse_in_linear_time() { + // Parsing the arguments of an `async(…)` again as parameters forgets + // what was recorded about the literals inside them, and must not walk + // what was recorded about every literal before them. + let literals = 32_768; + let source = format!( + "{}{}", + "[...a,];".repeat(literals), + "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); + assert!( + parsed_again < flat * 5 + std::time::Duration::from_millis(200), + "parsed again {parsed_again:?}, flat {flat:?}" + ); + } + /// Visits `source` with the floor `room` bytes below where the visit /// starts, on a stack deep enough to parse it, and returns whether the /// visitor stopped at the floor and whether it unwound. diff --git a/crates/lpm-security/src/behavioral/threats.rs b/crates/lpm-security/src/behavioral/threats.rs index 33316a834..4eb8a0999 100644 --- a/crates/lpm-security/src/behavioral/threats.rs +++ b/crates/lpm-security/src/behavioral/threats.rs @@ -662,6 +662,7 @@ fn destructured_methods<'a>(semantic: &Semantic<'a>) -> HashMap { key.value.as_str() } + PropertyKey::TemplateLiteral(key) => key.single_quasi().and_then(JSStr::as_str), _ => None, }; if let Some(name) = name diff --git a/crates/lpm-security/src/behavioral/threats/archive_tests.rs b/crates/lpm-security/src/behavioral/threats/archive_tests.rs index 15f50c44b..ed15e7b6b 100644 --- a/crates/lpm-security/src/behavioral/threats/archive_tests.rs +++ b/crates/lpm-security/src/behavioral/threats/archive_tests.rs @@ -154,7 +154,7 @@ fn aliased_filesystem_methods_keep_their_imported_identity() { "import {rmSync as remove} from 'node:fs'; import {homedir as home} from 'node:os'; remove(home(),{recursive:true});", "destructiveFilesystem" )); - for key in ["rmSync", "'rmSync'", "['rmSync']"] { + for key in ["rmSync", "'rmSync'", "['rmSync']", "[`rmSync`]"] { let source = format!( "const {{{key}:remove}}=require('fs'); const os=require('os'); remove(os.homedir(),{{recursive:true}});" ); diff --git a/vendor/oxc_parser/LPM-PATCH.md b/vendor/oxc_parser/LPM-PATCH.md index 82223331f..3c7824948 100644 --- a/vendor/oxc_parser/LPM-PATCH.md +++ b/vendor/oxc_parser/LPM-PATCH.md @@ -29,7 +29,11 @@ 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. +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. ## What changed @@ -90,6 +94,9 @@ stack, took four seconds. 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. - `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 @@ -120,7 +127,9 @@ more than 30% of its budget. 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. `lpm-security`'s + 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 `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 diff --git a/vendor/oxc_parser/lpm-stack-floor.patch b/vendor/oxc_parser/lpm-stack-floor.patch index f94efc95b..f996bec54 100644 --- a/vendor/oxc_parser/lpm-stack-floor.patch +++ b/vendor/oxc_parser/lpm-stack-floor.patch @@ -149,6 +149,17 @@ Expression::new_parenthesized_expression(self.end_span(start), expression, self) } else { expression +@@ -373,8 +374,8 @@ + { + // Discard what `rewind` does not restore, and parse the list as parameters. + self.state.cover_elements.truncate(base); +- self.state.cover_initialized_name.retain(|&start, _| start < lparen); +- self.state.trailing_commas.retain(|&start, _| start < lparen); ++ self.state.cover_initialized_name.split_off(&lparen); ++ self.state.trailing_commas.split_off(&lparen); + self.deferred_script_errors.truncate(deferred_script_errors_len); + if !had_module_syntax { + self.module_record_builder.unset_module_syntax(); --- a/src/js/cover.rs +++ b/src/js/cover.rs @@ -797,15 +797,31 @@ @@ -573,7 +584,16 @@ --- a/src/state.rs +++ b/src/state.rs -@@ -43,6 +43,13 @@ +@@ -1,5 +1,7 @@ +-use rustc_hash::{FxHashMap, FxHashSet}; ++use std::collections::BTreeMap; + ++use rustc_hash::FxHashSet; ++ + use oxc_allocator::{Allocator, ArenaVec}; + use oxc_ast::ast::Expression; + use oxc_span::Span; +@@ -43,6 +45,13 @@ /// Like `cover_elements`, each cover list owns the entries above its recorded length. pub cover_parenthesized: ArenaVec<'a, u32>, @@ -587,11 +607,37 @@ /// Zero outside speculative expression type arguments; otherwise their nesting depth. pub type_argument_depth: u32, -@@ -81,6 +88,7 @@ +@@ -51,12 +60,17 @@ + + /// Temporary storage for `CoverInitializedName` `({ foo = bar })`. + /// Keyed by `ObjectProperty`'s span.start. +- pub cover_initialized_name: FxHashMap>, ++ /// ++ /// Ordered, as `trailing_commas` is, so that parsing the arguments of `async(…)` again as ++ /// parameters drops the entries inside them without visiting every entry before them. ++ /// Neither map forgets an entry no conversion consumes, so visiting them all made each ++ /// parse again cost the number of literals before it. ++ pub cover_initialized_name: BTreeMap>, + + /// Trailing comma spans for `ArrayExpression` and `ObjectExpression` ending in a spread. + /// Used for error reporting when covering a rest assignment target. + /// Keyed by the expression start and consumed when checked. +- pub trailing_commas: FxHashMap, ++ pub trailing_commas: BTreeMap, + + /// Statements that may need reparsing when `sourceType` is `unambiguous`. + /// +@@ -81,10 +95,11 @@ mentions_await: false, cover_depth: 0, cover_parenthesized: ArenaVec::new_in(&allocator), + last_parenthesized: (u32::MAX, u32::MAX), type_argument_depth: 0, type_argument_lookahead: None, - cover_initialized_name: FxHashMap::default(), +- cover_initialized_name: FxHashMap::default(), +- trailing_commas: FxHashMap::default(), ++ cover_initialized_name: BTreeMap::new(), ++ trailing_commas: BTreeMap::new(), + potential_await_reparse: Vec::new(), + encountered_await_identifier: false, + } diff --git a/vendor/oxc_parser/src/js/arrow.rs b/vendor/oxc_parser/src/js/arrow.rs index 7771585b4..0c89534e2 100644 --- a/vendor/oxc_parser/src/js/arrow.rs +++ b/vendor/oxc_parser/src/js/arrow.rs @@ -374,8 +374,8 @@ impl<'a, C: Config> ParserImpl<'a, C> { { // Discard what `rewind` does not restore, and parse the list as parameters. self.state.cover_elements.truncate(base); - self.state.cover_initialized_name.retain(|&start, _| start < lparen); - self.state.trailing_commas.retain(|&start, _| start < lparen); + self.state.cover_initialized_name.split_off(&lparen); + self.state.trailing_commas.split_off(&lparen); self.deferred_script_errors.truncate(deferred_script_errors_len); if !had_module_syntax { self.module_record_builder.unset_module_syntax(); diff --git a/vendor/oxc_parser/src/state.rs b/vendor/oxc_parser/src/state.rs index 3215914b0..7facefa4c 100644 --- a/vendor/oxc_parser/src/state.rs +++ b/vendor/oxc_parser/src/state.rs @@ -1,4 +1,6 @@ -use rustc_hash::{FxHashMap, FxHashSet}; +use std::collections::BTreeMap; + +use rustc_hash::FxHashSet; use oxc_allocator::{Allocator, ArenaVec}; use oxc_ast::ast::Expression; @@ -58,12 +60,17 @@ pub struct ParserState<'a> { /// Temporary storage for `CoverInitializedName` `({ foo = bar })`. /// Keyed by `ObjectProperty`'s span.start. - pub cover_initialized_name: FxHashMap>, + /// + /// Ordered, as `trailing_commas` is, so that parsing the arguments of `async(…)` again as + /// parameters drops the entries inside them without visiting every entry before them. + /// Neither map forgets an entry no conversion consumes, so visiting them all made each + /// parse again cost the number of literals before it. + pub cover_initialized_name: BTreeMap>, /// Trailing comma spans for `ArrayExpression` and `ObjectExpression` ending in a spread. /// Used for error reporting when covering a rest assignment target. /// Keyed by the expression start and consumed when checked. - pub trailing_commas: FxHashMap, + pub trailing_commas: BTreeMap, /// Statements that may need reparsing when `sourceType` is `unambiguous`. /// @@ -91,8 +98,8 @@ impl<'a> ParserState<'a> { last_parenthesized: (u32::MAX, u32::MAX), type_argument_depth: 0, type_argument_lookahead: None, - cover_initialized_name: FxHashMap::default(), - trailing_commas: FxHashMap::default(), + cover_initialized_name: BTreeMap::new(), + trailing_commas: BTreeMap::new(), potential_await_reparse: Vec::new(), encountered_await_identifier: false, }