Skip to content
Open
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/fuzzy-wings-sin.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'svelte': minor
---

feat: allow `$state` in computed class fields
4 changes: 2 additions & 2 deletions packages/svelte/src/compiler/phases/2-analyze/types.d.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import type { Scope } from '../scope.js';
import type { ComponentAnalysis, ReactiveStatement } from '../types.js';
import type { AST, StateField, ValidatedCompileOptions } from '#compiler';
import type { AST, StateFields, ValidatedCompileOptions } from '#compiler';
import type { ExpressionMetadata } from '../nodes.js';

export interface AnalysisState {
Expand All @@ -22,7 +22,7 @@ export interface AnalysisState {
expression: ExpressionMetadata | null;

/** Used to analyze class state */
state_fields: Map<string, StateField>;
state_fields: StateFields;

function_depth: number;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -313,7 +313,7 @@ function is_variable_declaration(parent, context) {
* @param {AST.SvelteNode} parent
*/
function is_class_property_definition(parent) {
return parent.type === 'PropertyDefinition' && !parent.static && !parent.computed;
return parent.type === 'PropertyDefinition' && !parent.static;
}

/**
Expand All @@ -325,10 +325,7 @@ function is_class_property_assignment_at_constructor_root(node, context) {
node.type === 'AssignmentExpression' &&
node.operator === '=' &&
node.left.type === 'MemberExpression' &&
node.left.object.type === 'ThisExpression' &&
((node.left.property.type === 'Identifier' && !node.left.computed) ||
node.left.property.type === 'PrivateIdentifier' ||
node.left.property.type === 'Literal')
node.left.object.type === 'ThisExpression'
) {
// MethodDefinition (-5) -> FunctionExpression (-4) -> BlockStatement (-3) -> ExpressionStatement (-2) -> AssignmentExpression (-1)
const parent = get_parent(context.path, -5);
Expand Down
55 changes: 39 additions & 16 deletions packages/svelte/src/compiler/phases/2-analyze/visitors/ClassBody.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,55 +30,67 @@ export function ClassBody(node, context) {
}
}

/** @type {Map<string, StateField>} */
/** @type {Map<string | number, StateField>} */
const state_fields = new Map();

/** @type {Map<string, Array<MethodDefinition['kind'] | 'prop' | 'assigned_prop'>>} */
/** @type {Map<string | number, Array<MethodDefinition['kind'] | 'prop' | 'assigned_prop'>>} */
const fields = new Map();

context.state.analysis.classes.set(node, state_fields);

/** @type {MethodDefinition | null} */
let constructor = null;

function increment_computed() {
const numbered_keys = [...state_fields.keys()].filter((key) => typeof key === 'number');
return numbered_keys.length;
}
/**
* @param {PropertyDefinition | AssignmentExpression} node
* @param {Expression | PrivateIdentifier} key
* @param {Expression | null | undefined} value
* @param {boolean} [computed]
*/
function handle(node, key, value) {
const name = get_name(key);
function handle(node, key, value, computed = false) {
const name = computed ? increment_computed() : get_name(key);
if (name === null) return;

const rune = get_rune(value, context.state.scope);

if (rune && is_state_creation_rune(rune)) {
if (state_fields.has(name)) {
if (typeof name === 'string' && state_fields.has(name)) {
e.state_field_duplicate(node, name);
}

const _key = (node.type === 'AssignmentExpression' || !node.static ? '' : '@') + name;
const _key =
typeof name === 'string'
? (node.type === 'AssignmentExpression' || !node.static ? '' : '@') + name
: name;
const field = fields.get(_key);

// if there's already a method or assigned field, error
if (field && !(field.length === 1 && field[0] === 'prop')) {
e.duplicate_class_field(node, _key);
e.duplicate_class_field(node, typeof _key === 'string' ? _key : '[computed key]');
}

state_fields.set(name, {
node,
type: rune,
// @ts-expect-error for public state this is filled out in a moment
key: key.type === 'PrivateIdentifier' ? key : null,
value: /** @type {CallExpression} */ (value)
value: /** @type {CallExpression} */ (value),
computed_key: computed ? /** @type {Expression} */ (key) : null
});
}
}

for (const child of node.body) {
if (child.type === 'PropertyDefinition' && !child.computed && !child.static) {
handle(child, child.key, child.value);
const key = /** @type {string} */ (get_name(child.key));
if (child.type === 'PropertyDefinition' && !child.static) {
handle(child, child.key, child.value, child.computed && child.key.type !== 'Literal');
const key = get_name(child.key);
if (key === null) {
continue;
}
const field = fields.get(key);
if (!field) {
fields.set(key, [child.value ? 'assigned_prop' : 'prop']);
Expand All @@ -91,7 +103,11 @@ export function ClassBody(node, context) {
if (child.kind === 'constructor') {
constructor = child;
} else if (!child.computed) {
const key = (child.static ? '@' : '') + get_name(child.key);
const name = get_name(child.key);
if (name === null) {
continue;
}
const key = (child.static ? '@' : '') + name;
const field = fields.get(key);
if (!field) {
fields.set(key, [child.kind]);
Expand Down Expand Up @@ -132,18 +148,25 @@ export function ClassBody(node, context) {

if (left.type !== 'MemberExpression') continue;
if (left.object.type !== 'ThisExpression') continue;
if (left.computed && left.property.type !== 'Literal') continue;

handle(statement.expression, left.property, right);
handle(
statement.expression,
left.property,
right,
left.computed && left.property.type !== 'Literal'
);
}
}

for (const [name, field] of state_fields) {
if (name[0] === '#') {
if (typeof name === 'string' && name[0] === '#') {
continue;
}

let deconflicted = name.replace(regex_invalid_identifier_chars, '_');
let deconflicted = `${typeof name === 'number' ? '_' : ''}${name}`.replace(
regex_invalid_identifier_chars,
'_'
);
while (private_ids.includes(deconflicted)) {
deconflicted = '_' + deconflicted;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ import { BlockStatement } from './visitors/BlockStatement.js';
import { BreakStatement } from './visitors/BreakStatement.js';
import { CallExpression } from './visitors/CallExpression.js';
import { ClassBody } from './visitors/ClassBody.js';
import { ClassDeclaration } from './visitors/ClassDeclaration.js';
import { ClassExpression } from './visitors/ClassExpression.js';
import { Comment } from './visitors/Comment.js';
import { Component } from './visitors/Component.js';
import { ConstTag } from './visitors/ConstTag.js';
Expand All @@ -45,6 +47,7 @@ import { RenderTag } from './visitors/RenderTag.js';
import { SlotElement } from './visitors/SlotElement.js';
import { SnippetBlock } from './visitors/SnippetBlock.js';
import { SpreadAttribute } from './visitors/SpreadAttribute.js';
import { StaticBlock } from './visitors/StaticBlock.js';
import { SvelteBody } from './visitors/SvelteBody.js';
import { SvelteComponent } from './visitors/SvelteComponent.js';
import { SvelteDocument } from './visitors/SvelteDocument.js';
Expand Down Expand Up @@ -97,6 +100,8 @@ const visitors = {
BreakStatement,
CallExpression,
ClassBody,
ClassDeclaration,
ClassExpression,
Comment,
Component,
ConstTag,
Expand All @@ -123,6 +128,7 @@ const visitors = {
SlotElement,
SnippetBlock,
SpreadAttribute,
StaticBlock,
SvelteBody,
SvelteComponent,
SvelteDocument,
Expand Down Expand Up @@ -168,6 +174,7 @@ export function client_component(analysis, options) {
in_constructor: false,
instance_level_snippets: [],
module_level_snippets: [],
computed_field_declarations: null,

// these are set inside the `Fragment` visitor, and cannot be used until then
init: /** @type {any} */ (null),
Expand Down Expand Up @@ -714,7 +721,8 @@ export function client_module(analysis, options) {
state_fields: new Map(),
transform: {},
in_constructor: false,
is_instance: false
is_instance: false,
computed_field_declarations: null
};

const module = /** @type {ESTree.Program} */ (
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
/** @import { ArrowFunctionExpression, BlockStatement, Expression, FunctionDeclaration, FunctionExpression, Statement } from 'estree' */
/** @import { ArrowFunctionExpression, BlockStatement, Declaration, Expression, FunctionDeclaration, FunctionExpression, Statement, VariableDeclaration } from 'estree' */
/** @import { ComponentContext } from '../types' */
import { add_state_transformers } from './shared/declarations.js';
import * as b from '#compiler/builders';
Expand All @@ -11,6 +11,24 @@ export function BlockStatement(node, context) {
add_state_transformers(context);
const tracing = context.state.scope.tracing;

/** @type {BlockStatement['body']} */
const body = [];
for (const child of node.body) {
const visited = /** @type {Declaration | Statement} */ (context.visit(child));
if (
visited.type === 'ClassDeclaration' &&
'metadata' in visited &&
visited.metadata !== null &&
typeof visited.metadata === 'object' &&
'computed_field_declarations' in visited.metadata
) {
body.push(
.../** @type {VariableDeclaration[]} */ (visited.metadata.computed_field_declarations)
);
}
body.push(visited);
}

if (tracing !== null) {
const parent =
/** @type {ArrowFunctionExpression | FunctionDeclaration | FunctionExpression} */ (
Expand All @@ -22,11 +40,10 @@ export function BlockStatement(node, context) {
const call = b.call(
'$.trace',
/** @type {Expression} */ (tracing),
b.thunk(b.block(node.body.map((n) => /** @type {Statement} */ (context.visit(n)))), is_async)
b.thunk(b.block(body), is_async)
);

return b.block([b.return(is_async ? b.await(call) : call)]);
}

context.next();
return b.block(body);
}
Loading
Loading