Skip to content

fix: ensure snippet hoisting works in the correct scope #14642

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Dec 10, 2024
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
5 changes: 5 additions & 0 deletions .changeset/chatty-windows-own.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'svelte': patch
---

fix: ensure snippet hoisting works in the correct scope
Original file line number Diff line number Diff line change
Expand Up @@ -99,8 +99,9 @@ function can_hoist_snippet(scope, scopes, visited = new Set()) {
if (binding.initial?.type === 'SnippetBlock') {
if (visited.has(binding)) continue;
visited.add(binding);
const snippet_scope = /** @type {Scope} */ (scopes.get(binding.initial));

if (can_hoist_snippet(binding.scope, scopes, visited)) {
if (can_hoist_snippet(snippet_scope, scopes, visited)) {
continue;
}
}
Expand Down
6 changes: 1 addition & 5 deletions packages/svelte/src/compiler/phases/scope.js
Original file line number Diff line number Diff line change
Expand Up @@ -628,12 +628,8 @@ export function create_scopes(ast, root, allow_reactive_declarations, parent) {

SnippetBlock(node, context) {
const state = context.state;
// Special-case for root-level snippets: they become part of the instance scope
const is_top_level = !context.path.at(-2);
let scope = state.scope;
if (is_top_level) {
scope = /** @type {Scope} */ (parent);
}

scope.declare(node.expression, 'normal', 'function', node);

const child_scope = state.scope.child();
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { test } from '../../test';

export default test({
html: 'a'
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<script>
let abc = 'a'
</script>

{@render b()}

{#snippet a()}
{abc}
{/snippet}

{#snippet b()}
{@render a()}
{/snippet}
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { test } from '../../test';

export default test({
html: '<h1>Hello world!</h1>'
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<script module>
export { foo }
</script>

<script>
let name = 'world';
</script>

<h1>Hello {name}!</h1>

{#snippet foo()}
oo
{/snippet}
Loading