Skip to content

feat: more complex partial evaluation #15802

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

Closed
wants to merge 20 commits into from
Closed
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
1 change: 1 addition & 0 deletions packages/svelte/src/compiler/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,7 @@ function to_public_ast(source, ast, modern) {
if (modern) {
const clean = (/** @type {any} */ node) => {
delete node.metadata;
delete node.type_information;
};

ast.options?.attributes.forEach((attribute) => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,30 @@ const visitors = {
_(node, context) {
const n = context.next() ?? node;

// TODO there may come a time when we decide to preserve type annotations.
// until that day comes, we just delete them so they don't confuse esrap
const type_information = {};
if (Object.hasOwn(n, 'typeAnnotation')) {
type_information.annotation = n.typeAnnotation;
}
if (Object.hasOwn(n, 'typeParameters')) {
type_information.parameters = n.typeParameters;
}
if (Object.hasOwn(n, 'typeArguments')) {
type_information.arguments = n.typeArguments;
}
if (Object.hasOwn(n, 'returnType')) {
type_information.return = n.returnType;
}
Object.defineProperty(n, 'type_information', {
value: type_information,
writable: true,
configurable: true,
enumerable: false
});
delete n.typeAnnotation;
delete n.typeParameters;
delete n.typeArguments;
delete n.returnType;
// TODO figure out what this is exactly, and if it should be added to `type_information`
delete n.accessibility;
},
Decorator(node) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
/** @import { BlockStatement, Expression } from 'estree' */
/** @import { AST } from '#compiler' */
/** @import { ComponentContext } from '../types' */
import * as b from '#compiler/builders';

/**
* @param {AST.IfBlock} node
* @param {ComponentContext} context
*/
export function IfBlock(node, context) {
const test = /** @type {Expression} */ (context.visit(node.test));
const evaluated = context.state.scope.evaluate(test);

const consequent = /** @type {BlockStatement} */ (context.visit(node.consequent));
context.state.template.push('<!>');
if (evaluated.is_truthy) {
context.state.init.push(
b.stmt(b.call(b.arrow([b.id('$$anchor')], consequent), context.state.node))
);
} else {
const statements = [];
const consequent_id = context.state.scope.generate('consequent');
statements.push(b.var(b.id(consequent_id), b.arrow([b.id('$$anchor')], consequent)));

let alternate_id;

if (node.alternate) {
alternate_id = context.state.scope.generate('alternate');
const alternate = /** @type {BlockStatement} */ (context.visit(node.alternate));
const nodes = node.alternate.nodes;

let alternate_args = [b.id('$$anchor')];
if (nodes.length === 1 && nodes[0].type === 'IfBlock' && nodes[0].elseif) {
alternate_args.push(b.id('$$elseif'));
}

statements.push(b.var(b.id(alternate_id), b.arrow(alternate_args, alternate)));
}

/** @type {Expression[]} */
const args = [
node.elseif ? b.id('$$anchor') : context.state.node,
b.arrow(
[b.id('$$render')],
b.block([
b.if(
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
)
])
)
];

if (node.elseif) {
// We treat this...
//
// {#if x}
// ...
// {:else}
// {#if y}
// <div transition:foo>...</div>
// {/if}
// {/if}
//
// ...slightly differently to this...
//
// {#if x}
// ...
// {:else if y}
// <div transition:foo>...</div>
// {/if}
//
// ...even though they're logically equivalent. In the first case, the
// transition will only play when `y` changes, but in the second it
// should play when `x` or `y` change — both are considered 'local'
args.push(b.id('$$elseif'));
}

statements.push(b.stmt(b.call('$.if', ...args)));

context.state.init.push(b.block(statements));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -64,20 +64,21 @@ export function build_template_chunk(
node.expression.name !== 'undefined' ||
state.scope.get('undefined')
) {
let value = memoize(
/** @type {Expression} */ (visit(node.expression, state)),
node.metadata.expression
);
let value = /** @type {Expression} */ (visit(node.expression, state));

const evaluated = state.scope.evaluate(value);

if (!evaluated.is_known) {
value = memoize(value, node.metadata.expression);
}

has_state ||= node.metadata.expression.has_state && !evaluated.is_known;

if (values.length === 1) {
// If we have a single expression, then pass that in directly to possibly avoid doing
// extra work in the template_effect (instead we do the work in set_text).
if (evaluated.is_known) {
value = b.literal(evaluated.value);
value = b.literal(evaluated.value ?? '');
}

return { value, has_state };
Expand All @@ -96,7 +97,7 @@ export function build_template_chunk(
}

if (evaluated.is_known) {
quasi.value.cooked += evaluated.value + '';
quasi.value.cooked += (evaluated.value ?? '') + '';
} else {
if (!evaluated.is_defined) {
// add `?? ''` where necessary
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
/** @import { BlockStatement, Expression } from 'estree' */
/** @import { AST } from '#compiler' */
/** @import { ComponentContext } from '../types.js' */
import { BLOCK_OPEN_ELSE } from '../../../../../internal/server/hydration.js';
import * as b from '#compiler/builders';
import { block_close, block_open } from './shared/utils.js';
import { needs_new_scope } from '../../utils.js';

/**
* @param {AST.IfBlock} node
* @param {ComponentContext} context
*/
export function IfBlock(node, context) {
const consequent = /** @type {BlockStatement} */ (context.visit(node.consequent));
const test = /** @type {Expression} */ (context.visit(node.test));
const evaluated = context.state.scope.evaluate(test);
if (evaluated.is_truthy) {
if (needs_new_scope(consequent)) {
context.state.template.push(consequent);
} else {
context.state.template.push(...consequent.body);
}
} else {
consequent.body.unshift(b.stmt(b.assignment('+=', b.id('$$payload.out'), block_open)));
let if_statement = b.if(test, consequent);

context.state.template.push(if_statement, block_close);

let index = 1;
let alt = node.alternate;
while (
alt &&
alt.nodes.length === 1 &&
alt.nodes[0].type === 'IfBlock' &&
alt.nodes[0].elseif
) {
const elseif = alt.nodes[0];
const alternate = /** @type {BlockStatement} */ (context.visit(elseif.consequent));
alternate.body.unshift(
b.stmt(b.assignment('+=', b.id('$$payload.out'), b.literal(`<!--[${index++}-->`)))
);
if_statement = if_statement.alternate = b.if(
/** @type {Expression} */ (context.visit(elseif.test)),
alternate
);
alt = elseif.alternate;
}

if_statement.alternate = alt ? /** @type {BlockStatement} */ (context.visit(alt)) : b.block([]);
if_statement.alternate.body.unshift(
b.stmt(b.assignment('+=', b.id('$$payload.out'), b.literal(BLOCK_OPEN_ELSE)))
);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import {
import * as b from '#compiler/builders';
import { sanitize_template_string } from '../../../../../utils/sanitize_template_string.js';
import { regex_whitespaces_strict } from '../../../../patterns.js';
import { NUMBER } from '../../../../scope.js';

/** Opens an if/each block, so that we can remove nodes in the case of a mismatch */
export const block_open = b.literal(BLOCK_OPEN);
Expand Down Expand Up @@ -45,13 +46,19 @@ export function process_children(nodes, { visit, state }) {
quasi.value.cooked +=
node.type === 'Comment' ? `<!--${node.data}-->` : escape_html(node.data);
} else {
const evaluated = state.scope.evaluate(node.expression);

const expression = /** @type {Expression} */ (visit(node.expression));
const evaluated = state.scope.evaluate(expression);
if (evaluated.is_known) {
quasi.value.cooked += escape_html((evaluated.value ?? '') + '');
} else {
expressions.push(b.call('$.escape', /** @type {Expression} */ (visit(node.expression))));

if (
(evaluated.values.size === 1 && [...evaluated.values][0] === NUMBER) ||
[...evaluated.values].every((value) => typeof value === 'string' && !/[&<]/.test(value))
) {
expressions.push(expression);
} else {
expressions.push(b.call('$.escape', expression));
}
quasi = b.quasi('', i + 1 === sequence.length);
quasis.push(quasi);
}
Expand Down
13 changes: 12 additions & 1 deletion packages/svelte/src/compiler/phases/3-transform/utils.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
/** @import { Context } from 'zimmerframe' */
/** @import { TransformState } from './types.js' */
/** @import { AST, Binding, Namespace, ValidatedCompileOptions } from '#compiler' */
/** @import { Node, Expression, CallExpression } from 'estree' */
/** @import { Node, Expression, CallExpression, BlockStatement } from 'estree' */
import {
regex_ends_with_whitespaces,
regex_not_whitespace,
Expand Down Expand Up @@ -486,3 +486,14 @@ export function transform_inspect_rune(node, context) {
return b.call('$.inspect', as_fn ? b.thunk(b.array(arg)) : b.array(arg));
}
}

/**
* Whether a `BlockStatement` needs to be a block statement as opposed to just inlining all of its statements.
* @param {BlockStatement} block
*/
export function needs_new_scope(block) {
const has_vars = block.body.some((child) => child.type === 'VariableDeclaration');
const has_fns = block.body.some((child) => child.type === 'FunctionDeclaration');
const has_class = block.body.some((child) => child.type === 'ClassDeclaration');
return has_vars || has_fns || has_class;
}
Loading