Repository navigation
feat!: use SWC Next for type stripping and remove transform mode - #507
Conversation
|
Amazingg work, does this boost the performance? |
It's now faster for all cases! The swc-next commit I used is swc-project/swc-next@95e2394, and I'll try to find and fix any remaining bugs before merging. |
`deprecatedTsModuleAsError` is enabled by default, and the check parsed the whole input a second time when the text contained "module". Most real files contain that word in `module.exports`, `node:module`, or comments, so most inputs were parsed twice. Run the second parse only when a `module` word is followed by a possible declaration name and that word is erased in the stripped output. `strip_types` erases every `module` declaration as a whole statement, so a keyword that survives unchanged is in a comment, a string, or an expression. Inputs with strip diagnostics keep the previous behavior. Results for 442 corpus variants, including injected declarations, are identical to the previous build. This includes error codes, messages, and locations. Median `transformSync` time in the release WASM build: - hono-types.ts (76 KB): 1.11 ms -> 0.68 ms - checker.ts (3 MB): 34.7 ms -> 21.0 ms - typescript.js (8 MB): 100.7 ms -> 62.9 ms - astro-config.ts (125 KB): 0.97 ms -> 1.05 ms (the parse is still needed because a comment in an erased interface contains "module ...") Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
## Motivation On targets without a native SIMD backend, including `wasm32-unknown-unknown` without `simd128`, `swc_next_simd` processed each 16-byte vector one lane at a time. Loops written with `u8x16` were then much slower than byte loops. Block comment scanning in the lexer and blanking in `strip_types` were affected the most. For example, on a 1 MiB single-line block comment, swc-next parse took 5.4 ms, and the old `swc_ecma_parser` took 0.35 ms. Node.js amaro and the swc-next npm WebAssembly bindings build for this target without `simd128`. ## Changes - The scalar backend now processes each vector as two `u64` words (SWAR). The public API, the per-lane results, and the x86_64, aarch64, and wasm32 `simd128` backends are unchanged. Call sites are unchanged. - The scalar module is now compiled for tests on every host. New tests place every byte pair in every lane position and compare each operation with a per-lane reference. They also cover lane boundaries, `first_set`, and `any`. - On wasm32 without `simd128` (`opt-level = "z"`, fat LTO), compared with `main`: - Parse of a 1 MiB single-line block comment: 5.39 ms → 0.79 ms. - Parse of 1 MiB of JSDoc comments: 2.16 ms → 0.45 ms. - `strip_types` on `tasks/benchmark/files/astro-config.ts`: 0.57 ms → 0.11 ms. - No input is slower. - The `strip_types` output and diagnostics are identical to `main` for 22 inputs: the benchmark files, the inputs from #1418, and edge cases for line terminators, `0xE2` sequences, unterminated comments, and 16-byte boundaries. ## Related Links - Close #1418 - nodejs/amaro#507 Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
`strip_types` erases every `module` declaration, so compare the input with the stripped output and check only `module` words in erased text. This replaces the full-text `match_indices` search and the UTF-16 offset mapping. Also skip a `module` word that follows a non-keyword word on the same line, because it cannot start a statement. This avoids the second parse for prose such as `its module dependency` in comments inside erased interfaces. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
## Motivation Size-optimized builds keep the `#[inline]` wrappers in `swc_simd` as function calls. Amaro builds `swc_next_type_strip` for `wasm32-unknown-unknown` with `opt-level = "z"` and without `simd128`, so the scalar backend runs. In a profile of that build, `simd_eq` and `first_set` stay separate functions inside the block comment scanner, and each call passes a 16-byte vector through memory. A 1 MB block comment on one line takes 2.44 ms with `main`, compared with 1.72 ms on Amaro `main`, which uses `swc_ts_fast_strip`. ## Changes - Mark the vector and mask operations in `crates/swc_simd/src/lib.rs` `#[inline(always)]`, like the backend functions that they call. Behavior does not change. - Amaro `transformSync`, wasm32 without `simd128`, this branch compared with `main` (2fe537f). Medians of 6 rounds, measured locally: | Input | `main` | This PR | Speedup | | --- | ---: | ---: | ---: | | 1 MB block comment, one line | 2.44 ms | 2.19 ms | 1.11× | | 1 MB block comment, many lines | 2.00 ms | 1.91 ms | 1.05× | | 1 MB of JSDoc blocks | 2.14 ms | 2.04 ms | 1.05× | | 1 MB of plain block comments | 2.07 ms | 1.97 ms | 1.05× | | `typescript.js` (8 MB) | 56.61 ms | 54.88 ms | 1.03× | The other measured inputs (jQuery, three.js, `checker.ts`, cal.com, Hono, Effect, and 1 MB string, type, line comment, and whitespace inputs) changed by less than 1.5%. - The output matched the `main` build for 400 inputs: the Amaro benchmark corpus and synthetic inputs, each also with comments, line separators, and whitespace inserted. - `cargo fmt --check`, `cargo clippy -- -D warnings` (host and `wasm32-unknown-unknown`), and the tests of `swc_next_simd`, `swc_next_ecma_parser`, `swc_next_type_strip`, and `swc_next_ecma_codegen` pass. Native wall time was not measured. ## Related Links - #1419 - nodejs/amaro#507 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
|
@marco-ippolito Is removing |
Performance profiling result
|
I think its acceptable as semver major change |
…ckend (#1443) ## Motivation #1422 made block comments slower in Amaro's `wasm32-unknown-unknown` build (`opt-level = "z"`, no `simd128`), which uses the scalar backend. In Amaro `transformSync`, a 1 MB block comment on one line went from 1.87 ms to 5.09 ms. In a profile of that build, `Lexer::scan_block_comment` is no longer inlined into `next_token`. Inside it, `<[u8; 16] as IndexMut<RangeTo<usize>>>::index_mut` stays a separate call and takes 10% of the time. This call comes from `lanes[..8].copy_from_slice(..)` in the scalar backend. `Option::expect` in `Simd::from_slice` also stays a call. The 1 MB comment inputs do not call `TokenReader::read`, so the slowdown comes from code generation, not from extra work. ## Changes - The scalar backend's `lanes()` builds the array by destructuring the two words, and `Simd::from_slice` matches on `first_chunk` instead of calling `expect`. Behavior does not change. Only the scalar backend uses `lanes()`. The `from_slice` change applies to all backends. - Amaro `transformSync`, wasm32 without `simd128`. I measured the same diff locally on `69b31108`. Since then, `main` changed only `crates/swc_type_strip` (#1442). Medians of 4 rounds: | Input | Before #1422 (87adca5) | `69b31108` | `69b31108` + this PR | | --- | ---: | ---: | ---: | | 1 MB block comment, one line | 1.87 ms | 5.09 ms | 1.85 ms | | 1 MB block comment, many lines | 1.69 ms | 2.39 ms | 1.68 ms | | 1 MB of JSDoc blocks | 1.77 ms | 2.56 ms | 1.76 ms | | 1 MB of plain block comments | 1.73 ms | 2.42 ms | 1.71 ms | | Astro config types (125 KB) | 238.1 µs | 320.0 µs | 236.6 µs | | AngularJS 1.2.5 | 3.06 ms | 3.39 ms | 3.02 ms | | YUI 3.12.0 | 1.72 ms | 1.77 ms | 1.72 ms | | `typescript.js` (8 MB) | 49.95 ms | 51.03 ms | 48.89 ms | - For 650 inputs, the output matched the `69b31108` build. The inputs are the Amaro benchmark corpus and synthetic inputs, each also with TypeScript `module` declarations and comments inserted at several positions. - The `swc_next_simd` tests and Amaro's 99 tests pass with this change. `cargo fmt`, `cargo clippy`, and the tests of the other crates were not run locally. Native wall time was not measured. ## Related Links - #1422 - #1426 - nodejs/amaro#507 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
`SourceMap::new_source_file` removes a leading BOM, but SWC Next spans include it. With a BOM, every diagnostic was shifted by three bytes, and a shifted span inside a multi-byte character made snippet rendering panic, which traps in WebAssembly. A BOM before a hashbang also caused an `InvalidSyntax` error. Remove the BOM before stripping, as `swc_ts_fast_strip` did, and clamp diagnostic spans to character boundaries. Sort all diagnostics so that the first reported error is the first one in the source, also for the errors that `validate` adds. Keep an explicit error code with each diagnostic instead of matching messages, and remove the unused `Unsupported transform option` match. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Verification resultsI pushed 558cbb2 to this branch. It fixes a leading-BOM problem and the order of reported errors. This comment covers what I checked and what still needs a decision. What I checked
Open items
|
## Motivation #1443 made the scalar backend's `lanes()` build its `[u8; 16]` result by destructuring two words into 16 bytes. This removed a call from the block comment scanner, but it made string scanning slower in Amaro's `wasm32-unknown-unknown` build (`opt-level = "z"`, no `simd128`). In Amaro `transformSync`, 1 MB of string declarations went from 3.57 ms to 4.45 ms. When I revert only the `lanes()` change, this time returns to 3.57 ms, and the block comment slowdown comes back. When I revert only the `from_slice` change, nothing changes. A possible cause is that the inlined string scanner now does byte-wise work where it had two 8-byte stores before. I did not confirm this in the generated code. ## Changes - `lanes()` converts both words with one `u128::to_le_bytes`. It has no range indexing and no per-byte array. Behavior does not change. Only the scalar backend uses `lanes()`. - Amaro `transformSync`, wasm32 without `simd128`, measured locally. Medians of 4 rounds: | Input | Before #1443 (`69b31108`) | `main` (`0334f9d7`) | This PR | | --- | ---: | ---: | ---: | | 1 MB of string declarations | 3.57 ms | 4.45 ms | 3.58 ms | | 1 MB block comment, one line | 5.09 ms | 1.86 ms | 1.85 ms | | 1 MB block comment, many lines | 2.40 ms | 1.66 ms | 1.67 ms | | 1 MB of JSDoc blocks | 2.55 ms | 1.77 ms | 1.77 ms | | Astro config types (125 KB) | 321.1 µs | 241.4 µs | 236.9 µs | | AngularJS 1.2.5 | 3.40 ms | 3.05 ms | 3.01 ms | | `typescript.js` (8 MB) | 51.50 ms | 49.80 ms | 49.05 ms | | cal.com TSX (1 MB) | 7.10 ms | 7.21 ms | 6.94 ms | I also tried `u128` in `words()`. With that change, the string input took 3.90 ms, so this PR does not include it. - For 650 inputs, the output matched the `main` build. The inputs are the Amaro benchmark corpus and synthetic inputs, each also with TypeScript `module` declarations and comments inserted at several positions. - The `swc_next_simd` tests pass. `cargo fmt`, `cargo clippy`, the tests of the other crates, and the other Amaro benchmark inputs were not run for this change. Native wall time was not measured. ## Related Links - #1443 - #1422 - nodejs/amaro#507 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
SourceMap::new_source_file removes a BOM that follows the one the adapter drains, which shifted every diagnostic by three bytes and failed a debug assertion. Map offsets into the text that SourceMap keeps. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
SWC Next's strip_types prefixes its own diagnostics with "SyntaxError: ", while parser diagnostics have no prefix. Amaro's JavaScript errors already carry the type, so users saw "UnsupportedSyntaxError: SyntaxError: ...". Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
SWC Next always parses decorators, so the adapter ignored `parser.decorators: false` and returned decorators unchanged. Report each decorator as InvalidSyntax when the option is off, as the previous parser did. Make `Options::default()` match the serde defaults, so Rust tests see the same parser settings as JavaScript. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
SWC Next rejects every `import =` declaration, including `import type X = require(...)`, which swc_ts_fast_strip erased. TypeScript's erasableSyntaxOnly rejects them too (TS1294). Document the change and pin it with a test. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
Note This text was drafted with AI and posted after human approval.
Decisions needed before merge@marco-ippolito These items need your decision before this PR can merge. They apply to 550dafe. This PR removes 1. Rejection of type-only
|
|
|
## Motivation `strip_types` reports all non-erasable syntax with one message: ``This syntax is not allowed when `erasableSyntaxOnly` is enabled``. Users who run TypeScript without a tsconfig, for example through Node.js, do not know this option. The message also does not tell which construct is the problem. This feedback came from the Amaro integration: nodejs/amaro#507 (comment). Consumers also cannot tell these errors from parser errors without a match on the message text. Amaro does this now to select its `UnsupportedSyntax` error code. ## Changes - Add `UnsupportedSyntaxKind` (`Enum`, `Namespace`, `ImportEquals`, `ExportAssignment`, `ParameterProperty`, `TypeAssertion`). `UnsupportedSyntaxKind::message` gives a message for each kind, for example `SyntaxError: TypeScript enum declarations are not supported in type stripping`. - Add `StripResult::unsupported_syntax: Option<UnsupportedSyntax>`. It holds the kind and the span of the reported diagnostic. The diagnostic stays in `StripResult::diagnostics`. - Add the help text ``Use `expr as T` instead.`` to the diagnostic for angle-bracket type assertions. - An error inside a namespace keeps its own kind. For example, `namespace N { const enum E { A } }` reports `Enum`. Breaking changes: - `StripResult` has a new public field, so code that constructs or destructures it exhaustively must change. - The diagnostic messages for non-erasable syntax change. Validation: - `cargo test -p swc_next_type_strip`: passed (48 tests). A new test checks the kind for each construct and that other errors give `None`. The shared error assertion checks that `unsupported_syntax` matches the diagnostic span and message. - `cargo clippy -p swc_next_type_strip --all-targets --all-features -- -D warnings` and `cargo fmt`: passed. ## Related Links - nodejs/amaro#507 (comment) Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
SWC Next 0.9.1 reports the kind of non-erasable syntax in `StripResult::unsupported_syntax` (swc-project/swc-next#1702), and its messages name the construct, for example "TypeScript enum declarations are not supported in type stripping". They no longer mention `erasableSyntaxOnly`, which Node.js users may not know. Select the `UnsupportedSyntax` code from `unsupported_syntax` instead of a match on the message text. `Diagnostic` has no lifetime parameter now, so remove it from the adapter types. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
SWC Next gives the help text "Use `expr as T` instead." with the diagnostic for `<T>expr`, but Amaro reports only the message. Add the help text of the non-erasable syntax diagnostic to the message, as the deprecated `module` keyword error already does. Parser help text refers to the snippet position, so it is not added. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The README said that Amaro rejects every `import =` declaration. An
`import =` declaration inside an ambient declaration, for example
`declare module "pkg" { import type fs = require("node:fs"); }`, is
erased, and TypeScript's `erasableSyntaxOnly` accepts it too.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
kdy1
left a comment
There was a problem hiding this comment.
Note
This text was drafted with AI and posted after human approval.
- Harness: T3 Code
- AI agents: coordinator: Claude Opus 5.5 (claude-opus-5-5), reviewer: GPT-6.2 Astra (gpt-6.2-astra), reviewer: GPT-6.2 Sol (gpt-6.2-sol), reviewer: Claude Opus 5.5 (claude-opus-5-5), reviewer: Claude Sonnet 5.5 (claude-sonnet-5-5)
Verdict: Approve
This review approves the pull request. The P3 items are optional and do not block the merge.
@marco-ippolito This PR is ready to merge from my side. SWC Next 0.9.1 (swc-project/swc-next#1702) gives messages that name the unsupported construct, for example TypeScript enum declarations are not supported in type stripping, so the messages no longer mention erasableSyntaxOnly. If you prefer, I will squash the commits before the merge. The questions in #507 (comment) still need your decision. The notes below are non-blocking. The directive note and the nested type-only import note come from swc-next.
Reviewed commit: 9daedd0a82d0dc9784eb3dd4b3d7b32b3c230f3a
- P3 (non-blocking): 3 (1 inline)
This review is posted as a comment because GitHub does not let the account kdy1 approve or request changes on its own pull request. The verdict above still applies.
Items that cannot be inline
-
P3 · Non-blocking · Type-only import and export declarations inside a function or block are erased without an error — the whole change
function load() { import type { T } from './dep'; return 42 as T; }strips without an error. Amaro 1.3.0 reportsInvalidSyntax('import', and 'export' cannot be used outside of module code). The same applies to{ import type ... },if (a) import type ..., andexport interfaceinside a function. The SWC Next parser does not check that these declarations are at the top level. The stripped output keeps the intended runtime behavior, and a value import that remains in the output is rejected by V8. -
P3 · Non-blocking · The Dependabot
swcgroup also matches theswc_next_*crates —.github/dependabot.yml:19The
swc_*pattern of theswcgroup matchesswc_next_allocator,swc_next_ecma_ast,swc_next_ecma_parser, andswc_next_type_strip. The comment above the group says that the group exists because SWC publishes all of its crates from one release. SWC Next has a separate release train, so one Dependabot PR will update both trains, and a failure in one blocks the other.
|
Note This text was drafted with AI and posted after human approval.
Addendum to my review: The note "Type-only import and export declarations inside a function or block are erased without an error" needs a qualification. In SWC Next, the parser accepts When a value import remains in the output, V8 reports the error. A type-only declaration is erased, and the output keeps the intended runtime behavior. TypeScript and editors already report the error for this source. So this note is not a defect in SWC Next, and no change is needed. With the correction in #507 (comment), neither of the two notes that the review attributed to swc-next needs a change. |
|
How does it compare with https://tangled.org/nibling.dev/typestrip |
|
Note This text was drafted with AI and posted after human approval.
@marco-ippolito I compared this PR with typestrip. I ran the same inputs through three implementations:
Machine: x86-64 Linux, Node.js 24.22.1. Summary
Design
PerformanceEach value is a median.
Differential test
The table shows the cases where the results are different. "Real code" means that the case occurs in the OSS corpus.
The Conclusion for Node.js
|
|
I'll post the Wasm size without the SWC crates, too |
|
Note This text was drafted with AI and posted after human approval.
Follow-up to my comparison with typestrip: I measured how much of the package size comes from the SWC crates that this PR keeps besides SWC Next. This PR keeps two groups of published SWC crates:
I built three experimental variants of
Results
Validation of the replacement diagnosticsI ran this PR and the "both removed" variant on 54,909 inputs (TypeScript 6.0.3
These variants are experiments to measure size. They are not part of this PR. |
|
Lets do it |


Summary
Replace
swc_ts_fast_stripwith the SWC Next crates from crates.io, pinned to0.9.1, for TypeScript type stripping. Stripping keeps the fixed-width output: every UTF-16 offset in the output is the same as in the input. ThetransformSyncAPI and the Node.js REPL helpers do not change.Remove
mode: "transform", theamaro/transformloader, the transformation-only options, and their dependencies and tests. This is consistent with the removal of transformation support in nodejs/node#61803.This is a breaking change. It must be released as a new major version of Amaro (2.0.0).
Breaking changes
mode: "transform"is removed. A call with it throwsunknown variant `transform`, expected `strip-only`. It does not fall back to stripping.amaro/transformexport is removed.require.resolve("amaro/transform")throwsERR_PACKAGE_PATH_NOT_EXPORTED.Optionsno longer hastransformandsourceMap,Options["mode"]is only"strip-only", andTransformOutputno longer hasmap.import =declaration is rejected withUnsupportedSyntax. This includes type-only forms, for exampleimport type fs = require("node:fs")andexport import type A = N.B. Amaro 1.x erases the type-only forms. This matcheserasableSyntaxOnlyin tsc 5.9.TypeScript enum declarations are not supported in type strippinginstead ofTypeScript enum is not supported in strip-only mode. The message for an angle-bracket type assertion ends withUse `expr as T` instead.Error codes (UnsupportedSyntax,InvalidSyntax) and location fields do not change.'use strict' as any;at the start of a script or function body, is rejected withInvalidSyntax. Amaro 1.x erases the suffix, and the string becomes a directive.withstatements and legacy octal literals in module code. V8 reports them when it loads the output.Changes
crates/amaro/src/strip.rsadapts SWC Next to Amaro:UnsupportedSyntaxcode fromStripResult::unsupported_syntax(feat(type-strip)!: report the kind of non-erasable syntax swc-project/swc-next#1702), not from the message text. It adds the help text of that diagnostic to the message.modulekeyword (deprecatedTsModuleAsError). A fast path skips the second parse when no erasedmoduleword can start a declaration.parser.decorators: false. Onlytsxanddecoratorsinparserhave an effect.importandexportdeclarations whenmodule: false, because SWC Next accepts them in scripts.crates/amaro/src/options.rsdefines the publicOptionsandTransformOutputtypes.swc_ts_fast_stripand the SWC transform, codegen, and source map crates.swc_next_allocator,swc_next_ecma_ast,swc_next_ecma_parser, andswc_next_type_stripat=0.9.1.Zliblicense forfoldhashindeny.toml. It comes in throughhashbrown0.17.1.Performance
With SWC Next 0.6.1, on typescript.js (9.1 MB), stripping takes 56.3 ms instead of 152.8 ms with Amaro 1.3.0, and the output is the same. The full benchmark table is in the PR comments.
Validation
At
82b96fcc:cargo test --locked: 26 passed.cargo clippy --all-targets -- -D warningsandcargo fmt --check: passed.npm run typecheck,npm run build, andbiome ci: passed.npm test: 101 passed, with a local WebAssembly build (cargo build --release --target wasm32-unknown-unknownandwasm-bindgen0.2.100).With SWC Next 0.6.1, a differential test against
swc_ts_fast_strip59.0.2 found 0 output differences on 40,356 real-world units. The PR comments have the details and the TypeScript test-suite results.Review status
The bug analysis of the related swc-next components is complete, and the self-review found no blocking problem. The passing tests above do not establish complete compatibility or prove that swc-next is free of bugs.
AI assistance and human review
AI was used to prepare these changes. Human-reviewed by @kdy1.
The SWC Next
0.6.1update (9dea4ed0a) and the SWC Next0.9.1update (aba22c08,82b96fcc) were prepared with Claude Code (Claude Opus 5.5). This description was updated to match the diff at9daedd0awith Claude Code (Claude Opus 5.5) in T3 Code.