Skip to content

feat: only inject push/init/pop when necessary #11319

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 10 commits into from
Apr 25, 2024
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/nervous-berries-boil.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'svelte': patch
---

feat: only inject push/init/pop when necessary
51 changes: 50 additions & 1 deletion packages/svelte/src/compiler/phases/2-analyze/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -370,6 +370,8 @@ export function analyze_component(root, source, options) {
uses_slots: false,
uses_component_bindings: false,
uses_render_tags: false,
needs_context: false,
needs_props: false,
custom_element: options.customElementOptions ?? options.customElement,
inject_styles: options.css === 'injected' || options.customElement,
accessors: options.customElement
Expand Down Expand Up @@ -803,6 +805,8 @@ const legacy_scope_tweaker = {
return next();
}

state.analysis.needs_props = true;

if (!node.declaration) {
for (const specifier of node.specifiers) {
const binding = /** @type {import('#compiler').Binding} */ (
Expand Down Expand Up @@ -931,6 +935,8 @@ const runes_scope_tweaker = {
}

if (rune === '$props') {
state.analysis.needs_props = true;

for (const property of /** @type {import('estree').ObjectPattern} */ (node.id).properties) {
if (property.type !== 'Property') continue;

Expand Down Expand Up @@ -1038,6 +1044,33 @@ const function_visitor = (node, context) => {
});
};

/**
* A 'safe' identifier means that the `foo` in `foo.bar` or `foo()` will not
* call functions that require component context to exist
* @param {import('estree').Expression | import('estree').Super} expression
* @param {Scope} scope
*/
function is_safe_identifier(expression, scope) {
let node = expression;
while (node.type === 'MemberExpression') node = node.object;

if (node.type !== 'Identifier') return false;

const binding = scope.get(node.name);
if (!binding) return true;

if (binding.kind === 'store_sub') {
return is_safe_identifier({ name: node.name.slice(1), type: 'Identifier' }, scope);
}

return (
binding.declaration_kind !== 'import' &&
binding.kind !== 'prop' &&
binding.kind !== 'bindable_prop' &&
binding.kind !== 'rest_prop'
);
}

/** @type {import('./types').Visitors} */
const common_visitors = {
_(node, context) {
Expand Down Expand Up @@ -1209,14 +1242,16 @@ const common_visitors = {
}

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

if (callee.type === 'Identifier') {
const binding = context.state.scope.get(callee.name);

if (binding !== null) {
binding.is_called = true;
}

if (get_rune(node, context.state.scope) === '$derived') {
if (rune === '$derived') {
// special case — `$derived(foo)` is treated as `$derived(() => foo)`
// for the purposes of identifying static state references
context.next({
Expand All @@ -1228,13 +1263,27 @@ const common_visitors = {
}
}

if (rune === '$effect' || rune === '$effect.pre') {
// `$effect` needs context because Svelte needs to know whether it should re-run
// effects that invalidate themselves, and that's determined by whether we're in runes mode
context.state.analysis.needs_context = true;
} else if (rune === null) {
if (!is_safe_identifier(callee, context.state.scope)) {
context.state.analysis.needs_context = true;
}
}

context.next();
},
MemberExpression(node, context) {
if (context.state.expression) {
context.state.expression.metadata.dynamic = true;
}

if (!is_safe_identifier(node, context.state.scope)) {
context.state.analysis.needs_context = true;
}

context.next();
},
BindDirective(node, context) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -351,12 +351,11 @@ export function client_component(source, analysis, options) {
if (options.dev) push_args.push(b.id(analysis.name));

const component_block = b.block([
b.stmt(b.call('$.push', ...push_args)),
...store_setup,
...legacy_reactive_declarations,
...group_binding_declarations,
.../** @type {import('estree').Statement[]} */ (instance.body),
analysis.runes ? b.empty : b.stmt(b.call('$.init')),
analysis.runes || !analysis.needs_context ? b.empty : b.stmt(b.call('$.init')),
.../** @type {import('estree').Statement[]} */ (template.body)
]);

Expand Down Expand Up @@ -392,11 +391,22 @@ export function client_component(source, analysis, options) {
: () => {};

append_styles();
component_block.body.push(
component_returned_object.length > 0
? b.return(b.call('$.pop', b.object(component_returned_object)))
: b.stmt(b.call('$.pop'))
);

const should_inject_context =
analysis.needs_context ||
analysis.reactive_statements.size > 0 ||
component_returned_object.length > 0 ||
options.dev;

if (should_inject_context) {
component_block.body.unshift(b.stmt(b.call('$.push', ...push_args)));

component_block.body.push(
component_returned_object.length > 0
? b.return(b.call('$.pop', b.object(component_returned_object)))
: b.stmt(b.call('$.pop'))
);
}

if (analysis.uses_rest_props) {
const named_props = analysis.exports.map(({ name, alias }) => alias ?? name);
Expand Down Expand Up @@ -430,11 +440,19 @@ export function client_component(source, analysis, options) {
component_block.body.unshift(b.const('$$slots', b.call('$.sanitize_slots', b.id('$$props'))));
}

let should_inject_props =
should_inject_context ||
analysis.needs_props ||
analysis.uses_props ||
analysis.uses_rest_props ||
analysis.uses_slots ||
analysis.slot_names.size > 0;

const body = [...state.hoisted, ...module.body];

const component = b.function_declaration(
b.id(analysis.name),
[b.id('$$anchor'), b.id('$$props')],
should_inject_props ? [b.id('$$anchor'), b.id('$$props')] : [b.id('$$anchor')],
component_block
);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1228,6 +1228,8 @@ function serialize_event_handler(node, { state, visit }) {

return handler;
} else {
state.analysis.needs_props = true;

// Function + .call to preserve "this" context as much as possible
return b.function(
null,
Expand Down
2 changes: 2 additions & 0 deletions packages/svelte/src/compiler/phases/types.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,8 @@ export interface ComponentAnalysis extends Analysis {
uses_slots: boolean;
uses_component_bindings: boolean;
uses_render_tags: boolean;
needs_context: boolean;
needs_props: boolean;
custom_element: boolean | SvelteOptions['customElement'];
/** If `true`, should append styles through JavaScript */
inject_styles: boolean;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,7 @@ import TextInput from './Child.svelte';
var root_1 = $.template(`Something`, 1);
var root = $.template(`<!> `, 1);

export default function Bind_component_snippet($$anchor, $$props) {
$.push($$props, true);

export default function Bind_component_snippet($$anchor) {
let value = $.source('');
const _snippet = snippet;
var fragment_1 = root();
Expand All @@ -33,5 +31,4 @@ export default function Bind_component_snippet($$anchor, $$props) {

$.render_effect(() => $.set_text(text, ` value: ${$.stringify($.get(value))}`));
$.append($$anchor, fragment_1);
$.pop();
}
Original file line number Diff line number Diff line change
@@ -1,14 +1,10 @@
import "svelte/internal/disclose-version";
import * as $ from "svelte/internal/client";

export default function Bind_this($$anchor, $$props) {
$.push($$props, false);
$.init();

export default function Bind_this($$anchor) {
var fragment = $.comment();
var node = $.first_child(fragment);

$.bind_this(Foo(node, {}), ($$value) => foo = $$value, () => foo);
$.append($$anchor, fragment);
$.pop();
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,7 @@ import * as $ from "svelte/internal/client";

var root = $.template(`<div></div> <svg></svg> <custom-element></custom-element> <div></div> <svg></svg> <custom-element></custom-element>`, 3);

export default function Main($$anchor, $$props) {
$.push($$props, true);

export default function Main($$anchor) {
// needs to be a snapshot test because jsdom does auto-correct the attribute casing
let x = 'test';
let y = () => 'test';
Expand All @@ -32,5 +30,4 @@ export default function Main($$anchor, $$props) {
});

$.append($$anchor, fragment);
$.pop();
}
Original file line number Diff line number Diff line change
@@ -1,10 +1,7 @@
import "svelte/internal/disclose-version";
import * as $ from "svelte/internal/client";

export default function Each_string_template($$anchor, $$props) {
$.push($$props, false);
$.init();

export default function Each_string_template($$anchor) {
var fragment = $.comment();
var node = $.first_child(fragment);

Expand All @@ -16,5 +13,4 @@ export default function Each_string_template($$anchor, $$props) {
});

$.append($$anchor, fragment);
$.pop();
}
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
import "svelte/internal/disclose-version";
import * as $ from "svelte/internal/client";

export default function Function_prop_no_getter($$anchor, $$props) {
$.push($$props, true);

export default function Function_prop_no_getter($$anchor) {
let count = $.source(0);

function onmouseup() {
Expand All @@ -27,5 +25,4 @@ export default function Function_prop_no_getter($$anchor, $$props) {
});

$.append($$anchor, fragment);
$.pop();
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,8 @@ import * as $ from "svelte/internal/client";

var root = $.template(`<h1>hello world</h1>`);

export default function Hello_world($$anchor, $$props) {
$.push($$props, false);
$.init();

export default function Hello_world($$anchor) {
var h1 = root();

$.append($$anchor, h1);
$.pop();
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,10 @@ import * as $ from "svelte/internal/client";

var root = $.template(`<h1>hello world</h1>`);

function Hmr($$anchor, $$props) {
$.push($$props, false);
$.init();

function Hmr($$anchor) {
var h1 = root();

$.append($$anchor, h1);
$.pop();
}

if (import.meta.hot) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,7 @@ function reset(_, str, tpl) {

var root = $.template(`<input> <input> <button>reset</button>`, 1);

export default function State_proxy_literal($$anchor, $$props) {
$.push($$props, true);

export default function State_proxy_literal($$anchor) {
let str = $.source('');
let tpl = $.source(``);
var fragment = root();
Expand All @@ -30,7 +28,6 @@ export default function State_proxy_literal($$anchor, $$props) {
$.bind_value(input, () => $.get(str), ($$value) => $.set(str, $$value));
$.bind_value(input_1, () => $.get(tpl), ($$value) => $.set(tpl, $$value));
$.append($$anchor, fragment);
$.pop();
}

$.delegate(["click"]);
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,10 @@ import "svelte/internal/disclose-version";
import * as $ from "svelte/internal/client";

export default function Svelte_element($$anchor, $$props) {
$.push($$props, true);

let tag = $.prop($$props, "tag", 3, 'hr');
var fragment = $.comment();
var node = $.first_child(fragment);

$.element(node, tag, false);
$.append($$anchor, fragment);
$.pop();
}
Loading