Skip to content

fix: legacy mode: use coarse reactivity in the block's expressions #16073

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

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
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/popular-dancers-switch.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'svelte': patch
---

fix: legacy mode: use coarse reactivity in the block's expressions
Original file line number Diff line number Diff line change
Expand Up @@ -2,20 +2,16 @@
/** @import { AST } from '#compiler' */
/** @import { ComponentContext } from '../types' */
import * as b from '../../../../utils/builders.js';
import { build_legacy_expression } from './shared/utils.js';

/**
* @param {AST.AttachTag} node
* @param {ComponentContext} context
*/
export function AttachTag(node, context) {
context.state.init.push(
b.stmt(
b.call(
'$.attach',
context.state.node,
b.thunk(/** @type {Expression} */ (context.visit(node.expression)))
)
)
);
const expression = context.state.analysis.runes
? /** @type {Expression} */ (context.visit(node.expression))
: build_legacy_expression(node.expression, context);
context.state.init.push(b.stmt(b.call('$.attach', context.state.node, b.thunk(expression))));
context.next();
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { extract_identifiers } from '../../../../utils/ast.js';
import * as b from '#compiler/builders';
import { create_derived } from '../utils.js';
import { get_value } from './shared/declarations.js';
import { build_legacy_expression } from './shared/utils.js';

/**
* @param {AST.AwaitBlock} node
Expand All @@ -14,7 +15,11 @@ export function AwaitBlock(node, context) {
context.state.template.push_comment();

// Visit {#await <expression>} first to ensure that scopes are in the correct order
const expression = b.thunk(/** @type {Expression} */ (context.visit(node.expression)));
const expression = b.thunk(
context.state.analysis.runes
? /** @type {Expression} */ (context.visit(node.expression))
: build_legacy_expression(node.expression, context)
);

let then_block;
let catch_block;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { extract_identifiers } from '../../../../utils/ast.js';
import * as b from '#compiler/builders';
import { create_derived } from '../utils.js';
import { get_value } from './shared/declarations.js';
import { build_legacy_expression } from './shared/utils.js';

/**
* @param {AST.ConstTag} node
Expand All @@ -15,15 +16,10 @@ export function ConstTag(node, context) {
const declaration = node.declaration.declarations[0];
// TODO we can almost certainly share some code with $derived(...)
if (declaration.id.type === 'Identifier') {
context.state.init.push(
b.const(
declaration.id,
create_derived(
context.state,
b.thunk(/** @type {Expression} */ (context.visit(declaration.init)))
)
)
);
const init = context.state.analysis.runes
? /** @type {Expression} */ (context.visit(declaration.init))
: build_legacy_expression(declaration.init, context);
context.state.init.push(b.const(declaration.id, create_derived(context.state, b.thunk(init))));

context.state.transform[declaration.id.name] = { read: get_value };

Expand All @@ -48,13 +44,13 @@ export function ConstTag(node, context) {

// TODO optimise the simple `{ x } = y` case — we can just return `y`
// instead of destructuring it only to return a new object
const init = context.state.analysis.runes
? /** @type {Expression} */ (context.visit(declaration.init, child_state))
: build_legacy_expression(declaration.init, { ...context, state: child_state });
const fn = b.arrow(
[],
b.block([
b.const(
/** @type {Pattern} */ (context.visit(declaration.id, child_state)),
/** @type {Expression} */ (context.visit(declaration.init, child_state))
),
b.const(/** @type {Pattern} */ (context.visit(declaration.id, child_state)), init),
b.return(b.object(identifiers.map((node) => b.prop('init', node, node))))
])
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import { extract_paths, object } from '../../../../utils/ast.js';
import * as b from '#compiler/builders';
import { build_getter } from '../utils.js';
import { get_value } from './shared/declarations.js';
import { build_legacy_expression } from './shared/utils.js';

/**
* @param {AST.EachBlock} node
Expand All @@ -24,12 +25,16 @@ export function EachBlock(node, context) {

// expression should be evaluated in the parent scope, not the scope
// created by the each block itself
const collection = /** @type {Expression} */ (
context.visit(node.expression, {
...context.state,
scope: /** @type {Scope} */ (context.state.scope.parent)
})
);
const parent_scope_state = {
...context.state,
scope: /** @type {Scope} */ (context.state.scope.parent)
};
const collection = context.state.analysis.runes
? /** @type {Expression} */ (context.visit(node.expression, parent_scope_state))
: build_legacy_expression(node.expression, {
...context,
state: parent_scope_state
});

if (!each_node_meta.is_controlled) {
context.state.template.push_comment();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
/** @import { ComponentContext } from '../types' */
import { is_ignored } from '../../../../state.js';
import * as b from '#compiler/builders';
import { build_legacy_expression } from './shared/utils.js';

/**
* @param {AST.HtmlTag} node
Expand All @@ -11,7 +12,9 @@ import * as b from '#compiler/builders';
export function HtmlTag(node, context) {
context.state.template.push_comment();

const expression = /** @type {Expression} */ (context.visit(node.expression));
const expression = context.state.analysis.runes
? /** @type {Expression} */ (context.visit(node.expression))
: build_legacy_expression(node.expression, context);

const is_svg = context.state.metadata.namespace === 'svg';
const is_mathml = context.state.metadata.namespace === 'mathml';
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
/** @import { AST } from '#compiler' */
/** @import { ComponentContext } from '../types' */
import * as b from '#compiler/builders';
import { build_legacy_expression } from './shared/utils.js';

/**
* @param {AST.IfBlock} node
Expand Down Expand Up @@ -31,14 +32,18 @@ export function IfBlock(node, context) {
statements.push(b.var(b.id(alternate_id), b.arrow(alternate_args, alternate)));
}

const test = context.state.analysis.runes
? /** @type {Expression} */ (context.visit(node.test))
: build_legacy_expression(node.test, context);

/** @type {Expression[]} */
const args = [
node.elseif ? b.id('$$anchor') : context.state.node,
b.arrow(
[b.id('$$render')],
b.block([
b.if(
/** @type {Expression} */ (context.visit(node.test)),
test,
b.stmt(b.call(b.id('$$render'), b.id(consequent_id))),
alternate_id ? b.stmt(b.call(b.id('$$render'), b.id(alternate_id), b.false)) : undefined
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
/** @import { AST } from '#compiler' */
/** @import { ComponentContext } from '../types' */
import * as b from '#compiler/builders';
import { build_legacy_expression } from './shared/utils.js';

/**
* @param {AST.KeyBlock} node
Expand All @@ -10,7 +11,9 @@ import * as b from '#compiler/builders';
export function KeyBlock(node, context) {
context.state.template.push_comment();

const key = /** @type {Expression} */ (context.visit(node.expression));
const key = context.state.analysis.runes
? /** @type {Expression} */ (context.visit(node.expression))
: build_legacy_expression(node.expression, context);
const body = /** @type {Expression} */ (context.visit(node.fragment));

context.state.init.push(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
/** @import { ComponentContext } from '../types' */
import { unwrap_optional } from '../../../../utils/ast.js';
import * as b from '#compiler/builders';
import { build_legacy_expression } from './shared/utils.js';

/**
* @param {AST.RenderTag} node
Expand Down Expand Up @@ -31,7 +32,9 @@ export function RenderTag(node, context) {
}
}

let snippet_function = /** @type {Expression} */ (context.visit(callee));
let snippet_function = context.state.analysis.runes
? /** @type {Expression} */ (context.visit(callee))
: build_legacy_expression(/** @type {Expression} */ (callee), context);

if (node.metadata.dynamic) {
// If we have a chain expression then ensure a nullish snippet function gets turned into an empty one
Expand Down
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
/** @import { AssignmentExpression, Expression, ExpressionStatement, Identifier, MemberExpression, SequenceExpression, Literal, Super, UpdateExpression } from 'estree' */
/** @import { AssignmentExpression, Expression, ExpressionStatement, Identifier, MemberExpression, SequenceExpression, Literal, Super, UpdateExpression, Pattern } from 'estree' */
/** @import { AST, ExpressionMetadata } from '#compiler' */
/** @import { ComponentClientTransformState, Context } from '../../types' */
/** @import { ComponentClientTransformState, ComponentContext, Context } from '../../types' */
import { walk } from 'zimmerframe';
import { object } from '../../../../../utils/ast.js';
import * as b from '#compiler/builders';
import { sanitize_template_string } from '../../../../../utils/sanitize_template_string.js';
import { regex_is_valid_identifier } from '../../../../patterns.js';
import is_reference from 'is-reference';
import { dev, is_ignored, locator } from '../../../../../state.js';
import { create_derived } from '../../utils.js';
import { build_getter, create_derived } from '../../utils.js';

/**
* @param {ComponentClientTransformState} state
Expand Down Expand Up @@ -360,3 +360,135 @@ export function validate_mutation(node, context, expression) {
loc && b.literal(loc.column)
);
}

/**
* Checks whether the expression contains assignments, function calls, or member accesses
* @param {Expression|Pattern} expression
* @returns {boolean}
*/
function is_pure_expression(expression) {
// It's supposed that values do not have custom @@toPrimitive() or toString(),
// which may be implicitly called in expressions like `a + b`, `a & b`, `+a`, `str: ${a}`
switch (expression.type) {
case 'ArrayExpression':
return expression.elements.every(
(element) =>
element == null ||
(element.type === 'SpreadElement' ? false : is_pure_expression(element))
);
case 'BinaryExpression':
return (
expression.left.type !== 'PrivateIdentifier' &&
is_pure_expression(expression.left) &&
is_pure_expression(expression.right)
);
case 'ConditionalExpression':
return (
is_pure_expression(expression.test) &&
is_pure_expression(expression.consequent) &&
is_pure_expression(expression.alternate)
);
case 'Identifier':
return true;
case 'Literal':
return true;
case 'LogicalExpression':
return is_pure_expression(expression.left) && is_pure_expression(expression.right);
case 'MetaProperty':
return true; // new.target
case 'ObjectExpression':
return expression.properties.every(
(property) =>
property.type !== 'SpreadElement' &&
property.key.type !== 'PrivateIdentifier' &&
is_pure_expression(property.key) &&
is_pure_expression(property.value)
);
case 'SequenceExpression':
return expression.expressions.every(is_pure_expression);
case 'TemplateLiteral':
return expression.expressions.every(is_pure_expression);
case 'ThisExpression':
return true;
case 'UnaryExpression':
return is_pure_expression(expression.argument);
case 'YieldExpression':
return expression.argument == null || is_pure_expression(expression.argument);

case 'ArrayPattern':
case 'ArrowFunctionExpression':
case 'AssignmentExpression':
case 'AssignmentPattern':
case 'AwaitExpression':
case 'CallExpression':
case 'ChainExpression':
case 'ClassExpression':
case 'FunctionExpression':
case 'ImportExpression':
case 'MemberExpression':
case 'NewExpression':
case 'ObjectPattern':
case 'RestElement':
case 'TaggedTemplateExpression':
case 'UpdateExpression':
return false;
}
}

/**
* Serializes an expression with reactivity like in Svelte 4
* @param {Expression} expression
* @param {ComponentContext} context
*/
export function build_legacy_expression(expression, context) {
// To recreate Svelte 4 behaviour, we track the dependencies
// the compiler can 'see', but we untrack the effect itself
const serialized_expression = /** @type {Expression} */ (context.visit(expression));
if (is_pure_expression(expression)) return serialized_expression;

/** @type {Expression[]} */
const sequence = [];

for (const [name, nodes] of context.state.scope.references) {
const binding = context.state.scope.get(name);

if (binding === null || (binding.kind === 'normal' && binding.declaration_kind !== 'import'))
continue;

let used = false;
for (const { node, path } of nodes) {
const expression_idx = path.indexOf(expression);
if (expression_idx < 0) continue;
// in Svelte 4, #if, #each and #await copy context, so assignments
// aren't propagated to the parent block / component root
const track_assignment = !path.find(
(node, i) =>
i < expression_idx - 1 && ['IfBlock', 'EachBlock', 'AwaitBlock'].includes(node.type)
);
if (track_assignment) {
used = true;
break;
}
const assignment = /** @type {AssignmentExpression|undefined} */ (
path.find((node, i) => i >= expression_idx && node.type === 'AssignmentExpression')
);
if (!assignment || (assignment.left !== node && !path.includes(assignment.left))) {
used = true;
break;
}
}
if (!used) continue;

let serialized = build_getter(b.id(name), context.state);

// If the binding is a prop, we need to deep read it because it could be fine-grained $state
// from a runes-component, where mutations don't trigger an update on the prop as a whole.
if (name === '$$props' || name === '$$restProps' || binding.kind === 'bindable_prop') {
serialized = b.call('$.deep_read_state', serialized);
}

sequence.push(serialized);
}

return b.sequence([...sequence, b.call('$.untrack', b.thunk(serialized_expression))]);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { flushSync } from 'svelte';
import { test } from '../../test';

export default test({
test({ assert, target }) {
const button = target.querySelector('button');

assert.htmlEqual(target.innerHTML, `<div></div><button>inc</button> [0,0,0,0,0,0,0,0,0]`);
flushSync(() => button?.click());
assert.htmlEqual(target.innerHTML, `<div></div><button>inc</button> [0,0,0,0,0,0,0,0,1]`);
}
});
Loading