fix: generate correct code for simple destructurings (#17237)

Fixes #17236

* fix: generate correct code for simple destructurings

* add a test (existing one doesn't fail on main)

* adjust existing test so it fails on main

* slightly neater approach (with identical outcome)

---------

Co-authored-by: Rich Harris <rich.harris@vercel.com>
pull/17245/head
Simon H 2 months ago committed by GitHub
parent d0e61bc252
commit a7848c021a
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

@ -0,0 +1,5 @@
---
'svelte': patch
---
fix: generate correct code for simple destructurings

@ -53,23 +53,22 @@ export function transform_body(instance_body, runner, transform) {
transform(b.var(s.node.id, s.node.init))
);
if (visited.declarations.length === 1) {
return b.thunk(
b.assignment('=', visited.declarations[0].id, visited.declarations[0].init ?? b.void0),
s.has_await
);
const statements = visited.declarations.map((node) => {
if (node.id.type === 'Identifier' && node.id.name.startsWith('$$d')) {
// this is an intermediate declaration created in VariableDeclaration.js;
// subsequent statements depend on it
return b.var(node.id, node.init);
}
return b.stmt(b.assignment('=', node.id, node.init ?? b.void0));
});
if (statements.length === 1) {
const statement = /** @type {ESTree.ExpressionStatement} */ (statements[0]);
return b.thunk(statement.expression, s.has_await);
}
// if we have multiple declarations, it indicates destructuring
return b.thunk(
b.block([
b.var(visited.declarations[0].id, visited.declarations[0].init),
...visited.declarations
.slice(1)
.map((d) => b.stmt(b.assignment('=', d.id, d.init ?? b.void0)))
]),
s.has_await
);
return b.thunk(b.block(statements), s.has_await);
}
if (s.node.type === 'ClassDeclaration') {

@ -1,13 +1,17 @@
<script>
let count = $state(1);
// More complex init
let { squared, cubed } = $derived(await {
squared: count ** 2,
cubed: count ** 3
});
// Simple init with multiple destructurings after await
let { toFixed, toString } = $derived(count);
</script>
<button onclick={() => count++}>increment</button>
<p>{count} ** 2 = {squared}</p>
<p>{count} ** 3 = {cubed}</p>
<p>{typeof toFixed} {typeof toString}</p>

@ -13,6 +13,7 @@ export default test({
<button>increment</button>
<p>1 ** 2 = 1</p>
<p>1 ** 3 = 1</p>
<p>function function</p>
`
);
@ -25,6 +26,7 @@ export default test({
<button>increment</button>
<p>2 ** 2 = 4</p>
<p>2 ** 3 = 8</p>
<p>function function</p>
`
);
}

Loading…
Cancel
Save