fix: disallow static state fields (#9577)

closes #9547
pull/9581/head
Rich Harris 9 months ago committed by GitHub
parent 617df1f3c3
commit 945a90b56c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -490,18 +490,25 @@ function validate_call_expression(node, scope, path) {
const rune = get_rune(node, scope);
if (rune === null) return;
if (rune === '$props' && path.at(-1)?.type !== 'VariableDeclarator') {
const parent = /** @type {import('#compiler').SvelteNode} */ (path.at(-1));
if (rune === '$props') {
if (parent.type === 'VariableDeclarator') return;
error(node, 'invalid-props-location');
} else if (
(rune === '$state' || rune === '$derived') &&
path.at(-1)?.type !== 'VariableDeclarator' &&
path.at(-1)?.type !== 'PropertyDefinition'
) {
}
if (rune === '$state' || rune === '$derived') {
if (parent.type === 'VariableDeclarator') return;
if (parent.type === 'PropertyDefinition' && !parent.static && !parent.computed) return;
error(node, rune === '$derived' ? 'invalid-derived-location' : 'invalid-state-location');
} else if (rune === '$effect') {
if (path.at(-1)?.type !== 'ExpressionStatement') {
}
if (rune === '$effect') {
if (parent.type !== 'ExpressionStatement') {
error(node, 'invalid-effect-location');
} else if (node.arguments.length !== 1) {
}
if (node.arguments.length !== 1) {
error(node, 'invalid-rune-args-length', '$effect', [1]);
}
}

@ -0,0 +1,9 @@
import { test } from '../../test';
export default test({
error: {
code: 'invalid-state-location',
message: '$state() can only be used as a variable declaration initializer or a class field',
position: process.platform === 'win32' ? [35, 43] : [33, 41]
}
});

@ -0,0 +1,5 @@
<script>
class X {
static x = $state();
}
</script>
Loading…
Cancel
Save