[compiler] Bail out with Todo on using and await using declarations (#36946)

## Summary

The compiler silently rewrote functions containing `using` and `await
using` declarations (explicit resource management). BuildHIR's
`VariableDeclaration` case only special-cases `var`; every other kind
falls through to `InstructionKind.Const`. A `using` declaration
therefore compiled as a plain memoized `const`, and the implicit dispose
call at scope exit was dropped from the compiled output. No diagnostic
was emitted. The Rust port mirrored the same bug in `build_hir.rs`.

The Rust port had a second, harder failure: its
`VariableDeclarationKind` enum had no `await using` variant, so a Babel
AST containing one failed serde deserialization at the NAPI boundary
("unknown variant `await using`") and threw for the whole file.

The fix records the same per-function Todo bail as the existing `var`
case, in both implementations, then continues lowering the declaration
as `const` so references do not break while the error unwinds (mirroring
how `var` continues as `let`). This matches the compiler's established
Todo-bail precedent for unsupported syntax: the function is skipped with
a logged `CompileError` diagnostic, `panicThreshold` is respected, and
sibling functions in the same file still compile. This deliberately
contrasts with oxc-project/oxc#24217, which handles the same syntax with
a silent per-function skip; nothing in this compiler is skipped without
a surfaced diagnostic.

Changes:

- TS: `BuildHIR.ts` records a Todo `CompilerErrorDetail` for `using` and
`await using` kinds, in the style of the existing `var` case.
- Rust: same Todo `record_error` in `build_hir.rs`. New `AwaitUsing`
variant (serde name `"await using"`) in `react_compiler_ast`, so `await
using` survives the NAPI boundary, covered by a serde round-trip unit
test.
- Test harness: enables the `explicitResourceManagement` parser plugin
in snap and in the e2e script's Babel baseline so fixtures can use the
syntax.

Fixtures (identical snapshots for the TS and Rust pipelines):

- `error.todo-using-declaration` and
`error.todo-await-using-declaration` show the Todo diagnostic with code
frames.
- `using-declaration-bailout-sibling-compiles` shows the bailing
function left untouched (disposal preserved) while a sibling component
in the same file is memoized.

The first commit snapshots the previous broken behavior (`using`
memoized as `const` with disposal dropped); the second commit lands the
fix and updates the snapshots.

## How did you test this change?

All results below are from the branch rebased onto current main.

TS implementation:

- `yarn snap`: 1809 tests, 1809 passed, 0 failed.
- `yarn workspace babel-plugin-react-compiler lint`: clean. `yarn
prettier-check` at the repo root: clean.
- Manually verified pre-fix output: a component with `using resource =
getResource(props.id)` compiled to a memoized `const` with no disposal.

Rust implementation:

- `cargo test --workspace`: 42 passed, 0 failed (includes the new serde
round-trip unit test for both `using` kinds).
- `bash scripts/test-babel-ast.sh`: passed.
- `bash scripts/test-rust-port.sh`: 1808 passed, 0 failed.
- `yarn snap --rust`: 1809 tests, 1809 passed, 0 failed, against the
same `.expect.md` snapshots as the TS run.
- `scripts/test-e2e.ts` (babel variant): the three using fixtures pass
code and events parity.
- Manually verified `await using` now deserializes across the NAPI
boundary and records the Todo instead of throwing.

<div><a
href="https://cursor.com/agents/bc-5fe4350d-5d42-4c0e-9001-429ed0b5e5b7"><picture><source
media="(prefers-color-scheme: dark)"
srcset="https://cursor.com/assets/images/open-in-web-dark.png"><source
media="(prefers-color-scheme: light)"
srcset="https://cursor.com/assets/images/open-in-web-light.png"><img
alt="Open in Web" width="114" height="28"
src="https://cursor.com/assets/images/open-in-web-dark.png"></picture></a>&nbsp;<a
href="https://cursor.com/background-agent?bcId=bc-5fe4350d-5d42-4c0e-9001-429ed0b5e5b7"><picture><source
media="(prefers-color-scheme: dark)"
srcset="https://cursor.com/assets/images/open-in-cursor-dark.png"><source
media="(prefers-color-scheme: light)"
srcset="https://cursor.com/assets/images/open-in-cursor-light.png"><img
alt="Open in Cursor" width="131" height="28"
src="https://cursor.com/assets/images/open-in-cursor-dark.png"></picture></a>&nbsp;</div>

---------

Co-authored-by: Hanzo Dev <[email protected]>
This commit is contained in:
lauren
2026-07-07 20:46:37 -07:00
committed by GitHub
co-authored by Hanzo Dev
parent d665a321a8
commit 5894c3a0be
12 changed files with 175 additions and 12 deletions
@@ -478,6 +478,8 @@ pub enum VariableDeclarationKind {
Let,
Const,
Using,
#[serde(rename = "await using")]
AwaitUsing,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
@@ -668,6 +670,31 @@ mod tests {
assert!(matches!(stmt, Statement::EmptyStatement(_)));
}
/// Babel serializes `using`/`await using` declarations as ordinary
/// VariableDeclarations whose `kind` is "using" / "await using" (with a
/// space). Both must round-trip so the NAPI boundary does not reject
/// files containing them.
#[test]
fn using_declaration_kinds_round_trip() {
for kind in ["using", "await using"] {
let input = json!({
"type": "VariableDeclaration",
"kind": kind,
"declarations": [
{
"type": "VariableDeclarator",
"id": { "type": "Identifier", "name": "resource" },
"init": { "type": "NullLiteral" }
}
]
});
let stmt: Statement = serde_json::from_value(input.clone()).unwrap();
assert!(matches!(stmt, Statement::VariableDeclaration(_)));
assert_eq!(serde_json::to_value(&stmt).unwrap()["kind"], json!(kind));
}
}
#[test]
fn malformed_known_statement_type_errors() {
let err = serde_json::from_value::<Statement>(json!({
@@ -3058,22 +3058,30 @@ fn lower_statement(
Statement::VariableDeclaration(var_decl) => {
use react_compiler_ast::patterns::PatternLike;
use react_compiler_ast::statements::VariableDeclarationKind;
if matches!(var_decl.kind, VariableDeclarationKind::Var) {
let unsupported_node_kind = match var_decl.kind {
VariableDeclarationKind::Var => Some("var"),
VariableDeclarationKind::Using => Some("using"),
VariableDeclarationKind::AwaitUsing => Some("await using"),
VariableDeclarationKind::Let | VariableDeclarationKind::Const => None,
};
if let Some(node_kind) = unsupported_node_kind {
builder.record_error(CompilerErrorDetail {
reason: "(BuildHIR::lowerStatement) Handle var kinds in VariableDeclaration"
.to_string(),
reason: format!(
"(BuildHIR::lowerStatement) Handle {node_kind} kinds in VariableDeclaration"
),
category: ErrorCategory::Todo,
loc: convert_opt_loc(&var_decl.base.loc),
description: None,
suggestions: None,
})?;
// Treat `var` as `let` so references to the variable don't break
// Treat `var` as `let` and `using`/`await using` as `const` so
// references to the variable don't break while the error unwinds
}
let kind = match var_decl.kind {
VariableDeclarationKind::Let | VariableDeclarationKind::Var => InstructionKind::Let,
VariableDeclarationKind::Const | VariableDeclarationKind::Using => {
InstructionKind::Const
}
VariableDeclarationKind::Const
| VariableDeclarationKind::Using
| VariableDeclarationKind::AwaitUsing => InstructionKind::Const,
};
for declarator in &var_decl.declarations {
let stmt_loc = convert_opt_loc(&var_decl.base.loc);
@@ -903,7 +903,11 @@ function lowerStatement(
case 'VariableDeclaration': {
const stmt = stmtPath as NodePath<t.VariableDeclaration>;
const nodeKind: t.VariableDeclaration['kind'] = stmt.node.kind;
if (nodeKind === 'var') {
if (
nodeKind === 'var' ||
nodeKind === 'using' ||
nodeKind === 'await using'
) {
builder.recordError(
new CompilerErrorDetail({
reason: `(BuildHIR::lowerStatement) Handle ${nodeKind} kinds in VariableDeclaration`,
@@ -912,7 +916,10 @@ function lowerStatement(
suggestions: null,
}),
);
// Treat `var` as `let` so references to the variable don't break
/*
* Treat `var` as `let` and `using`/`await using` as `const` so
* references to the variable don't break while the error unwinds
*/
}
const kind =
nodeKind === 'let' || nodeKind === 'var'
@@ -0,0 +1,29 @@
## Input
```javascript
async function Component(props) {
await using resource = getResource(props.id);
return <div>{resource.data}</div>;
}
```
## Error
```
Found 1 error:
Todo: (BuildHIR::lowerStatement) Handle await using kinds in VariableDeclaration
error.todo-await-using-declaration.ts:2:2
1 | async function Component(props) {
> 2 | await using resource = getResource(props.id);
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ (BuildHIR::lowerStatement) Handle await using kinds in VariableDeclaration
3 | return <div>{resource.data}</div>;
4 | }
5 |
```
@@ -0,0 +1,4 @@
async function Component(props) {
await using resource = getResource(props.id);
return <div>{resource.data}</div>;
}
@@ -0,0 +1,29 @@
## Input
```javascript
function Component(props) {
using resource = getResource(props.id);
return <div>{resource.data}</div>;
}
```
## Error
```
Found 1 error:
Todo: (BuildHIR::lowerStatement) Handle using kinds in VariableDeclaration
error.todo-using-declaration.ts:2:2
1 | function Component(props) {
> 2 | using resource = getResource(props.id);
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ (BuildHIR::lowerStatement) Handle using kinds in VariableDeclaration
3 | return <div>{resource.data}</div>;
4 | }
5 |
```
@@ -0,0 +1,4 @@
function Component(props) {
using resource = getResource(props.id);
return <div>{resource.data}</div>;
}
@@ -0,0 +1,40 @@
## Input
```javascript
// @panicThreshold:"none"
function ComponentWithUsing(props) {
using resource = getResource(props.id);
return <div>{resource.data}</div>;
}
function ValidComponent(props) {
return <div>{props.greeting}</div>;
}
```
## Code
```javascript
import { c as _c } from "react/compiler-runtime"; // @panicThreshold:"none"
function ComponentWithUsing(props) {
using resource = getResource(props.id);
return <div>{resource.data}</div>;
}
function ValidComponent(props) {
const $ = _c(2);
let t0;
if ($[0] !== props.greeting) {
t0 = <div>{props.greeting}</div>;
$[0] = props.greeting;
$[1] = t0;
} else {
t0 = $[1];
}
return t0;
}
```
@@ -0,0 +1,9 @@
// @panicThreshold:"none"
function ComponentWithUsing(props) {
using resource = getResource(props.id);
return <div>{resource.data}</div>;
}
function ValidComponent(props) {
return <div>{props.greeting}</div>;
}
@@ -26,6 +26,12 @@ const skipFilter = new Set([
*/
'ts-namespace-export-declaration',
/**
* `using`/`await using` (explicit resource management) is not supported by
* the Node version the evaluator runs on.
*/
'using-declaration-bailout-sibling-compiles',
/**
* Observable different in logging between Forget and non-Forget
*/
+1 -1
View File
@@ -121,7 +121,7 @@ export function parseInput(
} else {
return BabelParser.parse(input, {
sourceFilename: filename,
plugins: ['typescript', 'jsx'],
plugins: ['typescript', 'jsx', 'explicitResourceManagement'],
sourceType,
});
}
+2 -2
View File
@@ -148,7 +148,7 @@ async function formatCode(code: string, isFlow: boolean): Promise<string> {
try {
const parserPlugins: string[] = isFlow
? ['flow', 'jsx']
: ['typescript', 'jsx'];
: ['typescript', 'jsx', 'explicitResourceManagement'];
const ast = babel.parseSync(code, {
sourceType: 'module',
parserOpts: {plugins: parserPlugins},
@@ -183,7 +183,7 @@ function compileBabel(
const isScript = firstLine.includes('@script');
const parserPlugins: string[] = isFlow
? ['flow', 'jsx']
: ['typescript', 'jsx'];
: ['typescript', 'jsx', 'explicitResourceManagement'];
const pragmaOpts = parseConfigPragmaForTests(firstLine, {
compilationMode: 'all',