Function parameters, TypeScript signatures, and function bodies currently share one Oxc semantic scope. A reference in a parameter can therefore bind to a declaration inside the body, even though JavaScript does not make body declarations visible there. Rolldown may then treat a global as local, skip a configured define, or remove live code.
## Example
```js
export function load(value = typeof window !== "undefined") {
var window;
return value;
}
```
The body `var window` is not visible to the default value. Before this change, Oxc resolved `window` in the default value to that body declaration. It should remain a global reference.
The workaround resolves parameter and signature references before visiting the body, while only parameter bindings are present. If a reference is still unresolved, its `lookup_scope_id` advances to the function's parent. Final resolution resumes there, so declarations added while visiting the body are skipped. References created in the body still begin at the function scope and resolve normally.
```text
Before: parameter reference -> completed function scope -> body binding (wrong)
After: parameter reference -> parameter bindings -> parent scopes
body reference -> completed function scope -> parent scopes
```
Parameter decorators already begin in the enclosing class scope, so they are left for normal final resolution. This emulates separate parameter and body scopes until https://github.com/oxc-project/backlog/issues/176 is implemented.
The corrected semantic data also exposes the transformer case covered by #26105.
Verified with semantic and transformer-plugin tests, Clippy, coverage, allocation snapshots, and diff checks. `just ready` completed workspace checks but stopped at a codegen snapshot recorded with Node.js v26.5.0; the local version is v25.8.1.
Closes#20427Closes#22783
Downstream reports:
- https://github.com/rolldown/rolldown/issues/10722
- https://github.com/rolldown/rolldown/issues/10779
AI assistance: OpenAI Codex was used to investigate, implement, and test this change. The contributor is responsible for the submitted change.
Fix the transformer conformance runner incorrectly marking a fixture as passed that specified `throws` when Oxc produces no error.
Failed conformance cases now always record a diagnostic. This exposes previously hidden failures in the Babel snapshot, including the nested ambient-module fixtures.
Quoted module names are only valid in ambient contexts in TypeScript, but we were accepting them in regular TypeScript files.
This reports TS1035 when a quoted module name appears outside a declaration file or ambient declaration. The conformance snapshots now cover both TypeScript cases, and the old invalid codegen fixture has been replaced with a valid internal module declaration.
Fixes `import =` semantic reference resolution so internal module references are resolved as namespace lookups instead of ordinary value reads.
TypeScript treats the RHS of an internal `import =` specially. In the checker, `getTargetOfImportEqualsDeclaration` delegates internal module references to `getSymbolOfPartOfRightHandSideOfImportEquals`, which resolves bare RHS names and intermediate qualified names with `SymbolFlags.Namespace` rather than value meaning:
- `getTargetOfImportEqualsDeclaration`: https://github.com/microsoft/TypeScript/blob/f350b52331494b68c90ab02e2b6d0828d2a22a74/src/compiler/checker.ts#L3708-L3733
- `getSymbolOfPartOfRightHandSideOfImportEquals`: https://github.com/microsoft/TypeScript/blob/f350b52331494b68c90ab02e2b6d0828d2a22a74/src/compiler/checker.ts#L4480-L4499
- `getSymbolOfNameOrPropertyAccessExpression` also routes names on the RHS of import/export assignments through that same helper: https://github.com/microsoft/TypeScript/blob/f350b52331494b68c90ab02e2b6d0828d2a22a74/src/compiler/checker.ts#L50014-L50019
Before this change, Oxc could count plain values as references from `import =`:
```ts
const x = 1;
import foo = x;
```
Before:
```text
x references: 1
```
After:
```text
x references: 0
```
That matches TypeScript’s behavior because `x` is only a value symbol, not a namespace-capable symbol.
The same applies to qualified names:
```ts
const x = { y: 1 };
import foo = x.y;
```
Before:
```text
x references: 1
```
After:
```text
x references: 0
```
But namespace-capable declarations still resolve:
```ts
namespace x {}
import foo = x;
```
After:
```text
x references: 1
```
and:
```ts
namespace x {
export namespace y {}
}
import foo = x.y;
```
After:
```text
x references: 1
```
This updates the semantic snapshots to reflect the corrected reference/declaration matching.
## Summary
Remove TypeScript enum-member bindings after transformation.
Enum members are represented as bindings during semantic analysis so the transformer can resolve member values, fold references, and handle merged enums. Once TypeScript transformation finishes, those bindings no longer correspond to emitted JavaScript declarations.
Include `EnumMember` in the existing final TypeScript binding cleanup instead of removing bindings during enum lowering, where later references may still need them.
This fixes `discriminatedUnionTypes4.ts` and removes the same stale binding mismatch from other enum cases.
Closes#24224 — the first commit is @camc314's fix from there.
Lowered namespaces kept their `ValueModule`/`NameSpaceModule` symbol flags, so the flags no longer matched the emitted JavaScript:
- Namespaces lowered to a declaration become `let` → `BlockScopedVariable`.
- Namespaces lowered to an assignment only lose their module bits.
This removes over 2,000 stale symbol-flag mismatches from the snapshots.
Unlike #24224 there is no pending state: the type-only check for merged namespaces now reads per-declaration flags from the redeclaration list instead of the symbol's live flags, so each declaration can update the flags right when it is lowered.
Closes#24226 — the first commit is @camc314's fix from there.
Lowered enums kept their `RegularEnum`/`ConstEnum` symbol flags, so the flags no longer matched the emitted JavaScript:
- Top-level enums become `var` → `FunctionScopedVariable`.
- Exported and nested enums become `let` → `BlockScopedVariable`.
- Merged enums lowered to an assignment only lose their enum bits.
This removes over 1,000 stale symbol-flag mismatches from the snapshots.
Unlike #24226 there is no pending state: enum member inlining now identifies enums through `EnumData` (#24268) instead of `SymbolFlags`, so the flags can be updated right when the enum is lowered.
## Summary
TypeScript enum lowering reuses the enum body’s scope for the generated function expression. Update that scope with `ScopeFlags::Function` so transformed semantic data matches a freshly rebuilt AST.
## Summary
Keep transformer semantic data in sync when TypeScript-only syntax is removed.
This change:
- removes resolved and unresolved references belonging only to stripped TypeScript syntax
- removes bindings for erased type-only and unused imports
- preserves runtime bindings when a type import is merged with a value declaration
- promotes the surviving declaration’s symbol flags, span, and redeclaration metadata
- adds coverage for type imports merged with runtime declarations
- refreshes semantic and transformer conformance snapshots
## Motivation
We are preparing to change the AST shape, including adding and rearranging scopes.
Currently, transformer semantic snapshots contain thousands of lines of mismatches caused by stale bindings and references from TypeScript syntax that has already been removed from the AST. That creates a large amount of unrelated snapshot noise.
With that noise present, snapshot changes caused by the upcoming AST work would be difficult to review: a real scope or semantic regression could easily be hidden among mechanical churn.
This PR fixes the underlying semantic inconsistencies first, giving us a much cleaner baseline for reviewing future AST and scope changes. It is not intended to change emitted JavaScript.
In #24078, the snapshot generation was missed, which caused the CI to fail on all subsequent PRs.
Also fixes typo in CI trigger, which should prevent this. 🙈
- Store class property definite assignment assertion positions as `u32` offsets instead of carrying a full `Span`.
- Reconstruct the one-character diagnostic span only when emitting class definite-assignment diagnostics.
- aligns the behaviour for definite assertion errors with variables by reporting on the definite assertion rather than on the whole class member
- Match TypeScript’s diagnostic precedence for class property definite assignment assertions.
- Report TS1264 when a class property uses ! without a type annotation.
- Report TS1255 when a definite assignment assertion is used in disallowed class property contexts, including static.
Fixes private method transforms so scopes inherited from a transformed private method are converted back to sloppy mode when the surrounding scope is sloppy.
Previously we only cleared `StrictMode` on the private method function scope itself. That left child scopes, such as async/generator wrapper scopes, marked as strict even though the transformed output is no longer inside a class method. This caused semantic rebuild mismatches across Babel and Test262 coverage.
Nested classes are still left strict, since class bodies are always strict mode.
Refs vitejs/vite#22452 (comment).
The optimize pass dropped the enum declaration whenever the members were all evaluable — regardless of whether some non-inlinable value reference still named the enum at runtime. The result referenced a binding that no longer existed:
```ts
const enum Phase { one = 'one' }
export default Phase;
// -> export default Phase; // ReferenceError at runtime
enum Direction { Up }
Direction.Up.toString();
// -> Direction.Up.toString(); // ReferenceError at runtime
```
## Fix
Decide based on the remaining resolved references: drop only when none of them is a value reference (`Read`/`Write`). Type references (`as E`, `: E`) are kept here and stripped later by `annotations.rs`, so they don't block removal. `typeof E` in JS expression position is `Read` and correctly keeps the IIFE; `typeof E` in TS type position is `ValueAsType` (not in `Value`) and doesn't.
Unifies the rule for regular and const enums — the previous asymmetry (const always dropped, regular dropped only when no refs at all) had no principled basis.
## Compatibility
Diverges from Babel on two `optimize-const-enums/*` fixtures where the input has a bare value reference to the enum that we can't inline. Three engines disagree on what to do:
| Engine | Inline `E.X` member accesses | Preserve `E` binding (IIFE) | Result for `E.unknown` / bare `E` |
|---|---|---|---|
| Babel `transform-typescript` (optimize-const-enums) | yes | **no** | runtime ReferenceError / TypeError |
| tsc `--isolatedModules` | no | yes | `undefined` / resolves |
| oxc after this PR | yes | yes | `undefined` / resolves |
We now hybridize: inline what's inlinable (Babel) **and** keep the binding (tsc). Local overrides under `tasks/transform_conformance/overrides/` record the new expected output for the two affected Babel fixtures.
### `optimize-const-enums/local`
Input:
```ts
const enum A {
x, y
}
A.x;
A["y"];
A.z;
A;
```
Babel (and oxc before this PR):
```js
0;
1;
A.z;
A;
```
`A.z` is `TypeError: cannot read properties of undefined`; `A;` is `ReferenceError`.
tsc (`--isolatedModules`):
```js
var A;
(function (A) {
A[A["x"] = 0] = "x";
A[A["y"] = 1] = "y";
})(A || (A = {}));
A.x;
A["y"];
A.z;
A;
```
Keeps the IIFE binding, no member-access inlining. `A.z` evaluates to `undefined`; `A;` is a no-op.
oxc after this PR (`overrides/.../optimize-const-enums/local/output.mjs`):
```js
var A = /* @__PURE__ */ function(A) {
A[A["x"] = 0] = "x";
A[A["y"] = 1] = "y";
return A;
}(A || {});
0;
1;
A.z;
A;
```
Hybrid: inlines `A.x` / `A["y"]` like Babel, **and** keeps the IIFE binding like tsc — so `A.z` evaluates to `undefined` (not crash) and `A;` resolves.
### `optimize-const-enums/merged`
Input:
```ts
const enum A {
x, y
}
const enum A {
z
}
A.x;
A["y"];
A.z;
A.w;
A;
```
Babel (and oxc before this PR):
```js
0;
1;
0;
A.w;
A;
```
`A.w` is `TypeError: cannot read properties of undefined`; `A;` is `ReferenceError`.
tsc (`--isolatedModules`):
```js
var A;
(function (A) {
A[A["x"] = 0] = "x";
A[A["y"] = 1] = "y";
})(A || (A = {}));
(function (A) {
A[A["z"] = 0] = "z";
})(A || (A = {}));
A.x;
A["y"];
A.z;
A.w;
A;
```
Both IIFEs emitted, no inlining. `A.w` is `undefined`; `A;` resolves.
oxc after this PR (`overrides/.../optimize-const-enums/merged/output.mjs`):
```js
var A = /* @__PURE__ */ function(A) {
A[A["x"] = 0] = "x";
A[A["y"] = 1] = "y";
return A;
}(A || {});
A = /* @__PURE__ */ function(A) {
A[A["z"] = 0] = "z";
return A;
}(A || {});
0;
1;
0;
A.w;
A;
```
Hybrid: both enum bodies lower (the second reuses the first's binding via `A = (function(A) { … })(A || {})` — assignment, not `var`) **and** members are inlined like Babel. `A.w` evaluates to `undefined`; `A;` resolves.
## Verification
New fixtures cover the bug shapes:
- `babel-plugin-transform-typescript/const-enum-value-ref-kept/` — `export default Phase`
- `babel-plugin-transform-typescript/const-enum-mixed-refs/` — member access + bare ref combined
Existing `optimize-enums/type-cast` updated to drop the IIFE for the all-type-refs case (the regular-enum side of the unified rule).
Given:
```
for (using x of y) { const x = z; }
```
Previously we would produce
```
var _usingCtx2 = require("@oxc-project/runtime/helpers/usingCtx");
for (const _x of y) try {
var _usingCtx = _usingCtx2();
const x = _usingCtx.u(_x);
const x = z;
} catch (_) {
_usingCtx.e = _;
} finally {
_usingCtx.d();
}
```
Now we produce
```
var _usingCtx2 = require("@oxc-project/runtime/helpers/usingCtx");
for (const _x of y) try {
var _usingCtx = _usingCtx2();
const x = _usingCtx.u(_x);
{
const x = z;
}
} catch (_) {
_usingCtx.e = _;
} finally {
_usingCtx.d();
}
```
Which avoids a syntax error - cannot create a duplicate var named `x`.
Given some code like
```js
const {
[({ ...rest }) => {
let { ...b } = {};
}]: a,
[({ ...d } = {})]: c,
} = {};
export {}; // necessary so we are in strict mode
```
It would previously be transformed to:
```js
const { [(_ref) => {
let rest = _extends({}, (_objectDestructuringEmpty(_ref), _ref));
let _ref2 = {}, b = _extends({}, (_objectDestructuringEmpty(_ref2), _ref2));
}]: a, [(_ref3 = {}, {} = _ref3, d = _extends({}, (_objectDestructuringEmpty(_ref3), _ref3)), _ref3)]: c } = {};
export {};
```
This is a problem because there was no declaration to `_ref3`
This causes runtime errors.
After this PR, we now emit:
This new code includes `var _ref3`, fixing the unresolved reference issue.
```js
var _ref3;
const {
[_ref => {
let rest = babelHelpers.extends({}, (babelHelpers.objectDestructuringEmpty(_ref), _ref));
let _ref2 = {},
b = babelHelpers.extends({}, (babelHelpers.objectDestructuringEmpty(_ref2), _ref2));
}]: a,
[(_ref3 = {}, {} = _ref3, d = babelHelpers.extends({}, (babelHelpers.objectDestructuringEmpty(_ref3), _ref3)), _ref3)]: c
} = {};
```
This aligns with Babel.
----
This has been fixed by walking up to find the containing statement, and inserting the var declaration before it.
Previously, the `var` declaration would only be inserted if we were inside `ExpressionStatementExpression` which was not guaranteed.
Stacked on #22305.
## Why
`class C { static getSelf() { return C } }` lowered by the explicit resource management transform was emitting `var C = class {}` (anonymous), so when the outer `C` is reassigned (`C = 123`), `getSelf()` returns the reassigned value instead of the original class — the exact behaviour the named class expression's inner binding is supposed to protect against. Babel emits `var C = class C {}` for the same input.
## Fix
1. **Emit `var C = class C {}`** for both `class C {}` and `export default class C {}`. Adds a `preserve_class_expression_name` helper that mirrors the swap in `decorator::legacy::transform_class_declaration_with_class_decorators` — generate a fresh `Class`-flagged symbol in the class scope for the inner class id, swap `class_decl.id.symbol_id` (via `Cell::replace`) to the new symbol, and repurpose the original symbol as the outer `var` (flags → `FunctionScopedVariable`). Returns the outer `BoundIdentifier` and the original span so the caller can emit the outer declarator with the correct span.
2. **Carry the original span through both sides of the swap.** The inner symbol is created with the original `id.span` (via `Scoping::create_symbol(span, ...)` + `add_binding`); the outer var's `BindingIdentifier` is emitted with the same span (via `BoundIdentifier::create_spanned_binding_pattern`, added in #22305). This eliminates the `Symbol span mismatch` diffs in:
- `transform-top-level/hoisting/input.mjs`
- `transform-top-level/hoisting-default-class/input.mjs`
- `export-class-name/input.js`
## Comparison with Babel
Babel reuses the *original `id` node* for the outer `var` and clones it for the inner class. This PR does the inverse — reuses the original *symbol id* for the outer `var` and generates a new symbol for the inner class. Given oxc's symbol-aware model, the inversion avoids rewiring every outer-scope reference (`const K = C`, `C = 123`, …): they already point at the original symbol.
## Remaining follow-up
`export-class-name/input.js` still has `Symbol reference IDs mismatch` for `C` — references inside the class body (`return C`) still resolve to the outer symbol in the transformer's bookkeeping. A fresh semantic rebuild over the printed AST correctly resolves them to the inner class symbol, so tools that re-run semantic (rolldown / oxc_minifier on a fresh build) are fine. Tools that trust the transformer's symbol table directly (in-place minification / mangler) will see the stale binding. Rewiring those references is a separate follow-up (`Reference.symbol_id` update + `delete_resolved_reference` / `add_resolved_reference`).
## Conformance impact
- Babel suite: **692 → 694 passing** (+2)
- `transform-top-level/hoisting/input.mjs` ✓
- `transform-top-level/hoisting-default-class/input.mjs` ✓
- `export-class-name/input.js`: 4 span mismatches eliminated; reference-rewiring follow-up remains.
## Test plan
- [x] `cargo run -p oxc_transform_conformance`
- [x] `cargo run -p oxc_transform_conformance -- --exec`
- [x] `cargo test -p oxc_transformer`
## Summary
Depends on #20602.
Closes: https://github.com/oxc-project/oxc/issues/6073Closes: #11844
- Inline const enum member accesses (`Foo.Bar` / `Foo["Bar"]`) to literal values when `optimize_const_enums` is enabled
- Remove non-exported const enum declarations when all members are evaluable
- Use `exit_statements` for enum removal so inlining happens before removal
- Delete references when inlining enum member accesses for correct semantic data
- Handle `IdentifierReferenceRename` for sibling enum member references in merged declarations
## Test plan
- [x] Transform conformance tests pass (`cargo run -p oxc_transform_conformance`)
- [x] `cargo test -p oxc_transformer` passes
- [x] Babel conformance snapshot updated
## Summary
- Replace bubble-up reference resolution with V8-style walk-up algorithm
- References are collected in a flat `Vec<(Ident, ReferenceId)>` during traversal instead of per-scope hashmaps
- After full AST visit, all references are resolved in a single pass by walking up the scope chain from each reference's scope
- `leave_scope()` no longer does any reference resolution work — only `direct_eval` flag propagation remains
- Early resolution via checkpoint mechanism preserved for function parameters and catch parameters (prevents binding to body variables that share the same scope)
- Deduplicated walk-up logic into a single `#[inline(always)]` helper shared by both normal and early resolution paths
- Uses `to_vec+truncate` instead of `split_off` to preserve `Vec` capacity and avoid reallocation
- Removes `smallvec` and `oxc_data_structures` dependencies from `oxc_semantic`
### Why this is faster
| Operation | Bubble-up (old) | Walk-up (new) |
|-----------|-----------------|---------------|
| Per reference creation | Hashmap insert | Vec push (O(1) amortized) |
| Per scope exit | Drain + merge hashmap | Nothing |
| Per reference resolution | Implicit via merging | Walk scope chain, O(depth) lookups |
| Total hashmap mutations | O(refs × depth) inserts+drains | 0 during traversal |
Hashmap lookups (read-only) are cheaper than hashmap drain+insert (mutating, allocating). The flat Vec also eliminates creating/recycling per-depth hashmaps entirely.
### Snapshot changes
3 jest linter rule snapshots have diagnostic reordering (same diagnostics, different emission order) due to references being processed in insertion order rather than scope-by-scope.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
## Summary
- Skip the trailing reference (e.g. `_c`) in the generated sequence expression when the destructuring assignment is directly inside an `ExpressionStatement`, since the expression result is not consumed
- Before: `_c = c2, {a2} = _c, b2 = objectWithoutProperties(_c, ["a2"]), _c;`
- After: `_c = c2, {a2} = _c, b2 = objectWithoutProperties(_c, ["a2"]);`
- The trailing reference is still kept when the result is consumed, e.g. `console.log((..., _c))`
Closes#7389 (issue 1)
🤖 Generated with [Claude Code](https://claude.com/claude-code)
## Summary
- Skip tests in transform conformance that expect parser errors
- Parser errors are already tested by parser conformance tests
- Transform conformance should only test transformation logic
When a test has a `throws` option, we now try parsing the input first. If parsing fails, the test is skipped since it's a parser error test (not a transformer error test).
🤖 Generated with [Claude Code](https://claude.com/claude-code)