#26099 resolves parameter and signature references before visiting the function body, so they cannot bind to declarations that only exist inside the body. That early pass only ran when the function had parameters or a return type. Type parameter constraints and a `this` parameter type are visited before that check, so a function whose signature has references only in those positions skipped the pass. Its references then resolved after the body was visited and bound to body-local types.
## Example
```ts
type U = number;
function f<T extends U>() {
type U = string;
return null! as T;
}
```
Before this change, `U` in the constraint resolved to the body-local `type U = string`. TypeScript scopes local types to the function body, so it must resolve to the outer alias. The same happened for `function f(this: U) { type U = string }` and for arrow functions with type parameters.
The early pass now runs for every function and arrow function. It returns immediately when the signature produced no references, so the `has_parameter() || return_type.is_some()` condition, which approximated that check, is no longer needed.
Also adds a regression test for the compaction in `resolve_references_for_current_scope`: a resolved reference followed by an unresolved one must neither drop nor duplicate entries, and no existing test covered that ordering.
Verified with the semantic and transformer unit tests, Clippy, `cargo coverage -- semantic`, and transform conformance; no snapshots changed.
AI assistance: Claude Code was used to investigate, implement, and verify this change. The contributor is responsible for the submitted change.
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.
## Summary
- report TS1234 for function-local ambient module declarations
- preserve TS1235 for function-local namespace and internal module declarations
- report TS2435 for ambient modules nested in namespaces while allowing module augmentation inside ambient external modules
## Babel Conformance Snapshot Parse Failure
This intentionally introduces one known Babel conformance false positive: `typescript/scope/redeclaration-in-nested-module/input.ts`. The Babel harness supplies `sourceType: "module"`, so Oxc reports TS2435 for its nested ambient module. This affects one unique fixture in both the parser and semantic Babel summaries. This change aligns with TS, and TS expects this error.
## Summary
- Introduces `ArrowFunctionBody` to represent concise expression and block bodies explicitly.
- Removes the `ArrowFunctionExpression::expression` boolean.
- Makes invalid arrow body combinations unrepresentable.
## Breaking Change
The Rust AST changes from:
```rust
pub struct ArrowFunctionExpression<'a> {
pub expression: bool,
pub body: Box<'a, FunctionBody<'a>>,
}
```
to:
```rust
pub enum ArrowFunctionBody<'a> {
FunctionBody(Box<'a, FunctionBody<'a>>) = 64,
INHERIT(Expression<'a>),
}
pub struct ArrowFunctionExpression<'a> {
pub body: ArrowFunctionBody<'a>,
}
```
Concise arrow bodies are now stored directly as expressions instead of synthetic `FunctionBody` and `ExpressionStatement` nodes. Block bodies continue to use `FunctionBody`.
## Why?
The previous representation required consumers to maintain this implicit invariant:
```text
expression == true
→ no directives
→ exactly one statement
→ that statement is an ExpressionStatement
```
Invalid combinations could cause panics, skipped work, or fallback behavior. The enum encodes the grammar directly and makes those invalid states unrepresentable.
Concise expressions also now have `ArrowFunctionExpression` as their direct traversal ancestor, without synthetic `FunctionBody` or `ExpressionStatement` nodes.
## How to migrate
Use the arrow body accessors or match on `ArrowFunctionBody` rather than inspecting `expression` and synthetic statements.
Common field migrations:
| Previous representation | New representation |
| --- | --- |
| `arrow.expression` | `arrow.is_expression()` |
| `arrow.get_expression()` | `arrow.get_expression()` |
| `&arrow.body.statements` | `arrow.get_function_body().map(\|body\| &body.statements)` |
| `&mut arrow.body.statements` | `arrow.get_function_body_mut().map(\|body\| &mut body.statements)` |
| Synthetic expression statement in `arrow.body` | Direct `ArrowFunctionBody` expression variant |
| `arrow.body = function_body` | `arrow.body = ArrowFunctionBody::FunctionBody(function_body)` |
| Expression-to-block conversion | Create a `FunctionBody` containing a return statement |
| Block-to-expression conversion | Assign the expression directly to `arrow.body` |
| Builder `(expression, body)` arguments | Pass a single `ArrowFunctionBody` |
closes https://github.com/oxc-project/backlog/issues/211
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
- mark computed method keys in ambient and abstract classes as type references
- preserve runtime read flags for concrete computed methods
- bound declare-class ancestry checks to the containing class
- add semantic snapshot coverage and update the TypeScript conformance snapshot
Follows the work done in 588d9971ac, 9b95632179
## Summary
- resolve declared class heritage expressions through ValueAsType so their final references are Type
- allow type-only namespace imports in declared heritage while preserving Read for runtime class heritage
- add regression coverage for type-only namespace imports, value namespace imports, local bases, and a runtime control
- update semantic conformance snapshots, yielding two additional TypeScript passes
## Summary
- resolve computed declare class-field keys through ValueAsType so their final references are Type
- allow declared keys to resolve type-only import bindings while preserving Read for ordinary runtime class fields
- add a red/green semantic snapshot and update conformance snapshots, yielding one additional TypeScript semantic pass and one additional transform-conformance pass
## Summary
- resolve computed TypeScript method, getter, and setter keys through ValueAsType so their final references are Type
- allow those keys to resolve value bindings and type-only import bindings consistently with computed property signatures and type queries
- add regression coverage and update semantic conformance snapshots, yielding one additional Babel pass and six additional TypeScript passes
Handled for TSPropertySignature via https://github.com/oxc-project/oxc/commit/d8b9909bd8df193306de7ff6f1204f3ac0963076
## Summary
Correct the CFG generated for `for` statements whose update expression spans multiple basic blocks, such as conditional or logical expressions.
This addresses the malformed CFG underlying #23789.
## Problem
`update_graph_ix` identifies the entry of the update expression. After visiting the expression, `cfg.current_node_ix` identifies its exit block.
Previously, the loop backedge to the test originated from the update entry. This allowed control flow to bypass the update expression and left its exit block disconnected.
### Before
```mermaid
flowchart LR
Test["Loop test"] -->|truthy| Body["Loop body"]
Test -->|falsy| After["After loop"]
Body -->|backedge| Entry["Update entry"]
Entry --> Update["Update expression blocks"]
Update --> Exit["Update exit"]
Entry -->|backedge| Test
```
### After
```mermaid
flowchart LR
Test["Loop test"] -->|truthy| Body["Loop body"]
Test -->|falsy| After["After loop"]
Body -->|backedge| Entry["Update entry"]
Entry --> Update["Update expression blocks"]
Update --> Exit["Update exit"]
Exit -->|backedge| Test
```
## Implementation
Record `cfg.current_node_ix` after visiting the update expression as `after_update_graph_ix`. The backedge to the loop test now originates from that exit block.
The loop body backedge and `continue` target still point to `update_graph_ix`, ensuring the complete update expression runs before the next test.
A dedicated CFG fixture covers a conditional update expression:
```js
forward ? index++ : index--
```
Correct the CFG generated for `while` statements whose test expression creates multiple basic blocks, such as logical or conditional expressions.
Previously, the loop body and exit edges originated from the test expression's entry block. They now originate from its exit block after the complete expression has been evaluated.
## Before
The body and exit edges could bypass the test expression, leaving its exit block disconnected.
```mermaid
flowchart LR
Entry["Test entry"] --> Test["Test expression"]
Test --> Exit["Test exit"]
Entry -->|true| Body["Loop body"]
Entry -->|false| After["After while"]
Body -->|backedge| Entry
```
## After
The complete test expression is evaluated before control branches to the loop body or exit.
```mermaid
flowchart LR
Entry["Test entry"] --> Test["Test expression"]
Test --> Exit["Test exit"]
Exit -->|true| Body["Loop body"]
Exit -->|false| After["After while"]
Body -->|backedge| Entry
```
The implementation records cfg.current_node_ix after visiting the test expression as after_test_graph_ix, then uses that block for the body and exit edges. The loop backedge and continue target remain connected to the test entry so each iteration evaluates the expression again.
## Summary
Introduces `oxc_diagnostics::Diagnostics` — a `Vec<OxcDiagnostic>` newtype that knows the difference between errors and warnings — and makes it the standard diagnostics return value across oxc.
- **New type**: `Diagnostics` with `has_errors()`, `has_warnings()`, `errors()`, `warnings()`, plus `Vec`-like ergonomics (Deref, `IntoIterator`, `Extend`, `From`/`Into<Vec>`) so most call sites are unchanged.
- **Return types**: `ParserReturn`, `SemanticBuilderReturn`, `IsolatedDeclarationsReturn`, the React Compiler `TransformResult`/`LintResult`, and `TransformerReturn` now expose `diagnostics: Diagnostics` instead of `errors: Vec<OxcDiagnostic>` (the React Compiler's separate `errors`/`warnings` are merged into one severity-tagged list).
- **Behaviour**: a React Compiler **error** now stops the transform (no output), while **warnings** flow through and the transform continues. `compile()` aborts codegen only when `diagnostics.has_errors()` — warnings alone no longer abort (previously any diagnostic did).
## Breaking change
Consumers reading `*.errors` on these return values must read `*.diagnostics`. React Compiler consumers that read `.errors`/`.warnings` separately should use `diagnostics.has_errors()` / `diagnostics.errors()` / `diagnostics.warnings()`.
Parser/semantic/isolated-declarations fatality is otherwise unchanged. Builds on the React Compiler transform feature (#23201).
🤖 Generated with [Claude Code](https://claude.com/claude-code)
## What
Make the full `AstNodes` store **opt-in**, so the compiler pipeline (transformer / codegen / minifier) can run semantic analysis without building it at all.
Previously every `SemanticBuilder` run allocated and populated the full `AstNodes` store, even for consumers that only need scoping + the syntax checker. This separates the node-related builder state into three independent pieces:
- a standalone `NodeId` counter — the source of truth for node ids, valid in either mode;
- an **ancestry stack** — an upward-walk-only stack of the current node's ancestors, the only ancestry the syntax checker and binder actually read;
- the full **`AstNodes`** store — random access to every node, needed by the linter and mangler.
## How
- A new `AstNodeStore` (in `crates/oxc_semantic/src/node/store.rs`) bundles the node-id counter, the current-node cursor/flags, and the storage. The storage is an enum (`AstNodeStoreKind`) with two variants — `Full(AstNodes)` and `Ancestry(AncestryStack)` — so the full store and the ancestry stack are **mutually exclusive by construction**; they can never both be maintained at once.
- The checker and binder read ancestry through an `Ancestry` view (`node/ancestry.rs`) that dispatches between the full store (linter / mangler) and the stack (compiler pipeline). They no longer do random `NodeId` access into the store — all ancestry access is upward-walk-only.
- `SemanticBuilder` gains `with_build_nodes(bool)`. The default is **off** (ancestry stack only). `new_linter()` turns it on (the linter needs the full store); `new_compiler()` leaves it off.
- `CompilerInterface::build_semantic_nodes()` lets `oxc::Compiler` consumers opt back in if their `after_semantic` hook reads `Semantic::nodes`.
## Notes
- Behaviour-neutral: semantic conformance snapshots are unchanged.
- Allocation snapshots updated — the default (ancestry) path allocates slightly less (the growing `Stack` trades a couple of fixed allocations for a few reallocs).
- Builds on the already-merged `SymbolFlags`-based redeclaration checks (#23060) and the `new_linter`/`new_compiler` preset adoption (#23057), which removed the last random node reads from the redeclaration path so the checker works without the store.
Encode whether a function binding is a named function expression or an `async`/generator function as two internal `SymbolFlags` bits (`FunctionExpression`, `AsyncOrGeneratorFunction`), set at bind time.
The redeclaration checks now read these flags instead of the AST node:
- `check_redeclaration` checks `FunctionExpression` rather than fetching the declaration node to ask `Function::is_expression`.
- `check_redeclared_function` (Annex B.3.3) checks `AsyncOrGeneratorFunction` on each previous declaration, replacing the build-only `async_or_generator_function_node_ids` Vec and its linear scan.
The transformer keeps the flags accurate when it rewrites functions, via a new `sync_function_symbol_flags` helper applied at the function-rewriting sites in `async_to_generator` and class private-method extraction.
Behaviour-neutral: semantic conformance snapshots are unchanged.
Replaces ad-hoc `SemanticBuilder::new().with_*()` chains with the `new_linter()` / `new_compiler()` presets where the preset already expands to the exact same option set, so the config lives in one place.
- linter example + linter benchmark → `new_linter()` (cfg + class table + syntax)
- semantic benchmark, cfg example, integration test util → `new_compiler()` (syntax)
Behavior-neutral — each preset matches the options the callsite set by hand. Carved out of the larger store-optional refactor so it can land independently on `main` first.
## Summary
Adds two named constructor presets to `SemanticBuilder` that bake in the options each use case needs, so the configuration lives in one place instead of being repeated at call sites:
- **`SemanticBuilder::new_compiler()`** — compiler pipeline. Enables syntax-error checking; leaves linter-only analyses (control flow graph, class table) off.
- **`SemanticBuilder::new_linter()`** — linter. Enables syntax-error checking, the control flow graph, and the class table.
The presets are applied at the real pipeline entry points:
- `new_linter()` → the linter service build.
- `new_compiler()` → `oxc::Compiler`, and the napi parser/transform bindings.
Everywhere else keeps `SemanticBuilder::new()` and turns on only the features it needs (mangler, minifier, formatter, transformer plugins, examples, tests, ...). Individual options can still be overridden after a preset (e.g. the linter service overrides `check_syntax_error` with its runtime flag).
Behavior is preserved at every migrated site. Node-store access is intentionally untouched in this PR.
## Verified
- Builds across the affected crates + napi; clippy clean; `oxc_linter` tests pass; full `cargo coverage` with no snapshot changes.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
## Summary
- When a TypeScript enum member with no initializer follows one whose initializer could not be evaluated to a constant, the auto-increment value previously fell back to `0`. It now propagates "unresolved" (`None`) like the existing `Some(String) => None` arm, matching tsc 6.0.3 (which errors on this construct and emits `void 0`, never `0`).
- The bug surfaced via rolldown's cross-module enum inliner (rolldown/rolldown#9494). Rolldown reads `Scoping::get_enum_member_value` to populate its `enum_member_value_map`; once the wrong `0` landed in the map, every call-site reference to the affected member was inlined to `0`. After this fix the map omits the entry and rolldown leaves the reference alone — matching tsc's call-site behavior.
- Adopts the existing `prev = Some(Number(-1.0))` sentinel pattern from `oxc_isolated_declarations/src/enum.rs` and `oxc_transformer/src/typescript/enum.rs`, so the first-member-defaults-to-0 case still resolves naturally and the auto-increment branch shrinks to two arms.
## Example
Input:
```ts
import { External } from './external'; // External.X = 0, External.Y = 1
enum Local { A = External.X, B = External.Y, C }
```
`Scoping::get_enum_member_value` before:
- A → None, B → None, C → Some(Number(0.0)) (wrong)
After:
- A → None, B → None, C → None
Covered by new test `crates/oxc_semantic/tests/integration/enum_values.rs::auto_increment_after_unresolvable_fails`; existing `auto_increment` (first member defaults to 0) and `auto_increment_after_string_fails` continue to pass.
AI disclosure: drafted with Claude Code, reviewed manually.
- clear `MemberWriteTarget` before visiting computed member keys
- add semantic snapshot coverage for computed keys versus computed objects
Fixes#22300
## Summary
- Extend `MemberWriteTarget` flag to cover compound assignments (`+=`), update expressions (`++/--`), and `delete` — previously only simple `=` assignments were covered
- Add `visit_unary_expression` override to set `Write` for `delete` on member expressions
- Change `is_write_only()` to `is_write()` in `visit_member_expression` so all write contexts trigger the flag
- Fix `MemberWriteTarget` leaking into conditional test positions (`(a ? x : y).foo = 1` was incorrectly marking `a`)
- Add snapshot test covering compound assignments, delete, and conditional expressions
- Update doc comments to reflect broader scope
## Test plan
- [x] New snapshot test `member-write-target.js` covering compound assignments, delete, conditional test/consequent/alternate
- [x] Existing semantic snapshot tests updated
- [x] `just ready` passes
🤖 Generated with [Claude Code](https://claude.com/claude-code)
## Summary
Part of https://github.com/oxc-project/oxc/issues/6073 and #11844
- Add `ConstantValue` type in `oxc_syntax` for representing enum member values (number/string)
- Implement enum member value evaluation in `oxc_semantic` supporting numeric auto-increment, string values, binary/unary expressions, cross-member and cross-enum references, template literals, and merged enum declarations
- Store evaluated enum member values in `Scoping` via `EnumData` struct with getter/setter APIs and enum body scope tracking
- All enum evaluation code is gated behind the `enum_eval` Cargo feature (enabled by `oxc_transformer`)
### Feature gate
The `enum_eval` feature controls:
- `ts_enum` module (evaluator + data types)
- `EnumData` field and enum-related methods on `Scoping`
- `oxc_syntax/to_js_string` dependency
Consumers that don't need enum values (linter, language server) pay zero cost.
### Babel alignment
Unary operators on strings follow Babel's JS-coercion semantics (`+"s"` → `"s"`, `-"s"` → `NaN`, `~"s"` → `-1`), which differs from TypeScript (unevaluated). This is documented in the source.
## Test plan
- [x] Integration tests in `crates/oxc_semantic/tests/integration/enum_values.rs`
- [x] Semantic TypeScript conformance snapshot updated
- [x] `cargo check -p oxc_semantic` passes (without feature)
- [x] `cargo check -p oxc_semantic --features enum_eval` passes (with feature)
- [x] `cargo check -p oxc_transformer` passes (enables feature transitively)
## Summary
Add a new `MemberWriteTarget` bit to `ReferenceFlags` ~~Store member write target references in a separate `FxHashSet<ReferenceId>` on `Semantic` rather than adding a flag to `ReferenceFlags`.~~
This marks identifier references read as the object of a member expression in a simple assignment target position (e.g., `A` in `A.foo = 1`).
- Set during `visit_member_expression` when flags indicate write-only context (simple `=`, not compound `+=` or update `++`)
- Stored in `Semantic::member_write_references` (`FxHashSet<ReferenceId>`)
- Queryable via `Semantic::is_member_write_reference(reference_id)` and `Semantic::member_write_references()`
- Does not affect existing `ReferenceFlags` — no changes to the shared bitflags type
## Motivation
Distinguishing "reads that exist only to serve a property write" from "real reads" is broadly useful:
### Minifier: dead code elimination of property-write-only symbols
```js
function A() {}
A.from = () => {} // A's only reference is a member write target
// → both can be eliminated when property_write_side_effects: false
```
Without this info, the minifier sees `A` as "referenced" and cannot remove the function declaration. With it, the minifier knows all of `A`'s reads are property-write targets and can safely drop them. (See stacked PR #20773 — will be updated to use the new API in a follow-up)
### Linter: `no_unused_vars` improvement
```js
const config = {};
config.debug = true;
config.verbose = false;
// config is never read — only mutated via property writes
```
Currently `config` is considered "used" because `config.debug = ...` creates a read reference. With member write target tracking, `no_unused_vars` could detect that `config`'s only reads are property-write targets and report it as unused.
### Linter: simplify `no_param_reassign` property detection
`no_param_reassign` has a complex `is_modifying_property()` function that manually walks the ancestor chain to detect property modifications like `param.foo = 1`. With member write target tracking, this can be checked directly on the reference.
### Rolldown: replace `MemberExprIsWrite` traversal state
Rolldown already maintains its own [`MemberExprIsWrite` flag](https://github.com/rolldown/rolldown/blob/eec7d7320cc991e1efd5ed8264d02c6889a223c3/crates/rolldown/src/ast_scanner/mod.rs#L130-L131) as local traversal state in the AST scanner to [detect member expressions in write context](https://github.com/rolldown/rolldown/blob/eec7d7320cc991e1efd5ed8264d02c6889a223c3/crates/rolldown/src/ast_scanner/impl_visit.rs#L55-L73). Having this on `Semantic` means Rolldown can consume it directly instead of re-detecting it during scanning. There's also a [TODO in Rolldown's treeshake options](https://github.com/rolldown/rolldown/blob/main/crates/rolldown_common/src/inner_bundler_options/types/treeshake.rs#L255-L259) to wire `property_write_side_effects` to oxc_minifier — our stacked PR #20773 provides that.
### General: escape analysis for local objects
Any analysis that needs to know "is this object only mutated locally, never passed elsewhere?" benefits from knowing which reads are purely for property writes vs. reads that pass the value to other functions.
## Test plan
- [x] Semantic snapshot tests updated
- [x] Conformance snapshots updated
- [x] Clippy clean
🤖 Generated with [Claude Code](https://claude.com/claude-code)
## Summary
Follow-up to #19138 after merge.
This PR fixes panic-safety in `multi_index_vec!` clone and keeps strict lint clean for `oxc_semantic` tests.
### Changes
- Make macro-generated `Clone` panic-safe by cloning row-by-row through `push`.
- Avoids setting `len` before all elements are initialized.
- Prevents dropping uninitialized elements if a field `clone()` panics.
- Add `#[expect(clippy::unused_self)]` to cfg-disabled integration helper methods to keep `cargo clippy -p oxc_semantic --lib --tests -D warnings` green.
## Validation
- `cargo clippy -p oxc_semantic --lib --tests -- -D warnings`
- `just lint`
## AI disclosure
AI-assisted: I used Codex to draft and apply this patch, then ran lint checks and reviewed the result before opening this PR.
## Summary
- In JavaScript modules, `import { Foo } from './foo.js'; var Foo;` (and `let`, `const`, `class`, `function`) should report `"Identifier 'Foo' has already been declared"` per the [ES spec](https://tc39.es/ecma262/#sec-imports-static-semantics-early-errors)
- The existing excludes-based conflict detection in the binder doesn't catch this because `Import` is not in the `Value` bitset
- Added a checker function that runs at `Program` leave, scanning root scope bindings for symbols with both `Import` and a value flag, and reports a redeclaration error
- TypeScript is excluded since it has its own declaration merging rules
Closes#15961🤖 Generated with [Claude Code](https://claude.com/claude-code)
## Summary
Fixes#18719.
- In module mode, function declarations are lexically scoped (part of `LexicallyDeclaredNames`), so `function a() {} var a = ''` is a redeclaration error per the ECMAScript spec
- The checker was only reporting the error when the `var` appeared **before** the function (`var a = ''; function a() {}`) but not the other way around, due to AST visit ordering
- `check_variable_declarator_redeclaration` unconditionally skipped the check at `Top | Function` scopes — now it falls through to the redeclaration check when in module mode at the top scope
🤖 Generated with [Claude Code](https://claude.com/claude-code)
## Summary
- Add `SourceType::script()` constructor for creating script source types
- `with_module(bool)` now only sets module mode when `true`, does nothing when `false`
- This aligns with the pattern of other `with_*` methods like `with_script()`, `with_jsx()`, etc.
### Migration
Before:
```rust
// This used to set script mode when is_module is false
let source_type = SourceType::default().with_module(is_module);
```
After:
```rust
// Start from script and upgrade to module when needed
let source_type = SourceType::script().with_module(is_module);
```
🤖 Generated with [Claude Code](https://claude.ai/code)
Remove `Scoping::scope_build_child_ids` and all related APIs to make the semantics cleaner. This could also make it easier for us to sync Scoping data since we don't need to worry about child scope IDs.
This is a breaking change, but it is okay because all use of `scope_build_child_ids` in the Oxc and Rolldown has been removed.
https://github.com/rolldown/rolldown/pull/7936 relies on this. You can see how Rolldown uses this at description of that PR.
Additionally, it can also simplify the use case when you want to get the scope ID where the `Reference` occurs. See follow-up PR #18059
## Summary
- Replace `type_parameter: Box<'a, TSTypeParameter<'a>>` with two dedicated fields:
- `key: BindingIdentifier<'a>` - the parameter name (e.g., `P` in `[P in keyof T]`)
- `constraint: TSType<'a>` - the constraint type (e.g., `keyof T`)
- Improves type safety by preventing invalid AST states - `TSTypeParameter` contains `const`, `in`, `out`, and `default` fields that are syntactically invalid in mapped types
- Matches TSESTree structure more closely
Closes#15101
## Test plan
- [x] All parser, codegen, semantic, and linter tests pass
- [x] Conformance tests show no regressions
- [x] Semantic snapshots updated to reflect the new structure
🤖 Generated with [Claude Code](https://claude.com/claude-code)
## Summary
- Implements speculative/unambiguous parsing for `.js`, `.jsx`, `.ts`, and `.tsx` files
- Instead of assuming module or script upfront, parses with `ModuleKind::Unambiguous` and upgrades to module mode when ESM syntax is detected
- ESM indicators: `import`, `export`, `import.meta` (NOT top-level await alone)
- Defers top-level await errors until module type is resolved
- Vue loader upgrades unambiguous scripts to module mode
- Updates linter tests to use explicit ESM extensions (`.mjs`/`.mts`) where needed
## Test plan
- [x] All parser tests pass
- [x] All linter tests pass
- [x] All semantic tests pass
- [x] Coverage conformance tests updated
🤖 Generated with [Claude Code](https://claude.com/claude-code)
## Summary
- Move `scope_id: Cell<Option<ScopeId>>` from `TSEnumDeclaration` to `TSEnumBody`
- Since `TSEnumBody` was introduced as a dedicated type in PR #10284, the scope logically belongs on the body rather than on the parent declaration node
Closes#10331
## Test plan
- [x] Unit tests pass (`just test`)
- [x] Conformance tests pass (`just conformance`)
- [x] Updated semantic test snapshots reflect scope now on `TSEnumBody`
🤖 Generated with [Claude Code](https://claude.ai/code)
fixes#11489
Note, in quite a few places i changed the span we report on to look something like this, the only reason for this is to reduce the diff in some of the snapshots
```
decl.type_annotation.as_ref().map_or_else(
|| decl.id.span(),
|type_annotation| decl.id.span().merge(type_annotation.span()),
),
```
Fix#14860.
### The problem
`TSModuleDeclaration` type was used to represent 4 different syntaxes:
* `namespace X {}`
* `module X {}`
* `module "x" {}`
* `global {}`
(and all the above prefixed with `declare`)
`global {}` is quite different from the others in a few ways:
* It has no identifier (`global` is a keyword, not an identifier).
* It has no symbol.
* The `body` block is not optional.
* Directives are not allowed in the `body` block.
* It is always ambient context (regardless of whether it has `declare` modifier).
In particular, it was causing panics because `symbol_id` field for `TSModuleDeclaration`s representing `global {}` was `None`.
### Solution
Rather than trying to make `TSModuleDeclaration` type encode all these differences, and make Oxc's code reason about them, split `global {}` into a new type `TSGlobalDeclaration`.
The rest of the diff is just adjusting code to also handle `TSGlobalDeclaration` where it was dealing with `TSModuleDeclaration`s.
This change simplifies the parser quite a bit.
`oxc_semantic`'s `SymbolDeclarationTest` tester now tests that all `TSModuleDeclaration`s with `id: BindingIdentifier` do have a symbol:
https://github.com/oxc-project/oxc/pull/15712/files#diff-ce544d71b839faa898887ac920237e563e59a708e7fca86b53023498ab67a611L101-R110
### Formatter bug
There is one regression in the formatter for `typescript/module/global.ts` case.
https://github.com/oxc-project/oxc/pull/15712/files#diff-f248b1d49b8c482864810055632d7322cdebc895dd4dfe05fbefcf5e23ba12c9R51
Input:
```ts
declare /* module */ global {}
declare /* namespace */ global {}
```
Output:
```diff
- declare /* module */ global {}
- declare /* namespace */ global {}
+ declare global /* module */ {}
+ declare global /* namespace */ {}
```
I assume this is happening because there's no longer a `BindingIdentifier` for the `global` keyword for the comment to get attached to.
I am not sure how to fix this. Maybe the `global_span` field can help?
@Dunqing This PR touches a *lot* of files. Can I propose that we merge it before it gets conflicts, and if you can give me some guidance, I'll do a follow-up PR to fix it?
Part of https://github.com/oxc-project/oxc/issues/11490
### Motivation
`AstKind::Argument` was an architectural inconsistency. The AstKind system is designed for struct types, but `Argument` is an enum (`SpreadElement | Expression`). This created unnecessary complexity in the AST traversal system.
### Solution
Replace AST-based argument detection with span-based utilities. Instead of traversing the tree to find `AstKind::Argument` nodes, we now use direct span containment checks.
### New Utilities
**Added to `oxc_linter/src/ast_util.rs`:**
```rust
pub fn is_node_exact_call_argument<'a>(
node: &AstNode<'a>,
ctx: &LintContext<'a>
) -> bool
```
Checks if a node is exactly a direct argument to its parent call
expression by checking if the parent is a call and the node's span
matches one of the argument spans.
```rust
pub fn is_node_within_call_argument<'a>(
node: &AstNode<'a>,
call: &CallExpression<'a>,
target_arg_index: usize,
) -> bool
```
Checks if a node is nested within a specific argument at the given index
of the provided call expression.
**Added to `oxc_ast/src/ast_kind_impl.rs`:**
```rust
pub fn has_argument_with_span(&self, span: Span) -> bool
```
Checks if this `AstKind` is a call expression with an argument matching
the given span.
```rust
pub fn is_callee_with_span(&self, span: Span) -> bool
```
Checks if this `AstKind` is a call expression whose callee matches the
given span.
### Architecture Change
**Before:**
```rust
// Required parent traversal and state management
match parent.kind() {
AstKind::Argument { .. } => {
// Check grandparent for call context
}
}
```
**After:**
```rust
// Direct span-based detection
if is_node_exact_call_argument(node, ctx) {
// Node is a direct call argument
}
if is_node_within_call_argument(node, call, 0) {
// Node is within first argument
}
```
---------
Co-authored-by: Cameron Clark <cameron.clark@hey.com>
Add explicit condition basic blocks in the control flow graph for logical
expressions and logical assignment operators. This improves CFG accuracy by
representing condition evaluation as distinct nodes.
Changes:
- Create condition basic blocks before evaluating left operands of logical expressions (&&, ||, ??)
- Record and attach AST nodes to condition blocks for better traceability
- Add edges from preceding blocks to condition blocks
- Apply same treatment to logical assignment operators (&&=, ||=, ??=)
This affects CFG generation for:
- LogicalExpression nodes
- AssignmentExpression nodes with logical operators
Fixes#8365
## Summary
The `with` statement was not creating a scope in the semantic analysis, causing `is_global_reference` to incorrectly return `true` for references inside `with` blocks. This could lead to incorrect minification.
## Problem
According to the ECMAScript specification, `with` statements should create an Object Environment Record that extends the lexical environment. Without proper scope tracking:
- `is_global_reference()` incorrectly returns `true` for identifiers inside `with` blocks
- This can cause minification to incorrectly treat local references as global
- The scope tree doesn't accurately represent the program structure
## Solution
### Changes Made
1. **AST Definition** (`crates/oxc_ast/src/ast/js.rs`):
- Added `#[scope]` attribute to `WithStatement` struct
- Added `scope_id: Cell<Option<ScopeId>>` field
2. **Semantic Builder** (`crates/oxc_semantic/src/builder.rs`):
- Modified `visit_with_statement` to call `enter_scope()` before visiting the body
- Added `leave_scope()` call after visiting the body
- Uses `ScopeFlags::empty()` similar to block statements
3. **Test Coverage** (`crates/oxc_semantic/tests/integration/scopes.rs`):
- Added `test_with_statement` to verify scope creation
- Tests both simple expressions and block statement bodies
- Verifies proper scope tree structure
### Example
```javascript
const foo = {
Object: class {
constructor() { console.log('Constructor') }
}
}
with (foo) {
console.log(new Object()) // should print "Constructor"
}
```
Before this fix, `Object` inside the `with` block would be incorrectly identified as a global reference, potentially causing minification errors.
## Implementation Notes
While this implementation doesn't fully model the complex object environment semantics (where property lookups can dynamically affect identifier resolution at runtime), it ensures:
- References inside `with` blocks are no longer incorrectly marked as global
- The scope tree properly represents the lexical structure
- Provides a foundation for future improvements to object environment handling
## Testing
All existing tests pass, plus the new test verifies:
- `with` statements create scopes
- Scopes are properly nested in the scope tree
- Works correctly with both simple and block statement bodies
part of #13646
## Summary
This PR converts the Control Flow Graph (CFG) functionality in `oxc_semantic` from runtime checks to a compile-time cargo feature, eliminating runtime overhead when CFG is not needed.
## Changes
- Added `cfg` cargo feature to `oxc_semantic/Cargo.toml` with `oxc_cfg` as optional dependency
- Feature-gated all CFG-related code using `#[cfg(feature = "cfg")]`
- Updated `oxc_linter` to enable the `cfg` feature (since it requires CFG)
- Made the `control_flow!` macro work correctly with and without the feature
## Benefits
- **Performance**: Eliminates runtime `Option<CFG>` checks when feature is disabled
- **Binary size**: Smaller binaries for crates that don't need CFG
- **Cleaner API**: CFG methods only available when feature is enabled
## Test Plan
- [x] All existing tests pass with `cargo test -p oxc_semantic --features cfg`
- [x] `oxc_linter` builds and works correctly (it enables the feature)
- [x] Feature is backward compatible - existing code continues to work
🤖 Generated with [Claude Code](https://claude.ai/code)
Where a type being returned by a function has lifetimes, specify them with `'_` instead of omitting them entirely. `Cow<str>` -> `Cow<'_, str>`.
This is split out from Rust upgrade PR #12873, so can see the diff in that PR more clearly.
Note: This is very slightly different from what was in #12873. Clippy auto-fix introduced a couple of unnecessary and weird-looking anonymous lifetimes in function params, which this PR skips.