From ae433135518e977fa2aa53bbf4889aa662ad432b Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 20 Nov 2026 08:45:05 +0000 Subject: [PATCH] fix(compiler,babel-plugin): run later-declarator JSX setup after the declarators before it (#5102) A declaration whose later declarator holds JSX hoisted the element's setup above the whole statement, so it read earlier declarators before initialization (minifiers' joinVars makes this shape). Split the declarators before the JSX into their own statement first, in the DOM, universal and SSR outputs of both compilers. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0117BoWPYxt1bEM9zZ5G6dPL --- .changeset/later-declarator-jsx-setup-5102.md | 6 ++ packages/babel-plugin/src/shared/utils.ts | 21 ++++- .../test/declarator-order.spec.js | 91 +++++++++++++++++++ .../compiler/__tests__/parity-probes.test.js | 12 +++ packages/compiler/src/shared/ast_builder.rs | 22 +++++ packages/compiler/src/shared/statements.rs | 31 +++++-- packages/compiler/src/ssr/transform.rs | 73 +++++++++++++-- packages/compiler/src/universal/transform.rs | 28 +++++- 8 files changed, 263 insertions(+), 21 deletions(-) create mode 100644 .changeset/later-declarator-jsx-setup-5102.md create mode 100644 packages/babel-plugin/test/declarator-order.spec.js diff --git a/.changeset/later-declarator-jsx-setup-5102.md b/.changeset/later-declarator-jsx-setup-5102.md new file mode 100644 index 0000000000..d0ea050aef --- /dev/null +++ b/.changeset/later-declarator-jsx-setup-5102.md @@ -0,0 +1,6 @@ +--- +"@solidjs/compiler": patch +"@solidjs/babel-plugin": patch +--- + +JSX in a later declarator of one declaration (`const a = …, b =
{a}
`, the shape minifiers make by joining declarations) no longer has its setup hoisted above the whole declaration. The declarators before it split into their own statement, so the setup runs after them instead of reading them before initialization. diff --git a/packages/babel-plugin/src/shared/utils.ts b/packages/babel-plugin/src/shared/utils.ts index efd4f40d3d..75e4322595 100644 --- a/packages/babel-plugin/src/shared/utils.ts +++ b/packages/babel-plugin/src/shared/utils.ts @@ -59,9 +59,28 @@ export function isStatementVariableInitializer(path: NodePath): boolean { * `else` or loop body it returns the whole `if` or loop: setup inserted there * runs on every path, and outside the loop's bindings. Inserting before the * return lets Babel wrap that body in a block. + * + * JSX in a later declarator (`const a = 1, b =
{a}
`, the shape + * minifiers make by joining declarations) splits the declarators before it + * into their own statement first, so its setup runs after them. */ export function getSetupStatement(path: NodePath): NodePath | null { - return t.isReturnStatement(path.parent) ? path.parentPath : path.getStatementParent(); + if (t.isReturnStatement(path.parent)) return path.parentPath; + const statement = path.getStatementParent(); + const declaration = path.parentPath?.parentPath; + if (statement && declaration?.isVariableDeclaration()) { + const index = declaration.node.declarations.indexOf(path.parent as t.VariableDeclarator); + if (index > 0) { + const before = t.variableDeclaration( + declaration.node.kind, + declaration.node.declarations.splice(0, index) + ); + statement.insertBefore( + statement.isExportNamedDeclaration() ? t.exportNamedDeclaration(before) : before + ); + } + } + return statement; } export function getConfig(path: NodePath): PluginConfig { diff --git a/packages/babel-plugin/test/declarator-order.spec.js b/packages/babel-plugin/test/declarator-order.spec.js new file mode 100644 index 0000000000..9730ef4cb3 --- /dev/null +++ b/packages/babel-plugin/test/declarator-order.spec.js @@ -0,0 +1,91 @@ +// JSX in a later declarator of one declaration (`const a = 1, b =
`, +// the shape minifiers make by joining declarations) must have its setup run +// after the declarators before it (#5102). The compiled output is EXECUTED +// against a stub runtime whose `insert`, `ssr` and attribute writes read +// their values at once, so setup hoisted above the declaration throws. +const babel = require("@babel/core"); +const plugin = require("../index"); + +const modes = { + dom: { moduleName: "r-dom", generate: "dom" }, + "dom hydratable": { moduleName: "r-dom", generate: "dom", hydratable: true }, + universal: { moduleName: "r-custom", generate: "universal" }, + ssr: { moduleName: "r-server", generate: "ssr" } +}; + +const source = ` + function mk(s) { return s; } + function Attr() { + const label = mk("hi"), onClick = () => label, view =
x
; + return view; + } + function Child() { + const label = mk("hi"), view =

{label}

; + return view; + } + function Two() { + const first = a, label = mk("hi"), second =

{first}{label}

; + return second; + } + let label = mk("hi"), view =

{label}

; + export const exported = mk("hi"), exportedView =

{exported}

; + __result = { Attr, Child, Two, view, exported, exportedView }; +`; + +// Every DOM walk (`firstChild`, `nextSibling`) lands on another stub node. +const stub = new Proxy({}, { get: (_t, key) => (key === Symbol.toPrimitive ? undefined : stub) }); +const node = () => stub; +const read = v => (typeof v === "function" ? v() : v); +const runtime = { + template: () => node, + createElement: node, + createTextNode: node, + getNextElement: template => template(), + getNextMarker: () => [stub, []], + runHydrationEvents: () => {}, + insert: (_parent, value) => read(value), + insertNode: () => {}, + setProp: (_node, _name, value) => read(value), + setAttribute: (_node, _name, value) => read(value), + addEvent: (_node, _name, handler) => read(handler), + delegateEvents: () => {}, + ssr: (_template, ...values) => values.map(read), + ssrAttribute: (_name, value) => read(value), + escape: v => v +}; + +function compile(options) { + return babel.transformSync(source, { + configFile: false, + babelrc: false, + filename: "x.jsx", + sourceType: "module", + plugins: [[plugin, { requireImportSource: false, ...options }]] + }).code; +} + +function run(options) { + const out = compile(options) + .replace(/import \{ ([\w$]+) as ([\w$]+) \} from "[\w-]+";/g, (_, name, local) => { + if (!(name in runtime)) throw new Error(`stub runtime lacks ${name}`); + return `const ${local} = __rt.${name};`; + }) + .replace(/^export /gm, ""); + return new Function("__rt", `let __result;\n${out}\nreturn __result;`)(runtime); +} + +describe.each(Object.entries(modes))("JSX in a later declarator (%s)", (_mode, options) => { + test("setup runs after the declarators before it", () => { + const result = run(options); + expect(() => result.Attr()).not.toThrow(); + expect(() => result.Child()).not.toThrow(); + expect(() => result.Two()).not.toThrow(); + }); + + test("the split keeps every declarator, exported ones included", () => { + const out = compile(options); + expect(out).toMatch(/export const exported = mk\("hi"\);/); + expect(out).toMatch(/export const exportedView = /); + expect(out).toMatch(/let label = mk\("hi"\);/); + }); +}); diff --git a/packages/compiler/__tests__/parity-probes.test.js b/packages/compiler/__tests__/parity-probes.test.js index 2be2dd27a4..dbba53706a 100644 --- a/packages/compiler/__tests__/parity-probes.test.js +++ b/packages/compiler/__tests__/parity-probes.test.js @@ -11,6 +11,18 @@ const { modes, compileBabel, compileOxc, normalize, unifiedDiff } = require("./parity/harness"); const cases = { + "JSX in a later declarator splits the declarators before it (#5102)": ` +function Comp(props) { + const label = mk(), onClick = () => label, view =
onClick()}>x{label()}
, other = 1; + return view; +} +function Two() { + const first = {mk()}, label = mk(), second =

{first}{label()}

; + return second; +} +export const exported = mk(), exportedView =

{exported()}

; +let a = mk(), frag = <>{a()}, st = static; +`, "slot prop hole before children (#3567)": ` const a =
{props.header}{props.children}
; const z =

P

; diff --git a/packages/compiler/src/shared/ast_builder.rs b/packages/compiler/src/shared/ast_builder.rs index ae12df0719..1c63274a87 100644 --- a/packages/compiler/src/shared/ast_builder.rs +++ b/packages/compiler/src/shared/ast_builder.rs @@ -551,6 +551,28 @@ impl<'a> AstBuilder<'a> { VariableDeclaration::boxed(span, kind, declarations, declare, &self.inner()) } + /// The declarators ahead of a JSX root split into their own statement + /// (`export`ed again when the declaration was), so the root's setup can + /// go between them and the declarators that follow. + pub(crate) fn split_declaration_statement( + &self, + span: Span, + kind: VariableDeclarationKind, + declarations: ArenaVec<'a, VariableDeclarator<'a>>, + exported: bool, + ) -> Statement<'a> { + let declaration = self.alloc_variable_declaration(span, kind, declarations, false); + if exported { + Statement::ExportDeclaration(ExportDeclaration::boxed( + span, + Declaration::VariableDeclaration(declaration), + &self.inner(), + )) + } else { + Statement::VariableDeclaration(declaration) + } + } + pub(crate) fn import_declaration_specifier_import_specifier( &self, span: Span, diff --git a/packages/compiler/src/shared/statements.rs b/packages/compiler/src/shared/statements.rs index 7632966f1e..3ff530db05 100644 --- a/packages/compiler/src/shared/statements.rs +++ b/packages/compiler/src/shared/statements.rs @@ -136,10 +136,10 @@ impl<'a> AstDomTransform<'a, '_> { // `insertBefore` targets the whole statement — including through an // `export const` wrapper (`getStatementParent` on an exported // declaration inserts before the export statement). - let declaration = match statement { - Statement::VariableDeclaration(declaration) => declaration, + let (declaration, exported) = match statement { + Statement::VariableDeclaration(declaration) => (declaration, false), Statement::ExportDeclaration(export) => match &mut export.declaration { - oxc_ast::ast::Declaration::VariableDeclaration(declaration) => declaration, + oxc_ast::ast::Declaration::VariableDeclaration(declaration) => (declaration, true), _ => return None, }, _ => return None, @@ -157,8 +157,10 @@ impl<'a> AstDomTransform<'a, '_> { } let mut setup: Option>> = None; - for index in 0..declaration.declarations.len() { + let mut index = 0; + while index < declaration.declarations.len() { let Some(taken) = declaration.declarations[index].init.take() else { + index += 1; continue; }; // Babel sees through parentheses: `const a = (
);` is still @@ -171,9 +173,23 @@ impl<'a> AstDomTransform<'a, '_> { Expression::JSXElement(element) => { match self.lower_root_element_with_setup(&element) { Ok((replacement, statements)) => { - setup - .get_or_insert_with(std::vec::Vec::new) - .extend(statements); + let setup = setup.get_or_insert_with(std::vec::Vec::new); + // Setup reads the declarators before this one + // (`const a = 1, b =

{a}

`, #5102): they + // split into their own statement ahead of it. + if index > 0 && !statements.is_empty() { + let before = self + .ast() + .vec_from_iter(declaration.declarations.drain(..index)); + setup.push(self.ast().split_declaration_statement( + declaration.span, + declaration.kind, + before, + exported, + )); + index = 0; + } + setup.extend(statements); crate::shared::transform::finalize_root_capture( self, element.span, @@ -210,6 +226,7 @@ impl<'a> AstDomTransform<'a, '_> { } }; declaration.declarations[index].init = Some(replaced); + index += 1; } setup } diff --git a/packages/compiler/src/ssr/transform.rs b/packages/compiler/src/ssr/transform.rs index dababbc57a..eaac9b3198 100644 --- a/packages/compiler/src/ssr/transform.rs +++ b/packages/compiler/src/ssr/transform.rs @@ -132,6 +132,10 @@ pub(crate) struct AstSsrTransform<'a, 'source> { /// Declaration statements to insert before the statement currently being /// processed (Babel's `getStatementParent().insertBefore`). pending_statements: std::vec::Vec>, + /// The JSX root each `pending_statements` entry was hoisted for, in step + /// with it, so a later declarator's setup can split the declarators + /// before it off first (#5102). + pending_jsx_spans: std::vec::Vec, /// Spans of JSX elements sitting in statement position (`return `, /// `const x = `) for the statement currently being processed. statement_jsx_spans: std::vec::Vec, @@ -313,6 +317,7 @@ impl<'a, 'source> AstSsrTransform<'a, 'source> { in_class_field: false, hoisted_props: std::vec::Vec::new(), pending_statements: std::vec::Vec::new(), + pending_jsx_spans: std::vec::Vec::new(), statement_jsx_spans: std::vec::Vec::new(), component_child_depth: 0, var_scope_stack: std::vec::Vec::new(), @@ -981,6 +986,7 @@ impl<'a, 'source> AstSsrTransform<'a, 'source> { false, ) })); + self.pending_jsx_spans.push(element.span); self.pending_statements.push(Statement::VariableDeclaration( self.ast().alloc_variable_declaration( span, @@ -1238,6 +1244,7 @@ impl<'a, 'source> AstSsrTransform<'a, 'source> { let mut setup: std::vec::Vec> = self.bare_var_declaration(&bare_vars).into_iter().collect(); setup.extend(self.pending_statements.split_off(pending_before)); + self.pending_jsx_spans.truncate(pending_before); if root_jsx_span.is_some() { self.statement_jsx_spans.pop(); } @@ -3964,6 +3971,15 @@ impl<'a> AstSsrTransform<'a, '_> { // emit their hoisted declarations as `var` statements before the // parent statement (Babel's `isReturnArg || isVarInit`). let recorded = record_statement_jsx_spans(&statement, &mut self.statement_jsx_spans); + let declarator_jsx_spans = statement_variable_declaration(&mut statement) + .map(|(declaration, _)| { + declaration + .declarations + .iter() + .map(|declarator| declarator.init.as_ref().and_then(statement_jsx_span)) + .collect::>() + }) + .unwrap_or_default(); self.visit_statement(&mut statement); self.statement_jsx_spans .truncate(self.statement_jsx_spans.len() - recorded); @@ -3996,7 +4012,30 @@ impl<'a> AstSsrTransform<'a, '_> { body.push(capture); self.clear_this_capture_context(); } - for pending in self.pending_statements.drain(..) { + let pending = std::mem::take(&mut self.pending_statements); + let pending_spans = std::mem::take(&mut self.pending_jsx_spans); + let mut split = 0; + for (pending, span) in pending.into_iter().zip(pending_spans) { + // Setup for JSX in a later declarator reads the declarators + // before it (`const a = 1, b =

{a}

`): they split into + // their own statement ahead of it. + let position = declarator_jsx_spans.iter().position(|s| *s == Some(span)); + if let Some(position) = position + && position > split + && let Some((declaration, exported)) = + statement_variable_declaration(&mut statement) + { + let before = self + .ast() + .vec_from_iter(declaration.declarations.drain(..position - split)); + body.push(self.ast().split_declaration_statement( + declaration.span, + declaration.kind, + before, + exported, + )); + split = position; + } body.push(pending); } body.push(statement); @@ -4544,16 +4583,34 @@ fn fragment_will_self_escape(fragment: &JSXFragment<'_>) -> bool { only.is_some_and(|element| !is_component_name(&element.opening_element.name)) } +fn statement_jsx_span(expression: &Expression<'_>) -> Option { + match expression { + Expression::ParenthesizedExpression(inner) => statement_jsx_span(&inner.expression), + Expression::JSXElement(element) => Some(element.span), + _ => None, + } +} + +/// The variable declaration a statement is, directly or under `export`. +fn statement_variable_declaration<'s, 'a>( + statement: &'s mut Statement<'a>, +) -> Option<(&'s mut oxc_ast::ast::VariableDeclaration<'a>, bool)> { + match statement { + Statement::VariableDeclaration(declaration) => Some((declaration, false)), + Statement::ExportDeclaration(export) => match &mut export.declaration { + oxc_ast::ast::Declaration::VariableDeclaration(declaration) => { + Some((declaration, true)) + } + _ => None, + }, + _ => None, + } +} + /// Records the spans of JSX elements in statement position — direct `return` /// arguments and variable-declarator inits, unwrapping parentheses. fn record_statement_jsx_spans(statement: &Statement<'_>, spans: &mut std::vec::Vec) -> usize { - fn jsx_span(expression: &Expression<'_>) -> Option { - match expression { - Expression::ParenthesizedExpression(inner) => jsx_span(&inner.expression), - Expression::JSXElement(element) => Some(element.span), - _ => None, - } - } + let jsx_span = statement_jsx_span; let mut count = 0; match statement { Statement::ReturnStatement(ret) => { diff --git a/packages/compiler/src/universal/transform.rs b/packages/compiler/src/universal/transform.rs index c544de0a15..c2c035b95c 100644 --- a/packages/compiler/src/universal/transform.rs +++ b/packages/compiler/src/universal/transform.rs @@ -1653,10 +1653,10 @@ impl<'a, 'source> AstUniversalTransform<'a, 'source> { ) -> Option>> { // Babel's `isVarInit` is per-declarator and its `insertBefore` // targets the whole statement, including through `export const`. - let declaration = match statement { - Statement::VariableDeclaration(declaration) => declaration, + let (declaration, exported) = match statement { + Statement::VariableDeclaration(declaration) => (declaration, false), Statement::ExportDeclaration(export) => match &mut export.declaration { - oxc_ast::ast::Declaration::VariableDeclaration(declaration) => declaration, + oxc_ast::ast::Declaration::VariableDeclaration(declaration) => (declaration, true), _ => return None, }, _ => return None, @@ -1673,8 +1673,10 @@ impl<'a, 'source> AstUniversalTransform<'a, 'source> { } let mut setup: Option>> = None; - for index in 0..declaration.declarations.len() { + let mut index = 0; + while index < declaration.declarations.len() { let Some(init) = declaration.declarations[index].init.take() else { + index += 1; continue; }; let init = if matches!( @@ -1683,7 +1685,22 @@ impl<'a, 'source> AstUniversalTransform<'a, 'source> { ) { let (init, lowered) = self.lower_statement_position_jsx(init); if let Some(lowered) = lowered { - setup.get_or_insert_with(std::vec::Vec::new).extend(lowered); + let setup = setup.get_or_insert_with(std::vec::Vec::new); + // Setup reads the declarators before this one (#5102): + // they split into their own statement ahead of it. + if index > 0 && !lowered.is_empty() { + let before = self + .ast() + .vec_from_iter(declaration.declarations.drain(..index)); + setup.push(self.ast().split_declaration_statement( + declaration.span, + declaration.kind, + before, + exported, + )); + index = 0; + } + setup.extend(lowered); } init } else { @@ -1694,6 +1711,7 @@ impl<'a, 'source> AstUniversalTransform<'a, 'source> { init }; declaration.declarations[index].init = Some(init); + index += 1; } setup }