Skip to content

feat: improve scoping of snippet declarations acting as slot properties #645

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 2 commits into from
Jan 15, 2025
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/blue-eggs-work.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"svelte-eslint-parser": minor
---

feat: improve scoping of snippet declarations acting as slot properties
33 changes: 27 additions & 6 deletions src/parser/analyze-scope.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,12 @@ import type {
SvelteScriptElement,
SvelteSnippetBlock,
} from "../ast/index.js";
import { addReference, addVariable, getScopeFromNode } from "../scope/index.js";
import {
addReference,
addVariable,
getScopeFromNode,
removeIdentifierVariable,
} from "../scope/index.js";
import { addElementToSortedArray } from "../utils/index.js";
import type { NormalizedParserOptions } from "./parser-options.js";
import type { SvelteParseContext } from "./svelte-parse-context.js";
Expand Down Expand Up @@ -304,11 +309,27 @@ export function analyzeSnippetsScope(
if (!upperScope) continue;
const variable = upperScope.set.get(snippet.id.name);
if (!variable) continue;
// Add the virtual reference for reading.
const reference = addVirtualReference(snippet.id, variable, upperScope, {
read: true,
});
(reference as any).svelteSnippetReference = true;
const defIds = variable.defs.map((d) => d.name);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Line number 305, I don't think we need to handle <svelte:boundary>.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think <svelte:boundary> needs to be handled because it has a failed slot.

Currently, no-shadow is reported:

<script lang="ts">
  let failed = false;
</script>

<svelte:boundary>
	<MyComponent />

	{#snippet failed()}
		<div>oops! try again</div>
	{/snippet}
</svelte:boundary>

Demo

Am I misunderstanding something?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As you say, only the failed slot can be used in an actual <svelte:boundary>.
However, I think parsers and scope analyzers should avoid handling by name whenever possible.
I think checking for these is done by lint rules and type checking.
Also, new slots may appear in the future.

Copy link
Member

@baseballyama baseballyama Jan 15, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In the REPL above, hello snippet is also rendered, right?
So <svelte:boundary> can use any {@snippet} IIUC.

So I guess snippets other than failed should still be handled by the scope manager.

Copy link
Member

@baseballyama baseballyama Jan 15, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Going back to the topic, I shared my opinion that the following case should not involve changes to the scope manager. What are your thoughts on this?

<svelte:boundary>
	{#snippet hello(name)}
		<p>hello {name}!</p>
	{/snippet}
</svelte:boundary>

Original (My opinion is keeping this scope manager)
image

This PR
image

Copy link
Member Author

@ota-meshi ota-meshi Jan 15, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think the confusion comes from the fact that the {#snippet} syntax is both a declaration and an expression.

First of all, any {#snippet} that isn't specified directly on a component or <svelte:boundary> is always a declaration. It is excluded by conditions L300-L306.

When specified on a component, {#snippet} is both a declaration and an expression.
It's like the following is done at once:

function mySnippet() {
}
const componentProps = { mySnippet }

In terms of the parser processing, {#snippet} is generated by a function declaration in virtual code, so it has a variable. Then, by adding a reference as an expression at the variable position in L323, it behaves as both a declaration and an expression.

The purpose of this PR change is to remove the declarative behavior from {#snippet} that is only used as a component prop, that is, to treat {#snippet} as an expression in this case.

The image is as follows:

const componentProps = { mySnippet() {} }

In terms of parser processing, if {#snippet} is only declared and not used anywhere else, the declared variables of the snippet are removed so that it behaves as if it were just an anonymous expression.

The following hello snippet only behaves as an expression, so the variables are not added in the scope manager.

<svelte:boundary>
	{#snippet hello(name)}
		<p>hello {name}!</p>
	{/snippet}
</svelte:boundary>

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

(日本語ですみません🙇)
ありがとうございます! 恐らくここまで同じ理解をできていると思います!
<svelte:boundary> を使用する場合、failed スニペットは <svelte:boundary> のために特別に用意されたスニペットなので、他のどこからも参照されていなかったとしてもそれは有効です。なので、このPRで対処されるべきです。
一方、<svelte:boundary> 直下で宣言されるそれ以外のスニペットは、他の部分で (例えばコンポーネントルートで) 宣言するスニペットと同じように動作するので、このPRでの特別対応からは除外した方がいいんじゃないか、という確認でした🙋 (つまり、以下の例では、 hello はただの declaration であるがどこからも使用されていないスニペットである)

<svelte:boundary>
	{#snippet hello(name)}
		<p>hello {name}!</p>
	{/snippet}
</svelte:boundary>

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

つまり、以下の例では、 hello はただの declaration であるがどこからも使用されていないスニペットである

はい。実際そうなのですが、それは<svelte:boundary>の実装の話だと思っていまして、パーサーではスニペット名で分岐せず「式のみ」として記述されたスニペットとして扱うのが良いと思っています。
今後<svelte:boundary>に新しいスニペットが追加されるたびに名前で分岐入れるのは厳しいですし、<svelte:boundary>で使えないスニペットが「式のみ」にならないのなら、カスタムコンポーネントが持っていないスニペットが「式のみ」になるのも一貫性がないので、今のPRの動きが妥当なところかなと思ってます 😃

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ありがとうございます! ようやく完全に理解できました!

const refs = variable.references.filter(
(id) => !defIds.includes(id.identifier),
);

if (refs.length <= 0) {
// If the snippet is not referenced,
// remove the a variable from the upperScope.
removeIdentifierVariable(snippet.id, upperScope);
} else {
// Add the virtual reference for reading.
const reference = addVirtualReference(
snippet.id,
variable,
upperScope,
{
read: true,
},
);
(reference as any).svelteSnippetReference = true;
}
}
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
<script lang="ts">
import Foo from './Foo.svelte';
</script>

<div>
<!-- The snippet is not used. -->
{#snippet children()}
<th>fruit</th>
<th>qty</th>
<th>price</th>
<th>total</th>
{/snippet}
</div>

<Foo>
<!-- The snippet is used and does not add any variables. -->
{#snippet children(arg)}
<p>{arg}</p>
{/snippet}
{#snippet c()}
<Foo>
<!-- The snippet is used and does not add any variables. -->
{#snippet children(arg)}
<p>{arg}</p>
{/snippet}
</Foo>
{/snippet}
</Foo>

<!-- The snippet is used and add a variable. -->
{#snippet bar(arg)}
<p>{arg}</p>
{/snippet}
<Foo children={bar}>
{#snippet c()}
<!-- The snippet is used and add a variable. -->
{#snippet bar(arg)}
<p>{arg}</p>
{/snippet}
<Foo children={bar}>
</Foo>
{/snippet}
</Foo>
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
[
{
"ruleId": "no-unused-vars",
"code": "children",
"line": 7,
"column": 12,
"message": "'children' is defined but never used."
},
{
"ruleId": "no-shadow",
"code": "bar",
"line": 37,
"column": 13,
"message": "'bar' is already declared in the upper scope on line 31 column 11."
},
{
"ruleId": "@typescript-eslint/no-shadow",
"code": "bar",
"line": 37,
"column": 13,
"message": "'bar' is already declared in the upper scope on line 31 column 11."
}
]
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"parse": {
"svelte": ">=5.0.0-0"
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import type { Linter } from "eslint";
import { generateParserOptions } from "../../../src/parser/test-utils.js";
import { rules } from "@typescript-eslint/eslint-plugin";
import * as parser from "../../../../src/index.js";
import globals from "globals";

export function getConfig(): Linter.Config {
return {
plugins: {
"@typescript-eslint": {
rules: rules as any,
},
},
languageOptions: {
parser,
parserOptions: {
...generateParserOptions(),
svelteFeatures: { runes: true },
},
globals: {
...globals.browser,
...globals.es2021,
},
},
rules: {
"no-shadow": "error",
"@typescript-eslint/no-shadow": "error",
"no-undef": "error",
"no-unused-vars": "error",
},
};
}
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import type { Linter } from "eslint";
import { generateParserOptions } from "../../../src/parser/test-utils";
import { generateParserOptions } from "../../../src/parser/test-utils.js";
import { rules } from "@typescript-eslint/eslint-plugin";
import * as parser from "../../../../src";
import * as parser from "../../../../src/index.js";
import globals from "globals";

export function getConfig(): Linter.Config {
Expand Down
Loading
Loading