Commit Graph

920 Commits

Author SHA1 Message Date
oxc-guard[bot] 63b129182d release(crates): oxc v0.132.0 (#22527)
### 🐛 Bug Fixes

- 0f26de6 ecmascript: Resolve identifier value type via tracked
constants (#22234) (Alexander Lichter)
- c27a8cf minifier: Normalize `{ x: x }` shorthand so adjacent-if merge
is idempotent (#22401) (Dunqing)
- e431a0e parser: Break extends clause loop on fatal error (#22517)
(Boshen)
- e9ec7c6 minifier: Fold optional chains by base nullishness (#22236)
(Alexander Lichter)
- e6090e7 transformer: Keep enum IIFE when a non-inlinable value
reference remains (#22501) (Dunqing)
- 931b7d6 transformer: Inline const enum members through type-cast
wrappers (#22500) (Dunqing)
- b9615b2 codegen: Preserve string quotes in require() calls during
minification (#22475) (zennnnnnn11)
- c73c159 transformer/async-to-generator: Reparent parameter initializer
scopes (#22507) (camc314)
- ecfd3ca transformer/async-to-generator: Move only parameter bindings
(#22503) (camc314)
- 3ce3431 transformer/explicit-resource-managment: Preserve shadowed
for-head block (#22451) (camc314)

### ⚡ Performance

- ce92c6c semantic: `#[inline]` `Scoping::get_binding` (#22414)
(Dunqing)
- 98be95c regular_expression: Track regex flags via bitflags (#22427)
(Boshen)
- dbbc059 jsdoc: Skip should_attach_jsdoc when no remaining comments
(#22409) (Boshen)
- 217d7d8 minifier: Index `SymbolValues` by `SymbolId` (#22441)
(Dunqing)
- d782b78 minifier: Use BitSet for LiveUsageCollector live references
(#22425) (Boshen)
2026-05-18 12:09:14 +01:00
zennnnnnn11 b9615b2ed9 fix(codegen): preserve string quotes in require() calls during minification (#22475)
Closes #22463

## Summary

- Add `try_print_require_call` to force plain string literals (no
backticks) for `require("...")` calls during minification
- Prevents `cjs-module-lexer` from failing to detect CJS reexport
sources

### Problem

When minifying, `StringLiteral::gen` passes `allow_backtick: true`,
which can convert:
```js
__exportStar(require("./decorators"), exports);
```
into:
```js
__exportStar(require(`./decorators`),exports);
```

Node.js uses `cjs-module-lexer` for CJS/ESM interop. This lexer uses a
fast heuristic parser that does **not** recognize template literals as
`require()` arguments, causing named reexports to silently disappear
from the module's export list.

### Fix

Add `try_print_require_call` (following the existing
`try_print_cjs_define_property_call` pattern) that detects
`require("...")` calls via the existing
`CallExpression::common_js_require()` helper and prints the string
argument with `allow_backtick: false`.

## Test plan

- [x] `require("./decorators")` stays quoted when minified
- [x] `require('./foo')` normalizes to double quotes (not backticks)
- [x] `require(foo)` (dynamic) is unaffected
- [x] Non-require calls like `foo("./bar")` still get backtick
optimization
- [x] `cargo test -p oxc_codegen` passes
- [x] Follows existing CJS special-case pattern in codegen

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: zennnnq <ennanzhou@gmail.com>
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
Co-authored-by: Dunqing <dengqing0821@gmail.com>
2026-05-18 08:42:42 +08:00
oxc-guard[bot] 564ebbf46f release(crates): oxc v0.131.0 (#22459)
### 🚀 Features

- bc91a17 codegen: Expose `Codegen::with_source_type` method (#22432)
(camc314)

### 🐛 Bug Fixes

- 5ac7e79 minifier: Drop unused-var-init pure IIFEs and preserve
annotation for downstream (#22349) (Dunqing)
- 4ab57eb allocator: Fixed-size allocators use `VirtualAlloc` on Windows
(#22124) (overlookmotel)
- 66d77eb allocator: Fix segfault on Linux MUSL with fixed-size
allocators (#22388) (overlookmotel)
- b8fbc1f transformer/object-rest-spread: Correct scope id when moving
bindings (#22419) (camc314)
- 18edc2c codegen: Keep `Object.defineProperty` property name as plain
string in minify (#22400) (Dunqing)
- dda33de transformer/explicit-resource-management: Align lexical
binding scopes (#22320) (camc314)
- 8e79de8 transformer: Preserve for-await statement bodies (#22361)
(camc314)
- 0cba210 transformer/class: Replace `new.target` in static blocks
(#22360) (camc314)
- 67ab1c9 transformer/es2018/for-await: Hoist for-await generated
bindings (#22355) (camc314)
- c3ceb4a transformer/object-rest-spread: Use hoisted scope for `for-of`
temp refs (#22347) (camc314)

### ⚡ Performance

- 73a9043 allocator/bitset: Avoid temp heap `String` allocation (#22403)
(camc314)
- 8b2f4f9 transformer/object-rest-spread: Collect `Vec<SymbolId` over
`Vec<BindingIdentifier>` (#22418) (camc314)
- 83679ea parser: Split TriviaBuilder::handle_token hot/cold paths
(#22415) (Boshen)
- 2c7d781 codegen: Inline identifier-name accessors (#22411) (Boshen)
- 618bc76 diagnostics: Inline `OxcDiagnosticInner` to avoid heap
allocation (#22406) (Boshen)
- 0b4e158 parser: Reserve cap `2` for sequence expressions vec (#22374)
(camc314)
- 5f3bdd0 codegen: Add `#[inline]` to `code`, `code_len` (#22373)
(camc314)

Co-authored-by: overlookmotel <557937+overlookmotel@users.noreply.github.com>
2026-05-15 15:38:24 +01:00
Dunqing 703557c52c fix(codegen): keep exports[STR] = … key as plain string in minify (#22402)
Stacked on #22400. Closes the second `cjs-module-lexer` gap.

After #22400, `Object.defineProperty(exports, "name", ...)` is fine, but `exports["name"] = …` / `module.exports["name"] = …` were still being emitted with backtick keys in minify. The lexer recognises this form too — it just couldn't see them past the template literal.

Valid-identifier keys (`exports["foo"]`) are already collapsed to dot access by the minifier earlier in the pipeline, so only non-identifier keys (`exports["has-dash"]`, `module.exports["__esModule"]`, …) survive to the codegen stage and were affected.

In `AssignmentExpression::gen_expr`, detect when the LHS is a computed member expression on `exports` / `module.exports` whose key is a `StringLiteral`, and print the key via `print_string_literal(key, false)`. Other computed access (`otherObj["x"]`) is unaffected.

### Where each cjs-module-lexer named-export form lands

| Pattern | Status |
|---|---|
| `exports.name = …` | identifier — never affected |
| `module.exports.name = …` | identifier — never affected |
| `module.exports = { "name": … }` | object property keys already use `allow_backtick: false` |
| `Object.defineProperty(exports, "name", …)` | fixed in #22400 |
| `exports["name"] = …` / `module.exports["name"] = …` | **fixed here** |

### Before / after

```js
// input
exports["has-dash"] = a;
module.exports["__esModule"] = true;
otherObj["not-exports"] = d;
```

```js
// before
exports[`has-dash`]=a,module.exports[`__esModule`]=!0,otherObj[`not-exports`]=d;

// after
exports["has-dash"]=a,module.exports.__esModule=!0,otherObj[`not-exports`]=d;
```

(`module.exports.__esModule` collapses to dot via a separate minifier pass; `otherObj["x"]` correctly stays backtick.)

Refs #22342

AI assisted.
2026-05-15 13:55:48 +00:00
camc314 bc91a17605 feat(codegen): expose Codegen::with_source_type method (#22432)
if we are only printing a fragment of a ast e.g. a expression, we can't control if `is_jsx` is true.

this means generics can be printed incorrectly as they are missing a `,` in jsx code.
2026-05-14 17:03:06 +00:00
Dunqing 18edc2ce8f fix(codegen): keep Object.defineProperty property name as plain string in minify (#22400)
Fix `cjs-module-lexer` failing to detect `Object.defineProperty(exports, "name", ...)` named exports after oxc minify.

`calculate_quote_maybe_backtick` favored backtick when all three quote costs tied at zero, so a plain ASCII property name like `"getInclusionReasons"` was emitted as a backtick template. [`cjs-module-lexer`](https://github.com/nodejs/cjs-module-lexer) (used by Node for CJS/ESM interop) only matches plain string literals there, so the affected exports silently dropped out of its export set — downstream ESM consumers then failed with `Named export 'X' not found`.

In `CallExpression::gen_expr`, detect `Object.defineProperty` / `Reflect.defineProperty` and print the 2nd argument via `print_string_literal(name, false)` (the existing `allow_backtick: false` path). Other arguments — and nested strings inside the descriptor — still benefit from backtick optimization. Minify-only: outside minify, `print_string_literal` uses `self.quote` (never backtick), and `print_arguments` is needed there to preserve argument comments.

### Before / after

```js
// input
Object.defineProperty(exports, "getInclusionReasons", { ... });
```

```js
// before
Object.defineProperty(exports,`getInclusionReasons`,{...});

// after
Object.defineProperty(exports,"getInclusionReasons",{...});
```

Closes #22342

AI assisted.
2026-05-14 10:28:48 +00:00
Boshen 2c7d7816fb perf(codegen): inline identifier-name accessors (#22411)
## Summary

`Codegen::get_identifier_reference_name` and `Codegen::get_binding_identifier_name` are called once per identifier emission (every `IdentifierReference`, `BindingIdentifier`, import/export spec, etc.) but were not marked `#[inline]`. The bodies are short and in the common case (no scoping i.e. no mangling) compile to a couple of loads, so the function-call overhead is a noticeable share of codegen self-time on identifier-heavy inputs.

## Measurements

Wall-time on codegen-only loop (parse once, codegen N times), `--profile release-with-debug`, median of 3 runs:

| file | before | after | delta |
|---|---|---|---|
| antd.js (6.7M) | 14.49 ms/iter | 13.25 ms/iter | **-8.6%** |
| checker.ts (2.8M) | 4.35 ms/iter | 4.12 ms/iter | **-5.3%** |
| binder.ts (189K) | 155 µs/iter | 150 µs/iter | -3.2% |
| pdf.mjs (554K) | 961 µs/iter | 935 µs/iter | -2.7% |
| cal.com.tsx (1.0M) | 1.46 ms/iter | 1.48 ms/iter | noise |

xctrace Time Profiler self-time on `Codegen::get_identifier_reference_name` (antd.js): 0.50% → 0.33%; samples redistribute into `GenExpr::print_expr` (the inlining call site) as expected.

🤖 Generated with [Claude Code](https://claude.com/claude-code)
2026-05-14 08:57:53 +00:00
camc314 5f3bdd09e1 perf(codegen): add #[inline] to code, code_len (#22373) 2026-05-13 07:32:57 +00:00
oxc-guard[bot] 650417ffd0 release(crates): oxc v0.130.0 (#22316)
### 🚀 Features

- 66c9b01 transformer/typescript: Debug_assert that `enum_eval` ran in
semantic (#22252) (Dunqing)
- ffe6475 minifier: Fold `Array` constructor with safe spreads (#22215)
(camc314)

### 🐛 Bug Fixes

- d3d0b18 traverse: Handle `ChainElement::TSNonNullExpression` in
`GatherNodeParts` (#22247) (leaysgur)
- 4e880de transformer/object-rest-spread: Declare temp vars for computed
keys (#22284) (camc314)
- a7c3e22 semantic: Clear member write target for computed keys (#22302)
(camc314)
- 6a8852d codegen: Emit newline after legal-comment orphan flush
(#22304) (Dunqing)
- 5da9fda transformer/explicit-resource-management: Preserve class names
(#22306) (Dunqing)
- b5d970f transformer/explicit-resource-management: Preserve class names
(#22290) (camc314)
- bc54fd4 minifier: Keep function / class names if direct eval is
present in the scope (#22241) (sapphi-red)
- 7a810c0 minifier: Refresh direct eval flags after DCE (#21787)
(Dunqing)
- dd88726 transformer/legacy-decorator: Preserve accessor type
annotation for emitDecoratorMetadata (#21966) (Dunqing)
- 29a3cd7 codegen: Swap mapping/indent order for top-level decls
(#22206) (Dunqing)
- 73b4f40 minifier: Preserve catch binding with direct eval (#22221)
(camc314)
- 0e13d17 minifier: Preserve optional chain base side effects (#22219)
(camc314)
- 0c7c01c transformer/typescript: Inline optional-chain enum member
access (#21834) (Dunqing)
- a6aff7e codegen: Emit block/array/object end mapping at close char
(#22200) (Dunqing)
- a099b03 codegen: Emit call end mapping at `)` position, not past it
(#22199) (Dunqing)
- 5753774 minifier: Cap if-return ternary collapse for firefox (#21841)
(Gurupungav Narayanan)
- 2493bdd codegen: Correct sourcemap end mappings for closing delimiters
(#22001) (Mark Dalgleish)
- 3b385e2 minifier: Bail optimizing `Array` with unknown arg count
(#22188) (camc314)
- 9fa2122 parser: Parse array computed class keys (#22159) (camc314)

### 📚 Documentation

- a4a6892 napi/parser: Correct code comment (#22278) (overlookmotel)
- 9305373 oxc: Update README (#22178) (camc314)

Co-authored-by: Cameron <cameron.clark@hey.com>
2026-05-11 16:02:22 +01:00
Dunqing 6a8852d910 fix(codegen): emit newline after legal-comment orphan flush (#22304)
`print_legal_orphans_before` carried the source-side `followed_by_newline = false` for inline orphans (e.g. `33/*!*/ ||`) over into the flush position. After printing the orphan, `print_comments` set `print_next_indent_as_space = true`, which then turned the closing-`}` indent into a single space — producing `\t/*!*/ }` on pass 1.

Pass 2 saw the comment at `}`-position, picked it up via `FunctionBody`'s `comments_at_end` branch (which calls `clear_pending_indent_space()`), and emitted `\t/*!*/}` without the space. The two passes diverged and [monitor-oxc's codegen idempotency check](https://github.com/oxc-project/monitor-oxc/actions/runs/25616176953/job/75194649734) failed on every cjs-module-lexer / es-module-lexer build.

Force `followed_by_newline = true` on the last orphan before the flush so `print_comments` takes its existing newline-emitting branch. Orphans now land block-level on both passes — matching the pass-2 `comments_at_end` path that already calls `clear_pending_indent_space()`.

The orphan-preservation behavior added in #21575 (issue #19750) is unaffected: `//! some license` whose anchor is DCE'd is still emitted at the next surviving statement.

## Test plan
- [x] `cargo test -p oxc_codegen` (105 tests, includes new `test_inline_legal_comment_in_function_body_is_idempotent`)
- [x] `cargo test -p oxc_minifier --tests` (492 tests, includes #21575's `preserve_legal_comment_when_dce_removes_anchor`)
- [x] Re-ran codegen idempotency on all 4 originally failing files (`cjs-module-lexer@1.4.3 / @2.2.0`, `es-module-lexer@1.7.0 / @2.0.0`) — all `same = true`.
2026-05-11 08:44:25 +00:00
Dunqing 5bdf4972b0 refactor(codegen): extract consume_pending_indent_space helper (#22211)
Stacked on #22206. Pure refactor — no behavior change.

The `print_next_indent_as_space` flag was being read inline at **five** sites in `gen.rs` via copy-pasted `if flag { print_hard_space(); flag = false }` blocks. Two named private helpers replace those:

- `consume_pending_indent_space() -> bool` — emit space + clear flag, returns whether anything was emitted
- `clear_pending_indent_space()` — drop the flag without emitting

`print_indent` continues to call `consume_pending_indent_space` internally, preserving the flag-as-space contract at every existing `print_indent` site.

## Test plan

- [x] `cargo test -p oxc_codegen` passes (100 integration tests, no new tests added since the existing `top_level_decl_mappings_start_after_generated_indent` from #22206 already covers the `Directive` indent path)
- [x] `cargo test -p oxc_isolated_declarations` passes (the namespace / `declare module` snapshot fixtures that already exercise indented import/export decls)
- [x] No snapshot updates needed
2026-05-07 14:11:34 +00:00
Dunqing 29a3cd76a0 fix(codegen): swap mapping/indent order for top-level decls (#22206)
Independent of #22199 / #22200. Fixes a separate sourcemap-indent issue.

Five `gen.rs` impls for top-level declarations were calling `add_source_mapping(self.span)` *before* `print_indent()`:

- `Directive`
- `ImportDeclaration`
- `ExportNamedDeclaration`
- `ExportAllDeclaration`
- `ExportDefaultDeclaration`

The mapping then anchored at the line's indent column (col 0) rather than at the actual keyword column. Sourcemap consumers querying the keyword's gen position would land on the leading whitespace.

Every other indented statement in the codebase (`ExpressionStatement`, `IfStatement`, `VariableDeclaration`, etc.) uses the inverse order — `print_indent` first, then `add_source_mapping`. This PR brings the five outliers in line.

## Visual comparison

The bug surfaces when codegen is invoked with non-zero `initial_indent` (a common pattern for bundler callers that nest output in a wrapper). [Before vs After this PR](https://source-map-viewer.void.app/compare?a=5KX8dYtn&b=ZFhNIEAv) on a fixture with all five declaration kinds:

```js
"use strict";
import { x } from "x";
export { y } from "y";
export * from "z";
export default 42;
```

Each declaration's source position now maps to gen col 1 (the keyword) instead of gen col 0 (the leading tab).

## Test plan

- [x] New test `top_level_decl_mappings_start_after_generated_indent` — wraps a `"use strict"`, `import`, three `export` forms inside an indented `if (true) { ... }` block, asserts each maps from `src col 0` to `gen col 1` (after the tab), not `gen col 0`.
- [x] Verified the test fails without the fix.
- [x] All 99 codegen tests pass.
2026-05-07 14:11:33 +00:00
Dunqing a6aff7ea51 fix(codegen): emit block/array/object end mapping at close char (#22200)
Stacked on #22199.

Extends the same fix shape from #22199 (move `add_source_mapping_end` before the closing `print_ascii_byte`) to the remaining close-delimiter sites: `print_block_end`, `print_curly_braces`, and the `]`/`}` of `ArrayExpression` / `ObjectExpression`.

## Why

#22199 fixed the call's `)`. The same root cause exists for `}` of blocks/objects and `]` of arrays — the end mapping was placed AFTER the close char, putting it at the position of whatever follows. The most visible case: `() => { ... };` — the source `}` mapped to the generated `;` rather than the generated `}`, so source-map consumers viewing this diff saw the `}` "point at the semicolon."

## How

Five sites total, four in this PR (one already in #22199):

| Site | File |
|---|---|
| `print_block_end` (the `}` of `BlockStatement`) | `lib.rs` |
| `print_curly_braces` (shared by class body, switch, TS enum/interface/typeliteral/module) | `lib.rs` |
| `ArrayExpression` (`]`) | `gen.rs` |
| `ObjectExpression` (`}`) | `gen.rs` |

Each: swap `print_ascii_byte; add_source_mapping_end` → `add_source_mapping_end; print_ascii_byte`. The mapping now lands at the gen position OF the close char.

## Visual comparisons

Fixture covering all 5 sites (classes, arrow bodies, arrays, objects, chained calls):

- **Pre-PR vs Full fix** (full picture): https://source-map-viewer.void.app/compare?a=j9GHxMTX&b=UcCYKDih
- **PR-only vs Full fix** (just the changes #22199 + #22200 add): https://source-map-viewer.void.app/compare?a=ngs4XAsh&b=UcCYKDih
- **esbuild vs Full fix** (alignment with esbuild): https://source-map-viewer.void.app/compare?a=26JVF9DI&b=UcCYKDih

## Reference

esbuild (`internal/js_printer/js_printer.go`):

```go
if e.CloseBraceLoc.Start > expr.Loc.Start {
    p.addSourceMapping(e.CloseBraceLoc)
}
p.print("}")
```

(Same pattern as the call's `)` handling — see #22199.)

## Test plan

Each of the 4 modified sites has direct test coverage:

- [x] `block_end_mapping_lands_at_close_brace` — pins `}` of `() => { return 1 }` (exercises `print_block_end`)
- [x] `class_body_close_brace_lands_at_close_brace` — pins `}` of `class C { a; }` (exercises `print_curly_braces` — shared by classes, switch, TS enum/interface/typeliteral/module)
- [x] `array_close_bracket_lands_at_close_bracket` — pins `]` of `const a = [1, 2]` (exercises `ArrayExpression`)
- [x] `object_close_brace_lands_at_close_brace` — pins `}` of `const o = { a: 1 }` (exercises `ObjectExpression`)
- [x] `synthesized_block_closing_braces_are_mapped` (added by #22001) updated to assert `dst (2, 0)` instead of `(2, 1)` — same intent (the synthesized `}` resolves back to the wrapped if's last char), now anchored at the `}` itself
- [x] `cargo test -p oxc_codegen` passes (11 sourcemap tests, 100 integration total)
- [x] `stacktrace_is_correct` snapshot unchanged

Each new test was verified to fail without the corresponding swap and pass with it.
2026-05-07 06:57:43 +00:00
Dunqing a099b03c61 fix(codegen): emit call end mapping at ) position, not past it (#22199)
Follow-up on #22001.

Move `add_source_mapping_end(span)` to before `print_ascii_byte(b')')` in `print_arguments` so the call's end mapping lands at the generated position **of** `)` rather than one past it. Each generated paren now has at most one mapping at its exact position, matching the convention used by esbuild and Babel.

A second follow-up (#22200) extends the same fix to block-end `}`, curly-braces `}`, and the `]`/`}` of `ArrayExpression` / `ObjectExpression`.

## Why

After #22001, `add_source_mapping_end` correctly points the source side at `span.end - 1` (the closing source char), but the generated position was still placed AFTER `)` was printed. For chained calls like `factory()()`, this collided with the next AST node's start position:

- inner call's end mapping at `gen 7:9 → src 7:8` (just past inner `)`)
- the outer call's `(` lives at `gen 7:9` in the generated code

Result: a V8 stack-trace lookup at `gen 7:9` (the outer `(`) returned `src 7:8` (the inner `)`) — one column off.

## How

Emit the end mapping at the gen position **of** `)`, not after it. Now:

- `gen 7:8 → src 7:8` (inner `)`)
- `gen 7:9` has no direct mapping → falls back to inner end → `src 7:8`
- `gen 7:10 → src 7:10` (outer `)`)

The chained-call shadow at the outer `(` becomes a plain "no mapping here, fall back to inner `)`" — same accepted behavior as esbuild, Babel, and TypeScript. None of them special-case chained calls.

## Visual comparisons

Generated against a fixture covering classes, arrow bodies, arrays, objects, and chained calls in the [source-map viewer](https://source-map-viewer.void.app):

- **Pre-PR vs Full fix** (full picture): https://source-map-viewer.void.app/compare?a=j9GHxMTX&b=UcCYKDih
- **PR-only vs Full fix** (just the changes #22199 + #22200 add): https://source-map-viewer.void.app/compare?a=ngs4XAsh&b=UcCYKDih
- **esbuild vs Full fix** (alignment with esbuild): https://source-map-viewer.void.app/compare?a=26JVF9DI&b=UcCYKDih

## Reference

esbuild (`internal/js_printer/js_printer.go`):

```go
if e.CloseParenLoc.Start > expr.Loc.Start {
    p.addSourceMapping(e.CloseParenLoc)
}
p.print(")")
```

Babel (`packages/babel-generator/src/printer.ts::rightParens`):

```ts
this.sourceWithOffset("end", node.loc, -1);
this.token(")");
```

## Test plan

- [x] New test `call_end_mapping_lands_at_close_paren` — pins both `)` mappings of `factory()()` to their close-paren positions
- [x] `cargo test -p oxc_codegen` passes (99 tests)
- [x] `stacktrace_is_correct` snapshot unchanged
2026-05-07 05:41:24 +00:00
Mark Dalgleish 2493bdde8e fix(codegen): correct sourcemap end mappings for closing delimiters (#22001)
This fixes incorrect sourcemap end mappings for closing delimiters
emitted by `oxc_codegen`.

This came up while investigating [Remix 3](https://remix.run/) test
coverage reporting for code transformed with Oxc via the Remix `assets`
package, which we were using in our `test` package to run in-browser
tests. V8 reported uncovered functions and branches correctly, but
`v8-to-istanbul` could not always resolve the end of those covered
ranges back through Oxc's sourcemap, which caused coverage to be
over-reported. This meant that we saw cases of 100% coverage being
incorrectly reported because `v8-to-istanbul` dropped the whole function
block when it could not map the closing `}` line of an uncalled
function.

`add_source_mapping_end` used `Span::end` directly even though spans are
end-exclusive, so the generated token could land one character past the
real source span. Block printers also did not emit end mappings for
closing `}` consistently. Consumers that resolve V8 coverage range ends
through the sourcemap can then miss those block boundaries and
over-report coverage.

This PR maps end tokens to `span.end - 1` and emits them for block
closers, then extends the sourcemap tests with:

- a runtime stacktrace regression for normal function and arrow block
bodies
- a direct regression for the synthesized wrapper-block path used to
preserve `else` binding

The snapshot updates in `stacktrace_is_correct` are expected for the
same reason. Those column numbers come from Node consuming the generated
sourcemap at runtime. For example, one frame changes from
`/project/input.js:10:12` to `/project/input.js:10:11` for the source
line `obj.fn({a})()`. In 1-based columns, that line is `o1 b2 j3 .4 f5
n6 (7 {8 a9 }10 )11 (12 )13`. The error happens in the first call
expression, so the end position should resolve to column 11, the first
`)`, which is the closing character of `obj.fn({a})`. Before this change
it resolved to column 12, the next `(`, because the end mapping pointed
one character too far to the right. After switching end mappings to the
final real source character and adding the missing block-closer
mappings, that frame moves left by one column to the correct source
position.

Please note, I created this PR with AI assistance, but I worked closely
with the agent to design, review, and iterate on the changes until it
was at a level I was happy with.
2026-05-07 11:07:39 +08:00
oxc-guard[bot] ec00055e64 release(crates): oxc v0.129.0 (#22108)
### 💥 BREAKING CHANGES

- 0ffbe0d allocator: [**BREAKING**] Remove `Allocator::end_ptr` method
(#21871) (overlookmotel)

### 🚀 Features

- 9593ec8 transformer/jsx: Add jsxDEV source metadata for fragments
(#21932) (Ido Rosenthal)

### 🐛 Bug Fixes

- 429deac napi/parser: Export `visitorKeys` from `wasm` entrypoint
(#21996) (NullVoxPopuli)
- e852911 codegen: Preserve legal comments orphaned by upstream passes
(#21575) (Dunqing)
- e3399ec transformer/class-properties: Preserve RHS in
logical-assignment to static private field (#21950) (Dunqing)
- c59c199 transformer/typescript: Emit class fields for parameter
properties (#21831) (Dunqing)
- aaabde4 parser: Attach legal comments to following token (#21670)
(Dunqing)

### ⚡ Performance

- 0bf0cb9 allocator: Per-platform `Arena::new_fixed_size`
implementations (#22088) (overlookmotel)

### 📚 Documentation

- 62ec410 allocator: Correct doc comment for `Allocator::from_raw_parts`
(#22093) (overlookmotel)
- 3e152c6 allocator: Correct typos in comments (#22092) (overlookmotel)
- e220855 allocator: Correct doc comment for `Allocator::set_cursor_ptr`
(#21866) (overlookmotel)

---------

Co-authored-by: Boshen <1430279+Boshen@users.noreply.github.com>
Co-authored-by: Cameron Clark <cameron.clark@hey.com>
2026-05-05 09:59:50 +01:00
Dunqing e85291136c fix(codegen): preserve legal comments orphaned by upstream passes (#21575)
Closes #19750.

## Problem

Legal comments (`//!`, `/*!`, `@license`, `@preserve`) anchor to AST nodes via `attached_to`. When DCE removes the node, codegen's `Inline` mode silently drops the comment.

## Fix

Codegen-side. Two helpers in `oxc_codegen`:

- `print_legal_orphans_before(end)` — drains pending legal-comment orphans and emits them at the current cursor in source order.
- `has_legal_orphans_before(end)` — used by block emitters to keep an empty body multi-line so it can host the flush.

Wired into every statement-list site (Program / FunctionBody / BlockStatement / StaticBlock / SwitchCase / TSModuleBlock) via a single `print_stmts_with_orphan_flush` helper. Orphans land at the next surviving anchor in the same scope, preserving lexical order.

A sorted side index `legal_comment_keys: Vec<u32>` keeps the per-call cost at `O(log K)` (K = legal-comment count) rather than `O(M)` over the full comments map. This avoids the 19% codegen regression on `react.development.js` an earlier iteration of this PR introduced.

## Behaviour

Statement-level orphans match esbuild's `inline` mode: anchor surviving → original spot; anchor removed with sibling → next sibling in scope; anchor removed with no sibling → enclosing block (or program scope-end as last resort). Order against surviving legal comments preserved. Never silently dropped.

Out of scope: comments anchored to non-statement nodes (array elements, object properties, class members, expression positions). They still survive via the nearest enclosing statement-scope flush but won't always land at their exact original position. Closing those gaps would need an AST-level change (legal comments as first-class statements).

## Tests

`preserve_legal_comment_when_dce_removes_anchor` covers all four legal styles, no-DCE no-op, multi-orphan order, order against surviving legals, all-removed scope-end fallback, BlockStatement / FunctionBody / SwitchCase scopes, and the single-consequent SwitchCase regression flagged by Codex review.

All minifier + codegen tests pass. CodSpeed at baseline.
2026-04-30 00:44:50 +00:00
Dunqing aaabde4574 fix(parser): attach legal comments to following token (#21670)
## Summary
- treat `Legal` and `JsdocLegal` comments as leading comments for the following token instead of allowing them to become trailing comments on the previous token
- apply that rule to both legal block comments and legal line comments after code
- add parser regressions for both cases and a codegen idempotency regression for comment-preserving minify mode

## Why
`monitor-oxc` whitespace found a repeated print/parse instability in comment-preserving whitespace removal. Some bundled files contain legal comments such as `@license`/`@preserve` or `/*! ... */` between two statements. After one print, Oxc could produce a shape where a legal comment appeared after code and before the next token. On the second parse, the trivia builder sometimes classified that legal comment as trailing trivia for the previous token.

That classification is wrong for legal-comment preservation. Oxc only treats legal comments as preservable legal comments when they are leading comments. So the parser should keep legal comments attachable to the following token instead of finalizing them as trailing comments.

This makes repeated parse/print cycles stable in modes that remove whitespace but keep comments, without changing executable JavaScript semantics. Ordinary non-legal comments still use the existing leading/trailing classification.

## esbuild comparison
I checked esbuild's implementation because Oxc's legal-comment behavior is intended to follow the same model. esbuild's lexer records legal comments in `LegalCommentsBeforeToken`, and the parser consumes that list before parsing the next statement by inserting `SComment { IsLegalComment: true }` statements. In other words, esbuild models legal comments as comments before the next token/statement, not as trailing trivia attached to the previous token.

For the concrete repro, esbuild with `minify: true` and `legalComments: "inline"` keeps the legal comments inline and is idempotent across repeated transforms:

```js
foo();/**
* @license MIT
**//*! #__NO_SIDE_EFFECTS__ */function bar(){}
```

The key invariant from esbuild is not the exact newline placement. It is that legal comments remain associated with the following statement/token for preservation. This change moves Oxc's parser classification toward that invariant while leaving ordinary non-legal trailing comments alone.

## Testing
- `cargo test -p oxc_parser trivia_builder -- --nocapture`
- `cargo test -p oxc_codegen comments -- --nocapture`
- `cargo fmt --all --check`
- `git diff --check`
- `monitor-oxc whitespace` filtered to the two previously failing files (`@vue-macros/devtools` and `@asamuzakjp/css-color`): both files were collected and processed with no `RemoveWhitespace` diagnostics. The local runtime phase then failed separately under Node.js v25.8.1 on old package imports.
2026-04-29 14:16:53 +00:00
oxc-guard[bot] 9951013ece release(crates): oxc v0.128.0 (#21837)
### 💥 BREAKING CHANGES

- 502e804 ast: [**BREAKING**] Reduce size of `TSTypePredicateName`
(#21711) (overlookmotel)
- 5651539 ast: [**BREAKING**] Reduce size of `JSXExpression` (#21710)
(overlookmotel)
- c44e280 ast: [**BREAKING**] Reduce size of `ArrayExpressionElement`
(#21709) (overlookmotel)
- c5b3deb syntax: [**BREAKING**] Remove `CommentNodeId` (#21679)
(overlookmotel)

### 🚀 Features

- b738a39 allocator: Add `Allocator::cursor_ptr` method (#21773)
(overlookmotel)
- 678767e ast: Generate node_id accessors for AST enum wrappers (#21653)
(camc314)
- f091d77 minifier: Inline constant spread elements into arrays (#21095)
(Armano)

### 🐛 Bug Fixes

- 0d608c2 minifier: Preserve raw CR in template literals (#21645)
(Dunqing)
- a889ea9 minifier: Track pure functions in DCE mode (#21722) (Dunqing)
- 674dfac allocator: `Arena` retry allocation when chunk size approaches
maximum (#21777) (overlookmotel)
- f130cc0 allocator: Fix arithmetic overflow in
`Arena::new_chunk_memory_details` (#21745) (overlookmotel)
- b9bf239 allocator: Fix UB in `Arena::grow_zeroed` (#21739)
(overlookmotel)
- d2b9389 allocator: Clippy warning when building without `testing`
feature (#21681) (camc314)
- 503dc86 codegen: Map sourcemaps from visible output starts (#21662)
(Dunqing)
- c92bd3b transformer: Use SPAN for synthesized helper calls to prevent
comment misattribution (#21578) (Dunqing)
- 0d80441 codegen: Add mapping before printing `#` for private ident
(#21619) (camc314)

### ⚡ Performance

- 9fa362e napi/parser: Do not generate tokens except in tests (#21811)
(overlookmotel)
- 0044392 allocator: Reduce branches when allocating new chunk (#21776)
(overlookmotel)
- 7896bd0 allocator: `Allocator::used_bytes` do not use chunk iterator
(#21771) (overlookmotel)
- a5c562f allocator: Remove check in `Arena::new_chunk_memory_details`
(#21750) (overlookmotel)
- 35bbe1f allocator: `Arena` use unchecked size round up where
guaranteed no overflow (#21743) (overlookmotel)
- ffe229b allocator: Remove unnecessary check from
`Arena::try_alloc_layout_slow_impl` (#21732) (overlookmotel)
- 72fece5 allocator: Use `NonNull::offset_from_unsigned` in
`Arena::chunk_capacity` (#21731) (overlookmotel)
- cab32ae ast: Add `#[inline(always)]` to `node_id` methods on enums
with all variants unboxed (#21707) (overlookmotel)
- b179688 parser: Allocate `TriviaBuilder` comments in the arena
(#21512) (Boshen)
- 2290f31 lexer: Fix perf of `Token::set_*` methods on Rust 1.95.0
(#21659) (overlookmotel)
- 1b58029 allocator: Move code into cold path in `Arena::alloc_layout`
(#21622) (overlookmotel)
- 3cf7cef allocator: Reduce instructions on allocation hot path (#21510)
(overlookmotel)

### 📚 Documentation

- ce65070 data_structures: Document why `as_ref` and `as_mut` on
`NonNullConst` and `NonNullMut` take `self` (#21800) (overlookmotel)
- 93b7dbd allocator: Improve doc comments for `ChunkFooter` (#21733)
(overlookmotel)
- 295db8d transformer: Fix comment (#21717) (overlookmotel)
- 5c93af8 ast: Add comments explaining `#[inline(always)]` to `node_id`
methods on enums (#21706) (overlookmotel)
- e4cea25 transform: Use the `node:` namespace in the example (#19998)
(루밀LuMir)

### 🛡️ Security

- d8076c9 deps: Update rolldown (#21639) (renovate)

Co-authored-by: Boshen <1430279+Boshen@users.noreply.github.com>
2026-04-27 12:32:32 +01:00
Dunqing 503dc86d8b fix(codegen): map sourcemaps from visible output starts (#21662)
## Summary

move statement sourcemap anchors to the first emitted token after generated indentation

## Testing
- cargo test -p oxc_codegen indented_statement_mappings_start_after_generated_indent -- --nocapture
- cargo test -p oxc_codegen class_member_mappings_start_before_member_keys -- --nocapture
- cargo test -p oxc_transformer --test integrations -- --nocapture

## AI Usage
- Codex was used to help prepare this change.
2026-04-23 02:54:58 +00:00
camc314 0d80441a19 fix(codegen): add mapping before printing # for private ident (#21619)
Before:

![Screenshot 2026-04-21 at 19.39.46.png](https://app.graphite.com/user-attachments/assets/4ddfd06d-f6d7-4cba-84cd-76aac4af9f94.png)

After:

![Screenshot 2026-04-21 at 19.40.39.png](https://app.graphite.com/user-attachments/assets/b5fbcdf4-68ec-49d1-b686-63d4fb8a23e2.png)
2026-04-22 07:43:13 +00:00
oxc-guard[bot] 161d6b5583 release(crates): oxc v0.127.0 (#21572)
### 🐛 Bug Fixes

- 48967e8 isolated_declarations: Drop required type check for private
parameter properties on private constructors (#21515) (Dunqing)
- 91e5bde transformer/typescript: Preserve computed-key static block
when class has an empty constructor (#21562) (Dunqing)
- 50e9d26 mangler: Assign correct slot to shadowed function-expression
names (#21535) (Dunqing)
- 065ce47 isolated_declarations: Collect types from private accessors
for paired inference (#21516) (Dunqing)
- 00fc136 codegen: Preserve coverage comments before object properties
(#21312) (bab)
- d676e0c minifier: Mark LHS of `??=` as read when converting from `==
null &&` (#21546) (Gunnlaugur Thor Briem)

### ⚡ Performance

- e45efc5 parser: Reduce `try_parse` usage in favour of `lookahead`
(#21532) (Boshen)
- ddb1bf8 parser: Avoid redundant `IdentifierReference` clone in
shorthand property (#21511) (Boshen)
- be2b392 allocator: Store pointers directly in `Arena` (#21483)
(overlookmotel)

Co-authored-by: Boshen <1430279+Boshen@users.noreply.github.com>
Co-authored-by: Cameron <cameron.clark@hey.com>
2026-04-20 20:29:50 +01:00
Dunqing 67d40f8b36 fix(parser): set pure comment index after dedup check to handle lookahead/rewind (#21570)
Fix some idempotency tests that failed in https://github.com/oxc-project/monitor-oxc/actions/runs/24652862465/job/72079552802

## Summary

When `/* @__PURE__ */` appears before an object literal (e.g. `export const X = /* @__PURE__ */ { a: 1 }`), the parser's arrow-function lookahead causes the comment to be added to the `comments` vec during speculative parsing. After rewind, the same comment is encountered again — the dedup check skips the push, but `parse_annotation` had already set `pure_comment` to `comments.len()`, which now points to a non-existent index. This causes `mark_pure_comment_not_applied` to silently fail, breaking codegen idempotency.

### Fix

- Move `pure_comment` / `has_no_side_effects_comment` assignment from `parse_annotation` to `add_comment`, **after** the dedup check
- In the dedup branch, set the index to the existing comment (`len - 1`)
- In the normal branch, set the index to where the comment will be pushed (`len`)
- Extract shared logic into `set_annotation_flags` helper

## Test plan

- Added parser test: `/* @__PURE__ */` before object literal is correctly marked `PureNotApplied`
- Added parser test: `/* @__PURE__ */` before call expression remains `Pure` after lookahead
- Added codegen idempotency test: parse→codegen→parse→codegen produces identical output
- `cargo test -p oxc_parser --lib -- trivia_builder` — 9 tests pass
- `cargo test -p oxc_codegen --test integration -- comments` — all pass
2026-04-20 12:26:33 +00:00
bab 00fc13620d fix(codegen): preserve coverage comments before object properties (#21312)
Closes #21302

---------

Co-authored-by: Dunqing <dengqing0821@gmail.com>
2026-04-20 12:51:01 +08:00
renovate 611b3b69ef chore(deps): update dependency rust to v1.95.0 (#21509)
This PR contains the following updates:

| Package | Update | Change |
|---|---|---|
| [rust](https://redirect.github.com/rust-lang/rust) | minor | `1.94.1` → `1.95.0` |

---

### Release Notes

<details>
<summary>rust-lang/rust (rust)</summary>

### [`v1.95.0`](https://redirect.github.com/rust-lang/rust/compare/1.94.1...1.95.0)

[Compare Source](https://redirect.github.com/rust-lang/rust/compare/1.94.1...1.95.0)

</details>

---

### Configuration

📅 **Schedule**: (in timezone Asia/Shanghai)

- Branch creation
  - At any time (no schedule defined)
- Automerge
  - At any time (no schedule defined)

🚦 **Automerge**: Enabled.

♻ **Rebasing**: Whenever PR is behind base branch, or you tick the rebase/retry checkbox.

🔕 **Ignore**: Close this PR and you won't be reminded about this update again.

---

 - [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check this box

---

This PR was generated by [Mend Renovate](https://mend.io/renovate/). View the [repository job log](https://developer.mend.io/github/oxc-project/oxc).
<!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiI0My4xMjMuOCIsInVwZGF0ZWRJblZlciI6IjQzLjEyMy44IiwidGFyZ2V0QnJhbmNoIjoibWFpbiIsImxhYmVscyI6W119-->
2026-04-17 14:43:16 +00:00
Boshen 836fe9d51c release(crates): oxc v0.126.0 (#21471)
### 💥 BREAKING CHANGES

- 24fb7eb allocator: [**BREAKING**] Rename `Box` and `Vec` methods
(#21395) (overlookmotel)

### 🚀 Features

- ce5072d parser: Support `turbopack` magic comments (#20803) (Kane
Wang)
- f5deb55 napi/transform: Expose `optimizeConstEnums` and
`optimizeEnums` options (#21388) (Dunqing)
- 24b03de data_structures: Introduce `NonNullConst` and `NonNullMut`
pointer types (#21425) (overlookmotel)

### 🐛 Bug Fixes

- d7a359a ecmascript: Treat update expressions as unconditionally
side-effectful (#21456) (Dunqing)
- 56af2f4 transformer/async-to-generator: Correct scope of inferred
named FE in async-to-generator (#21458) (Dunqing)
- b3ed467 minifier: Avoid illegal `var;` when folding unused arguments
copy loop (#21421) (fazba)
- b0e8f13 minifier: Preserve `var` inside `catch` with same-named
parameter (#21366) (Dunqing)
- 4fb73a7 transformer/typescript: Preserve execution order for accessor
with `useDefineForClassFields: false` (#21369) (Dunqing)

### ⚡ Performance

- da3cc16 parser: Refactor out `LexerContext` (#21275) (Ulrich Stark)

### 📚 Documentation

- c5b19bb allocator: Reformat comments in `Arena` (#21448)
(overlookmotel)
- 091e88e lexer: Update doc comment about perf benefit of reading
through references (#21423) (overlookmotel)
- 922cbee allocator: Remove references to "bump" from comments (#21397)
(overlookmotel)

Co-authored-by: Dunqing <29533304+Dunqing@users.noreply.github.com>
2026-04-16 09:38:51 +08:00
Boshen fb6b1b053f release(crates): oxc v0.125.0 (#21374)
### 💥 BREAKING CHANGES

- 36cdc31 str: [**BREAKING**] Remove identity `FromIn` impl for `Ident`
(#21251) (overlookmotel)
- 382958a span: [**BREAKING**] Remove re-exports of string types from
`oxc_span` crate (#21246) (overlookmotel)
- c4aedfa str: [**BREAKING**] Add `static_ident!` macro (#21245)
(overlookmotel)

### 🚀 Features

- e7e1aea transformer/typescript: Add `optimize_enums` option for
regular enum inlining (#20539) (Dunqing)
- 679f57f transformer/typescript: Implement const enum inlining and
declaration removal (#20508) (Dunqing)
- 6dd061c semantic: Extend `MemberWriteTarget` to cover all property
modification patterns (#21205) (Dunqing)
- f134e24 minifier: Support `property_write_side_effects` option to drop
unused property assignments (#20773) (Dunqing)
- 75663c0 semantic: Add enum member value evaluation for const enum
support (#20602) (Dunqing)
- 3cfe8ed semantic: Add `MemberWriteTarget` flag to `ReferenceFlags`
(#20772) (Dunqing)

### 🐛 Bug Fixes

- af1a586 transformer/class-properties: Use correct property name when
converting parameter properties (#21268) (Amal Jossy)
- b43250a allocator: Move allocation tracking into `Bump` (#21342)
(overlookmotel)
- 36f505f allocator: `StringBuilder` use `Allocator::alloc_layout`
(#21340) (overlookmotel)
- 7a08a6f allocator: Fix allocation counting in
`Allocator::alloc_concat_strs_array` (#21336) (overlookmotel)
- 2338e28 ecmascript: Treat `this` as potentially having side effects
(#21297) (sapphi-red)
- bd8bd39 allocator: Remove unsafe hacks from `from_raw_parts` methods
(#21283) (overlookmotel)
- 8f4c340 allocator: Remove dangerous pointer const to mut cast (#21279)
(overlookmotel)
- aa9259f parser: Add missing error code for optional param diagnostic
(#21258) (camc314)
- 04b3c2f str: Fix unsound casting const pointers to mut pointers
(#21242) (overlookmotel)
- ceadf6c str: Make `Ident::from_raw` an unsafe function (#21241)
(overlookmotel)
- eab13b3 transformer/decorators: Avoid accessor storage name collisions
(#21106) (Dunqing)
- 07e8a30 transformer/react-refresh: Handle parenthesized variable
initializers (#21047) (camc314)

### ⚡ Performance

- c3ca6f6 allocator: `StringBuilder::from_strs_array_in` check for 0
length earlier (#21338) (overlookmotel)
- c2422bb allocator: `Allocator::alloc_concat_strs_array` check for 0
length earlier (#21337) (overlookmotel)
- 04b0fdc allocator: Mark `Allocator::alloc_layout` as
`#[inline(always)]` (#21335) (overlookmotel)
- 17aee9e allocator: Use `offset_from_unsigned` in
`ChunkFooter::as_raw_parts` (#21280) (overlookmotel)
- 61adedd minifier: Fix O(n²) perf on very many var decls (#21062)
(Gunnlaugur Thor Briem)
- addcd02 napi/parser, linter/plugins: Raw transfer deserializer for
`Vec`s use shift instead of multiply where possible (#21142)
(overlookmotel)
- 3068ded napi/parser, linter/plugins: Shift before add when calculating
positions in raw transfer deserializer (#21141) (overlookmotel)
- eb400b8 napi/parser, linter/plugins: Remove `uint32` buffer view
(#21140) (overlookmotel)
- 2675085 napi/parser: Lazy deserialization use only `Int32Array`
(#21139) (overlookmotel)
- 5b35a53 napi/parser: Deserializing tokens use only `int32` array
(#21138) (overlookmotel)
- f163d10 parser: Tokens raw deserialization use `Int32Array` (#21137)
(overlookmotel)
- 7a86613 linter/plugins: Use `Int32Array`s for tokens and comments
buffers (#21136) (overlookmotel)
- 8c51121 napi/parser, linter/plugins: Raw transfer deserialize `Span`
fields as `i32`s (#21135) (overlookmotel)
- bc1bcdd napi/parser, linter/plugins: Inline trivial raw transfer field
deserializers into node object definitions (#21134) (overlookmotel)
- c0278ab napi/parser, linter/plugins: Use `Int32Array` in raw transfer
deserializer (#21132) (overlookmotel)
- 43482c7 linter/plugins: Use `>>` not `>>>` in binary search loops
(#21129) (overlookmotel)

### 📚 Documentation

- f5e1845 allocator: Upgrade headers in doc comments for `Bump` (#21263)
(overlookmotel)
- 2870174 allocator: Upper case `SAFETY` in comments (#21253)
(overlookmotel)
- 01bc269 str: Reformat `Ident` doc comments (#21240) (overlookmotel)
- dd47359 allocator: Add doc comments for panics and errors (#21230)
(overlookmotel)
2026-04-13 11:25:53 +01:00
overlookmotel 382958afa8 feat(span)!: remove re-exports of string types from oxc_span crate (#21246)
For historical reasons, `oxc_span` crate was re-exporting string types which now live in `oxc_str` crate.

Remove these re-exports, and import these types directly from `oxc_str`.

Main motivation is just that it makes sense, but it should also have a minor positive effect on compile times - `oxc_span` and `oxc_str` crates can now be compiled in parallel.
2026-04-09 12:06:21 +00:00
Boshen 38aea543e4 release(crates): oxc v0.124.0 (#21084)
### 🐛 Bug Fixes

- fc7f60c allocator: Revert changes to
`get_current_chunk_footer_field_offset` (#20964) (overlookmotel)
- 31316c8 semantic: Rebind class expressions before identifier checks
(#20916) (camc314)

### ⚡ Performance

- fb52383 napi/parser, linter/plugins: Clear buffers and source texts
earlier (#21025) (overlookmotel)
- 3b7dec4 napi/parser, linter/plugins: Use `utf8Slice` for decoding
UTF-8 strings (#21022) (overlookmotel)
- 012c924 napi/parser, linter/plugins: Speed up decoding strings in raw
transfer (#21021) (overlookmotel)
- 55e1e9b napi/parser, linter/plugins: Initialize vars as 0 (#21020)
(overlookmotel)
- c25ef02 napi/parser, linter/plugins: Simplify branch condition in
`deserializeStr` (#21019) (overlookmotel)
- 9f494c3 napi/parser, linter/plugins: Raw transfer use
`String.fromCharCode` in string decoding (#21018) (overlookmotel)
- 91cf105 allocator: Increase initial chunk size from 512B to 16KB
(#20968) (overlookmotel)
- cbc0c21 allocator: Add `#[cold]` to to error handling functions
(#20967) (overlookmotel)
- 0503a78 napi/parser, linter/plugins: Faster deserialization of `raw`
fields (#20923) (overlookmotel)
- a24f75e napi/parser: Optimize string deserialization for non-ASCII
sources (#20834) (Joshua Tuddenham)

### 📚 Documentation

- c78a57a syntax: Fix typo (#21044) (camc314)
- f5e228f allocator: Fix typo in comment (#20972) (overlookmotel)
- 7159d51 allocator: Improve doc comment examples for `vec2::Vec`
(#20969) (overlookmotel)
- b1da750 allocator, data_structures: Correct comments (#20966)
(overlookmotel)

Co-authored-by: Boshen <1430279+Boshen@users.noreply.github.com>
2026-04-07 09:34:33 +09:00
Boshen 990763453c release(crates): oxc v0.123.0 (#20862) 2026-03-30 18:00:11 +08:00
overlookmotel c9cd809e50 refactor(str)!: rename Atom to Str (#20835)
Pure refactor.

Rename `Atom` to `Str`. The name "Atom" is a leftover from when we used to intern strings (years ago), and is misleading now.

Just call it `Str`. This follows the naming convention we have for arena-allocated versions of other types e.g. `Box`, `Vec`, `HashMap` - which we name the same as the native equivalents but with a lifetime (`Box<'a>` not `ArenaBox<'a>`, so `Str<'a>` not `ArenaStr<'a>`).

Rename all variables that contained "atom", and methods which relate to `Str`s to match the new type name.

Rename `as_atom` methods to `as_arena_str`. The longer name is required here to disambiguate from `as_str` methods which return a `&str`.

Some variables called "atom" still exist in `oxc_regular_expression` crate - that's a different meaning of "atom" - the meaning defined in regexp spec.

The diff of this PR is large but it's 100% renaming. No substantive or unrelated changes whatsoever.
2026-03-30 02:40:33 +00:00
Boshen 59fd7975be feat(parser): mark pure comments that cannot be applied (#20687)
## Summary

Adds `CommentContent::PureNotApplied` variant to flag `#__PURE__` / `@__PURE__` annotations that cannot be applied, aligning with [Rollup's behavior](https://rollupjs.org/configuration-options/#pure) for invalid pure comment positions.

### Changes

- `set_pure_on_call_or_new_expr` now returns `bool` so callers detect when the annotation couldn't be applied
- Track the specific pure comment index (`Option<usize>`) instead of a boolean flag, fixing a bug where the wrong comment could be retagged when multiple pure comments exist (e.g. `/*#__PURE__*/ foo + /*#__PURE__*/ bar()`)
- Mark pure comments as `PureNotApplied` in three contexts:
  - **Expression-level**: annotation not before a call/new expression (e.g. `/* #__PURE__ */ a().b`)
  - **Statement-level**: annotation before non-expression statements (e.g. `/* #__PURE__ */ function foo() {}`)
  - **Variable declarator**: annotation before `=` (e.g. `const foo /* #__PURE__ */ = bar()`)
- Downstream consumers (codegen, minifier, Rolldown) can check for `PureNotApplied` to warn or strip

Closes #20334

Rolldown will add custom logic to emit the comments that are `PureNotApplied` so it does not affect the rest of the compiler pipeline.

## Test plan

- [x] Unit tests for all `PureNotApplied` cases (expression, statement, variable declarator)
- [x] Regression test for correct comment targeting with multiple pure comments
- [x] Codegen integration tests updated
- [x] `cargo test -p oxc_parser -p oxc_codegen` passes

🤖 Generated with [Claude Code](https://claude.com/claude-code)
2026-03-25 00:57:41 +00:00
Boshen 77abf546de fix(codegen): preserve coverage comments before ConditionalExpression alternate and between SwitchCases (#20718)
## Summary

- Print leading coverage ignore comments (e.g. `/* istanbul ignore next */`) before `ConditionalExpression`'s alternate expression
- Print leading coverage ignore comments before `case`/`default` keywords in `SwitchStatement`

Closes #20549

🤖 Generated with [Claude Code](https://claude.com/claude-code)
2026-03-25 00:07:22 +00:00
Boshen 9dd33b080c release(crates): oxc v0.122.0 (#20648) 2026-03-23 17:59:21 +08:00
Boshen 6cd513ffae release(crates): oxc v0.121.0 (#20515)
### 🚀 Features

- 7215d9e transformer: Support lowering `accessor` with legacy
decorators (#20348) (Dunqing)

### 🐛 Bug Fixes

- 3bbd0cd transformer: Emit `Object` instead of `void 0` for untyped
getter/setter `design:type` metadata (#20488) (Dunqing)
- 4ae3f3f ecmascript: Apply coercion-is-pure assumption to constructor
side-effect detection (#20420) (Dunqing)
- 11f9695 transformer: Legacy decorator on computed property key leaves
variable unassigned (#20430) (bab)
- efeba28 ecmascript: Add argument validation for NewExpression
side-effect detection (#20395) (Dunqing)

Co-authored-by: Boshen <1430279+Boshen@users.noreply.github.com>
2026-03-19 14:31:00 +08:00
Boshen 8741e6532a release(crates): oxc v0.120.0 (#20422)
### 🐛 Bug Fixes

- edb8677 ecmascript: Treat collection constructor with variable arg as side-effectful (#20383) (Dunqing)
- 1f65c3f transformer: Emit design:paramtypes when class has static anonymous class expression (#20382) (bab)
- fa70d5c transformer: Use implementation signature for design:paramtypes when constructor is overloaded (#20394) (bab)
- ed5a7fb parser: Report syntax error for `new super()` (#20384) (Boshen)
- e62524d minifier: Treat object spread of getters as having side effects (#20380) (Boshen)
- f8fbd6e linter/plugins: Remove `hashbang` property from AST (#20365) (overlookmotel)

### ⚡ Performance

- 30a2b0f minifier: Use atom_from_strs_array for template literal concat (#20386) (Boshen)
- 690ce17 minifier: Use Vec::with_capacity for inline template expressions (#20389) (Boshen)
- 9cd612f linter/plugins: Recycle comment objects (#20362) (overlookmotel)

Co-authored-by: Boshen <1430279+Boshen@users.noreply.github.com>
2026-03-16 10:28:35 +00:00
Boshen e9b5546ed2 release(crates): oxc v0.119.0 (#20371)
### 🚀 Features

- e7163b6 ecmascript: Add known-globals to side-effect-free property
reads (#20212) (Dunqing)
- 139ab68 ecmascript: Add `property_write_side_effects` to
`MayHaveSideEffectsContext` (#20217) (Dunqing)

### 🐛 Bug Fixes

- 78c264a parser: Fix conditional expressions with arrow-function
alternates in TS (#20356) (camc314)
- 5c97b14 minifier: Recognize object spread of object literals as
side-effect-free (#20299) (Boshen)
- 1ff5c1d transformer/typescript: Rewrite extensions in dynamic
`import()` expressions (#20121) (Sverre Johansen)
- 1c07b3b diagnostics: Handle `WouldBlock` in stdout writes to prevent
panic (#20295) (Boshen)
- ade14d4 ecmascript: Enhance side-effect detection for classes,
TypedArrays, computed members, and spread (#20213) (Dunqing)

### ⚡ Performance

- 5474d0a semantic: V8-style walk-up reference resolution (#20292)
(Boshen)

### 📚 Documentation

- e4aa5b5 parser/napi, linter/plugins: Add JSDoc comments to raw
transfer constants (#20286) (overlookmotel)

Co-authored-by: Boshen <1430279+Boshen@users.noreply.github.com>
2026-03-14 17:23:27 +08:00
Boshen abe21615db chore(node): bump .node-version to 24.14.0 (#20261)
Update the pinned Node.js version to 24.14.0 by changing only
.node-version.
2026-03-12 17:00:33 +08:00
Boshen ce4ecb0ffe release(crates): oxc v0.118.0 (#20266)
Co-authored-by: leaysgur <6259812+leaysgur@users.noreply.github.com>
2026-03-12 14:31:12 +09:00
Boshen dafe4ad8cc release(crates): oxc v0.117.0 (#20142)
### 🚀 Features

- e8547cc parser: Report error for using declarations in ambient
contexts (#19934) (camc314)
- 8345318 allocator: Add methods for boxed slices `ArenaBox<[T]>`
(#19968) (overlookmotel)
- f83be30 allocator: Add `Vec::push_fast` method (#19959)
(overlookmotel)

### 🐛 Bug Fixes

- 291d867 transformer_plugins: Unwrap ChainExpression after define
replacement removes optional markers (#20058) (IWANABETHATGUY)
- 36b2e56 codegen: Print type for TSImportEqualsDeclaration (#20128)
(camc314)
- 5a246ec codegen: Print type arguments for JSXOpeningElement (#20127)
(camc314)
- a40870e codegen: Preserve parens for TSNonNullExpression (#20125)
(camc314)
- ae830b2 codegen: Print `declare` for `TSInterfaceDeclaration` (#20124)
(camc314)
- 92cfb14 linter/plugins: Fix types for `walkProgram` and
`walkProgramWithCfg` (#20081) (overlookmotel)
- ee0491e apps,napi: Explicitly specify libs in tsconfigs (#20071)
(camc314)
- 588009e codegen: Print `static` keyword for TSIndexSignature (#19755)
(Dunqing)
- 5a8799c codegen: Print `with_clause` for `ExportNamedDeclaration`
(#20002) (Dunqing)
- 7502afe parser: Correct capacity for tokens `Vec` (#19967)
(overlookmotel)

### ⚡ Performance

- 4ea8f9a napi: Remove `napi_build::setup()` from `oxc_napi` to avoid
redundant rebuilds (#20094) (Boshen)
- 2baa5fb napi: Unify build-test profile to coverage for cache sharing
(#20090) (Boshen)
- 8ba61dd parser: Make pushing tokens faster (#19960) (overlookmotel)

Co-authored-by: Boshen <1430279+Boshen@users.noreply.github.com>
2026-03-09 10:49:21 +00:00
camc314 5f28a3f57b fix(codegen): print type param on class expression with no id (#20144) 2026-03-09 10:35:58 +00:00
Dunqing 0f6eda3d2e fix(codegen): print decorators for FormalParameterRest (#20132)
FormalParameterRest was missing decorator printing, so decorators on
rest parameters (e.g. `@foo ...rest`) were silently dropped during
code generation.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-09 10:35:58 +00:00
camc314 36b2e56910 fix(codegen): print type for TSImportEqualsDeclaration (#20128) 2026-03-09 00:59:52 +00:00
camc314 5a246ec848 fix(codegen): print type arguments for JSXOpeningElement (#20127) 2026-03-09 00:59:52 +00:00
camc314 a40870e838 fix(codegen): preserve parens for TSNonNullExpression (#20125) 2026-03-09 00:59:52 +00:00
camc314 ae830b2466 fix(codegen): print declare for TSInterfaceDeclaration (#20124) 2026-03-09 00:59:52 +00:00
Dunqing 588009ed65 fix(codegen): print static keyword for TSIndexSignature (#19755)
The codegen was missing the `static` keyword when printing `TSIndexSignature`
nodes, causing `static [key: string]: string` index signatures to lose the
`static` modifier during code generation.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-04 16:25:56 +00:00
Dunqing 5a8799c548 fix(codegen): print with_clause for ExportNamedDeclaration (#20002)
Fixes: #20001
2026-03-04 14:19:08 +00:00
Boshen 3a8c4a4cad release(crates): oxc v0.116.0 (#19911)
### 🚀 Features

- 733d6dc parser: Report error on `infer` outside conditional type
(#19879) (camc314)
- c2a42f6 allocator: Add `Vec::into_bump_slice_mut` (#19895)
(overlookmotel)
- ee4982b parser: Add `VARIANTS` const to `Kind` via `fieldless_enum!`
macro (#19877) (overlookmotel)
- b3dceae data_structures: Add `fieldless_enum!` macro (#19876)
(overlookmotel)
- 12b841e parser: Make all `Kind::is_*` methods `const` (#19874)
(overlookmotel)
- 25c2e25 estree/tokens: Add function to update tokens in place (#19856)
(overlookmotel)
- f78e6df parser: Add `mutate_tokens` Cargo feature (#19853)
(overlookmotel)
- 5036bb6 parser: Report error on `for await` in static blocks (#19844)
(camc314)
- 42bd431 parser: Report error for missing initializer in using decl
(#19824) (camc314)
- a2f58e5 parser: Report error for `implements` clause in non-ts files
(#19820) (Cameron)
- b25228a estree: Add `IS_COMPACT` const to `Formatter` trait (#19787)
(overlookmotel)
- e2a1b79 estree: Expose buffer and formatter of serializers (#19773)
(overlookmotel)
- 4699498 data_structures: Add `CodeBuffer::print_strs_array` (#19760)
(overlookmotel)
- 233f947 estree: `oxc_estree` crate export config and formatter types
(#19724) (overlookmotel)
- 5937a32 semantic: Introduce `symbol_declarations` method (#19609)
(camc314)
- ea6b796 parser: Add `LexerConfig::TOKENS_METHOD_IS_STATIC` const
(#19683) (overlookmotel)
- 655c38f semantic: Add "did you mean?" suggestions to undefined name
errors (#19102) (copilot-swe-agent)
- 9e11dc6 parser,estree,coverage: Collect tokens in parser and convert
to ESTree format (#19497) (camc314)
- c4a3677 parser: Report error for initializer in ambient context
(#19187) (camc314)

### 🐛 Bug Fixes

- abc7e19 codegen: Improve parenthesised checks when printing types
(#19880) (camc314)
- 017de5d parser: Update error code for type annotation in `for...in`
statement (#19882) (camc314)
- 7682e5a linter/plugins: Decode escapes in identifier tokens (#19838)
(overlookmotel)
- 06767ed estree/tokens: Convert `this` tokens in `TSTypeName` (#19815)
(overlookmotel)
- ef798af parser: Use TS8037 for satisfies expression in JS files
diagnostic (#19819) (camc314)
- 98ea5c5 parser: Use TS8016 for type assertions in JS files diagnostic
(#19818) (camc314)
- 1710f56 codegen: Remove double indentation for enum inside namespace
(#19775) (Dunqing)
- 9e4995c codegen: Print type annotation on `CatchParameter` (#19790)
(camc314)
- 297b2bb codegen: Wrap `TSConditionalType` in parens when necessary
(#19788) (camc314)
- cec7878 codegen: Print `definite` property on AccessorProperty
(#19786) (camc314)
- 6f395cf codegen: Print `definite` property on PropertyDefinition
(#19785) (camc314)
- b749373 codegen: Correctly parenthesise TSArrayType (#19784) (camc314)
- 876dc1b codegen: Print object property `this` param (#19783) (camc314)
- 93bb861 formatter: Trim trailing whitespace before breaking line
(#19740) (leaysgur)
- ed17bbf codegen: Print `override` keyword for method and property
definitions (#19753) (Dunqing)
- 6a59a76 parser: Improve error recovery for private identifiers in
property names (#19710) (Boshen)
- 3b96f41 codegen: Print comments in JSX expression containers and
spread attributes (#19701) (Boshen)
- f5694ce estree/tokens: Reverse field order of `regex` object in tokens
(#19679) (overlookmotel)
- b2b7a55 estree/tokens: Generate tokens for files with BOM (#19535)
(overlookmotel)
- 50a7514 estree: Fix tokens for JSX (#19524) (overlookmotel)
- a35063e minifier: Preserve side effects for meta property url reads
(#19668) (Boshen)
- 8ad3430 semantic/jsdoc: Handle even-numbered backtick sequences in
JSDoc parsing (#19664) (Boshen)

### ⚡ Performance

- 05ccf9f linter/plugins: Transfer tokens via raw transfer (#19893)
(overlookmotel)
- c1bfdcf estree/tokens: Preallocate sufficient space for tokens JSON
(#19851) (overlookmotel)
- 4b0611a estree/tokens: Introduce `ESTreeTokenConfig` trait (#19842)
(overlookmotel)
- 81bab90 estree/tokens: Do not JSON-encode keyword, punctuator, etc
tokens (#19814) (overlookmotel)
- 6260ddd estree/tokens: Do not JSON-encode `this` identifiers (#19813)
(overlookmotel)
- b378f4a estree/tokens: Do not JSON-encode JSX identifiers (#19812)
(overlookmotel)
- 5016d92 estree/tokens: Handle regex tokens separately (#19796)
(overlookmotel)
- 780a68e estree/tokens: Use strings from AST for identifier tokens
(#19744) (overlookmotel)
- dc9c2e3 estree: Use `CodeBuffer::print_strs_array` to reduce bounds
checks (#19766) (overlookmotel)
- 845da35 estree: Use `CodeBuffer::print_indent` (#19727)
(overlookmotel)
- ec88f6a estree/tokens: Serialize tokens while visiting AST (#19726)
(overlookmotel)
- bc6507f estree/tokens: Serialize with `ESTree` not `serde` (#19725)
(overlookmotel)
- ec24859 estree/tokens: Do not branch on presence of override twice
(#19721) (overlookmotel)
- dac14be estree/tokens: Replace hash map with `Vec` (#19718)
(overlookmotel)
- b9d2443 estree/tokens: Replace multiple hash sets into a single hash
map (#19716) (overlookmotel)
- 7233548 parser: Remove branches from `finish_next_inner` (#19695)
(overlookmotel)
- b5d9845 parser: Remove const generic param from `finish_next_inner`
(#19684) (overlookmotel)
- 8940f66 estree/tokens: Serialize tokens to compact JSON (#19572)
(overlookmotel)
- 136e39b parser/tokens: Pre-allocate capacity for tokens (#19543)
(overlookmotel)
- 6a6513c linter/plugins: Use Oxc tokens in plugins (#19498) (camc314)
- b3b2d30 parser: Introduce `ParserConfig` (#19637) (overlookmotel)

### 📚 Documentation

- b2b7a64 estree/tokens: Correct comment (#19873) (overlookmotel)
- 0399311 estree/tokens: Improve comments (#19836) (overlookmotel)
- 1b392de minifier: Add `Function.prototype.toString` assumption
(#19758) (sapphi-red)
- 75c9cd8 parser: Improve doc comments for `ParserConfig` and
`LexerConfig` (#19682) (overlookmotel)
- 2fa936f README.md: Map npm package links to npmx.dev (#19666) (Boshen)

Co-authored-by: Boshen <1430279+Boshen@users.noreply.github.com>
2026-03-02 11:21:50 +00:00
camc314 abc7e19b98 fix(codegen): improve parenthesised checks when printing types (#19880) 2026-03-02 02:18:36 +00:00