Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .changeset/later-declarator-jsx-setup-5102.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
"@solidjs/compiler": patch
"@solidjs/babel-plugin": patch
---

JSX in a later declarator of one declaration (`const a = …, b = <div>{a}</div>`, 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.
21 changes: 20 additions & 1 deletion packages/babel-plugin/src/shared/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 = <div>{a}</div>`, 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 {
Expand Down
91 changes: 91 additions & 0 deletions packages/babel-plugin/test/declarator-order.spec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
// JSX in a later declarator of one declaration (`const a = 1, b = <div/>`,
// 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 = <div title={label} onClick={onClick}>x</div>;
return view;
}
function Child() {
const label = mk("hi"), view = <p>{label}</p>;
return view;
}
function Two() {
const first = <i>a</i>, label = mk("hi"), second = <p>{first}{label}</p>;
return second;
}
let label = mk("hi"), view = <p title={label}>{label}</p>;
export const exported = mk("hi"), exportedView = <p>{exported}</p>;
__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"\);/);
});
});
12 changes: 12 additions & 0 deletions packages/compiler/__tests__/parity-probes.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 = <div title={label()} onClick={() => onClick()}>x{label()}<Foo a={label} /></div>, other = 1;
return view;
}
function Two() {
const first = <i>{mk()}</i>, label = mk(), second = <p>{first}{label()}</p>;
return second;
}
export const exported = mk(), exportedView = <p>{exported()}</p>;
let a = mk(), frag = <>{a()}</>, st = <b>static</b>;
`,
"slot prop hole before children (#3567)": `
const a = <main>{props.header}{props.children}</main>;
const z = <p>P</p>;
Expand Down
22 changes: 22 additions & 0 deletions packages/compiler/src/shared/ast_builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
31 changes: 24 additions & 7 deletions packages/compiler/src/shared/statements.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -157,8 +157,10 @@ impl<'a> AstDomTransform<'a, '_> {
}

let mut setup: Option<std::vec::Vec<Statement<'a>>> = 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 = (<div/>);` is still
Expand All @@ -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 = <p>{a}</p>`, #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,
Expand Down Expand Up @@ -210,6 +226,7 @@ impl<'a> AstDomTransform<'a, '_> {
}
};
declaration.declarations[index].init = Some(replaced);
index += 1;
}
setup
}
Expand Down
73 changes: 65 additions & 8 deletions packages/compiler/src/ssr/transform.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Statement<'a>>,
/// 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<Span>,
/// Spans of JSX elements sitting in statement position (`return <jsx/>`,
/// `const x = <jsx/>`) for the statement currently being processed.
statement_jsx_spans: std::vec::Vec<Span>,
Expand Down Expand Up @@ -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(),
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -1238,6 +1244,7 @@ impl<'a, 'source> AstSsrTransform<'a, 'source> {
let mut setup: std::vec::Vec<Statement<'a>> =
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();
}
Expand Down Expand Up @@ -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::<std::vec::Vec<_>>()
})
.unwrap_or_default();
self.visit_statement(&mut statement);
self.statement_jsx_spans
.truncate(self.statement_jsx_spans.len() - recorded);
Expand Down Expand Up @@ -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 = <p>{a}</p>`): 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);
Expand Down Expand Up @@ -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<Span> {
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<Span>) -> usize {
fn jsx_span(expression: &Expression<'_>) -> Option<Span> {
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) => {
Expand Down
Loading
Loading