Skip to content

breaking: add $bindable() rune to denote bindable props #10851

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 30 commits into from
Mar 22, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
30 commits
Select commit Hold shift + click to select a range
001a831
add $props.bindable()
dummdidumm Mar 14, 2024
e98c242
compile time mutation validation
dummdidumm Mar 14, 2024
7557c8f
fix
dummdidumm Mar 15, 2024
f05e1db
regenerate
dummdidumm Mar 15, 2024
376898f
runtime error when trying to bind: to non-bindable prop
dummdidumm Mar 15, 2024
0bcc55d
sigh
dummdidumm Mar 15, 2024
e17e5e7
Merge branch 'main' into props-bindable
dummdidumm Mar 18, 2024
695a309
remove compiler error due to potential of false positives
dummdidumm Mar 18, 2024
a472ccf
error on rest prop and duplicate props
dummdidumm Mar 18, 2024
efcc5ac
revert duplicate prop name validation (valid use cases exist)
dummdidumm Mar 18, 2024
4d92bfb
fix
dummdidumm Mar 18, 2024
b0a8aaf
more fixes
dummdidumm Mar 18, 2024
17b916c
fix another edge case
dummdidumm Mar 18, 2024
cc90ffa
woops
dummdidumm Mar 18, 2024
4f97639
regenerate
dummdidumm Mar 18, 2024
ed670eb
Merge branch 'main' into props-bindable
dummdidumm Mar 19, 2024
84e2dd3
make it a dev-time validation error that also deals with ...rest props
dummdidumm Mar 19, 2024
1d81838
allow rest props on $props.bindable() and add related dev time valida…
dummdidumm Mar 19, 2024
6f274ac
tweak
dummdidumm Mar 19, 2024
6f8a451
Merge branch 'main' into props-bindable
dummdidumm Mar 20, 2024
6d6e94c
breaking: add `$bindable()` rune to denote bindable props
dummdidumm Mar 20, 2024
017db61
code mirror
dummdidumm Mar 20, 2024
7992ef8
tweak docs
dummdidumm Mar 21, 2024
ef0bc44
Apply suggestions from code review
dummdidumm Mar 22, 2024
62c39ee
Merge branch 'main' into props-bindable-2
dummdidumm Mar 22, 2024
6ea89a3
args validation
dummdidumm Mar 22, 2024
adc3f7a
bindable location fix + test
dummdidumm Mar 22, 2024
8ad1b98
feat: include rest props object name in error message (#10868)
Rich-Harris Mar 22, 2024
34d9a59
doh
dummdidumm Mar 22, 2024
bf0a830
lint
dummdidumm Mar 22, 2024
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/errors.js
Original file line number Diff line number Diff line change
Expand Up @@ -182,6 +182,7 @@ const runes = {
`$props() assignment must not contain nested properties or computed keys`,
'invalid-props-location': () =>
`$props() can only be used at the top level of components as a variable declaration initializer`,
'invalid-bindable-location': () => `$bindable() can only be used inside a $props() declaration`,
/** @param {string} rune */
'invalid-state-location': (rune) =>
`${rune}(...) can only be used as a variable declaration initializer or a class field`,
Expand Down
28 changes: 22 additions & 6 deletions packages/svelte/src/compiler/phases/2-analyze/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -436,7 +436,7 @@ export function analyze_component(root, options) {
);
}
} else {
instance.scope.declare(b.id('$$props'), 'prop', 'synthetic');
instance.scope.declare(b.id('$$props'), 'bindable_prop', 'synthetic');
instance.scope.declare(b.id('$$restProps'), 'rest_prop', 'synthetic');

for (const { ast, scope, scopes } of [module, instance, template]) {
Expand Down Expand Up @@ -466,7 +466,10 @@ export function analyze_component(root, options) {
}

for (const [name, binding] of instance.scope.declarations) {
if (binding.kind === 'prop' && binding.node.name !== '$$props') {
if (
(binding.kind === 'prop' || binding.kind === 'bindable_prop') &&
binding.node.name !== '$$props'
) {
const references = binding.references.filter(
(r) => r.node !== binding.node && r.path.at(-1)?.type !== 'ExportSpecifier'
);
Expand Down Expand Up @@ -758,7 +761,7 @@ const legacy_scope_tweaker = {
(binding.kind === 'normal' &&
(binding.declaration_kind === 'let' || binding.declaration_kind === 'var'))
) {
binding.kind = 'prop';
binding.kind = 'bindable_prop';
if (specifier.exported.name !== specifier.local.name) {
binding.prop_alias = specifier.exported.name;
}
Expand Down Expand Up @@ -796,7 +799,7 @@ const legacy_scope_tweaker = {
for (const declarator of node.declaration.declarations) {
for (const id of extract_identifiers(declarator.id)) {
const binding = /** @type {import('#compiler').Binding} */ (state.scope.get(id.name));
binding.kind = 'prop';
binding.kind = 'bindable_prop';
}
}
}
Expand Down Expand Up @@ -885,11 +888,24 @@ const runes_scope_tweaker = {
property.key.type === 'Identifier'
? property.key.name
: /** @type {string} */ (/** @type {import('estree').Literal} */ (property.key).value);
const initial = property.value.type === 'AssignmentPattern' ? property.value.right : null;
let initial = property.value.type === 'AssignmentPattern' ? property.value.right : null;

const binding = /** @type {import('#compiler').Binding} */ (state.scope.get(name));
binding.prop_alias = alias;
binding.initial = initial; // rewire initial from $props() to the actual initial value

// rewire initial from $props() to the actual initial value, stripping $bindable() if necessary
if (
initial?.type === 'CallExpression' &&
initial.callee.type === 'Identifier' &&
initial.callee.name === '$bindable'
) {
binding.initial = /** @type {import('estree').Expression | null} */ (
initial.arguments[0] ?? null
);
binding.kind = 'bindable_prop';
} else {
binding.initial = initial;
}
}
}
},
Expand Down
33 changes: 28 additions & 5 deletions packages/svelte/src/compiler/phases/2-analyze/validation.js
Original file line number Diff line number Diff line change
Expand Up @@ -299,17 +299,19 @@ const validation = {
error(node, 'invalid-binding-expression');
}

const binding = context.state.scope.get(left.name);

if (
assignee.type === 'Identifier' &&
node.name !== 'this' // bind:this also works for regular variables
) {
const binding = context.state.scope.get(left.name);
// reassignment
if (
!binding ||
(binding.kind !== 'state' &&
binding.kind !== 'frozen_state' &&
binding.kind !== 'prop' &&
binding.kind !== 'bindable_prop' &&
binding.kind !== 'each' &&
binding.kind !== 'store_sub' &&
!binding.mutated)
Expand All @@ -328,8 +330,6 @@ const validation = {
// TODO handle mutations of non-state/props in runes mode
}

const binding = context.state.scope.get(left.name);

if (node.name === 'group') {
if (!binding) {
error(node, 'INTERNAL', 'Cannot find declaration for bind:group');
Expand Down Expand Up @@ -780,7 +780,25 @@ function validate_call_expression(node, scope, path) {
error(node, 'invalid-props-location');
}

if (rune === '$state' || rune === '$derived' || rune === '$derived.by') {
if (rune === '$bindable') {
if (parent.type === 'AssignmentPattern' && path.at(-3)?.type === 'ObjectPattern') {
const declarator = path.at(-4);
if (
declarator?.type === 'VariableDeclarator' &&
get_rune(declarator.init, scope) === '$props'
) {
return;
}
}
error(node, 'invalid-bindable-location');
}

if (
rune === '$state' ||
rune === '$state.frozen' ||
rune === '$derived' ||
rune === '$derived.by'
) {
if (parent.type === 'VariableDeclarator') return;
if (parent.type === 'PropertyDefinition' && !parent.static && !parent.computed) return;
error(node, 'invalid-state-location', rune);
Expand Down Expand Up @@ -873,6 +891,8 @@ export const validation_runes_js = {
error(node, 'invalid-rune-args-length', rune, [0, 1]);
} else if (rune === '$props') {
error(node, 'invalid-props-location');
} else if (rune === '$bindable') {
error(node, 'invalid-bindable-location');
}
},
AssignmentExpression(node, { state }) {
Expand Down Expand Up @@ -1022,6 +1042,9 @@ export const validation_runes = merge(validation, a11y_validators, {
}
},
CallExpression(node, { state, path }) {
if (get_rune(node, state.scope) === '$bindable' && node.arguments.length > 1) {
error(node, 'invalid-rune-args-length', '$bindable', [0, 1]);
}
validate_call_expression(node, state.scope, path);
},
EachBlock(node, { next, state }) {
Expand Down Expand Up @@ -1062,7 +1085,7 @@ export const validation_runes = merge(validation, a11y_validators, {
state.has_props_rune = true;

if (args.length > 0) {
error(node, 'invalid-rune-args-length', '$props', [0]);
error(node, 'invalid-rune-args-length', rune, [0]);
}

if (node.id.type !== 'ObjectPattern') {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -239,7 +239,7 @@ export function client_component(source, analysis, options) {
);
});

const properties = analysis.exports.map(({ name, alias }) => {
const component_returned_object = analysis.exports.map(({ name, alias }) => {
const expression = serialize_get_binding(b.id(name), instance_state);

if (expression.type === 'Identifier' && !options.dev) {
Expand All @@ -249,10 +249,26 @@ export function client_component(source, analysis, options) {
return b.get(alias ?? name, [b.return(expression)]);
});

if (analysis.accessors) {
for (const [name, binding] of analysis.instance.scope.declarations) {
if (binding.kind !== 'prop' || name.startsWith('$$')) continue;
const properties = [...analysis.instance.scope.declarations].filter(
([name, binding]) =>
(binding.kind === 'prop' || binding.kind === 'bindable_prop') && !name.startsWith('$$')
);

if (analysis.runes && options.dev) {
/** @type {import('estree').Literal[]} */
const bindable = [];
for (const [name, binding] of properties) {
if (binding.kind === 'bindable_prop') {
bindable.push(b.literal(binding.prop_alias ?? name));
}
}
instance.body.unshift(
b.stmt(b.call('$.validate_prop_bindings', b.id('$$props'), b.array(bindable)))
);
}

if (analysis.accessors) {
for (const [name, binding] of properties) {
const key = binding.prop_alias ?? name;

const getter = b.get(key, [b.return(b.call(b.id(name)))]);
Expand All @@ -271,12 +287,12 @@ export function client_component(source, analysis, options) {
};
}

properties.push(getter, setter);
component_returned_object.push(getter, setter);
}
}

if (options.legacy.componentApi) {
properties.push(
component_returned_object.push(
b.init('$set', b.id('$.update_legacy_props')),
b.init(
'$on',
Expand All @@ -292,7 +308,7 @@ export function client_component(source, analysis, options) {
)
);
} else if (options.dev) {
properties.push(
component_returned_object.push(
b.init(
'$set',
b.thunk(
Expand Down Expand Up @@ -360,16 +376,16 @@ export function client_component(source, analysis, options) {

append_styles();
component_block.body.push(
properties.length > 0
? b.return(b.call('$.pop', b.object(properties)))
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) {
/** @type {string[]} */
const named_props = analysis.exports.map(({ name, alias }) => alias ?? name);
for (const [name, binding] of analysis.instance.scope.declarations) {
if (binding.kind === 'prop') named_props.push(binding.prop_alias ?? name);
if (binding.kind === 'bindable_prop') named_props.push(binding.prop_alias ?? name);
}

component_block.body.unshift(
Expand Down Expand Up @@ -476,9 +492,7 @@ export function client_component(source, analysis, options) {
/** @type {import('estree').Property[]} */
const props_str = [];

for (const [name, binding] of analysis.instance.scope.declarations) {
if (binding.kind !== 'prop' || name.startsWith('$$')) continue;

for (const [name, binding] of properties) {
const key = binding.prop_alias ?? name;
const prop_def = typeof ce === 'boolean' ? {} : ce.props?.[key] || {};
if (
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ export function serialize_get_binding(node, state) {
return typeof binding.expression === 'function' ? binding.expression(node) : binding.expression;
}

if (binding.kind === 'prop') {
if (binding.kind === 'prop' || binding.kind === 'bindable_prop') {
if (binding.node.name === '$$props') {
// Special case for $$props which only exists in the old world
// TODO this probably shouldn't have a 'prop' binding kind
Expand Down Expand Up @@ -377,6 +377,7 @@ export function serialize_set_binding(node, context, fallback, options) {
binding.kind !== 'state' &&
binding.kind !== 'frozen_state' &&
binding.kind !== 'prop' &&
binding.kind !== 'bindable_prop' &&
binding.kind !== 'each' &&
binding.kind !== 'legacy_reactive' &&
!is_store
Expand All @@ -389,7 +390,7 @@ export function serialize_set_binding(node, context, fallback, options) {

const serialize = () => {
if (left === node.left) {
if (binding.kind === 'prop') {
if (binding.kind === 'prop' || binding.kind === 'bindable_prop') {
return b.call(left, value);
} else if (is_store) {
return b.call('$.store_set', serialize_get_binding(b.id(left_name), state), value);
Expand Down Expand Up @@ -467,7 +468,7 @@ export function serialize_set_binding(node, context, fallback, options) {
b.call('$.untrack', b.id('$' + left_name))
);
} else if (!state.analysis.runes) {
if (binding.kind === 'prop') {
if (binding.kind === 'bindable_prop') {
return b.call(
left,
b.sequence([
Expand Down Expand Up @@ -571,7 +572,7 @@ function get_hoistable_params(node, context) {
params.push(b.id(binding.expression.object.arguments[0].name));
} else if (
// If we are referencing a simple $$props value, then we need to reference the object property instead
binding.kind === 'prop' &&
(binding.kind === 'prop' || binding.kind === 'bindable_prop') &&
!binding.reassigned &&
binding.initial === null &&
!context.state.analysis.accessors
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ export const global_visitors = {
binding?.kind === 'each' ||
binding?.kind === 'legacy_reactive' ||
binding?.kind === 'prop' ||
binding?.kind === 'bindable_prop' ||
is_store
) {
/** @type {import('estree').Expression[]} */
Expand All @@ -64,7 +65,7 @@ export const global_visitors = {
fn += '_store';
args.push(serialize_get_binding(b.id(name), state), b.call('$' + name));
} else {
if (binding.kind === 'prop') fn += '_prop';
if (binding.kind === 'prop' || binding.kind === 'bindable_prop') fn += '_prop';
args.push(b.id(name));
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ export const javascript_visitors_legacy = {
state.scope.get_bindings(declarator)
);
const has_state = bindings.some((binding) => binding.kind === 'state');
const has_props = bindings.some((binding) => binding.kind === 'prop');
const has_props = bindings.some((binding) => binding.kind === 'bindable_prop');

if (!has_state && !has_props) {
const init = declarator.init;
Expand Down Expand Up @@ -80,7 +80,7 @@ export const javascript_visitors_legacy = {
declarations.push(
b.declarator(
path.node,
binding.kind === 'prop'
binding.kind === 'bindable_prop'
? get_prop_source(binding, state, binding.prop_alias ?? name, value)
: value
)
Expand Down Expand Up @@ -168,7 +168,7 @@ export const javascript_visitors_legacy = {

// 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 === 'prop') {
if (name === '$$props' || name === '$$restProps' || binding.kind === 'bindable_prop') {
serialized = b.call('$.deep_read_state', serialized);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -207,33 +207,30 @@ export const javascript_visitors_runes = {

seen.push(name);

let id = property.value;
let initial = undefined;

if (property.value.type === 'AssignmentPattern') {
id = property.value.left;
initial = /** @type {import('estree').Expression} */ (visit(property.value.right));
}

let id =
property.value.type === 'AssignmentPattern' ? property.value.left : property.value;
assert.equal(id.type, 'Identifier');

const binding = /** @type {import('#compiler').Binding} */ (state.scope.get(id.name));
const initial =
binding.initial &&
/** @type {import('estree').Expression} */ (visit(binding.initial));

if (binding.reassigned || state.analysis.accessors || initial) {
declarations.push(b.declarator(id, get_prop_source(binding, state, name, initial)));
}
} else {
// RestElement
declarations.push(
b.declarator(
property.argument,
b.call(
'$.rest_props',
b.id('$$props'),
b.array(seen.map((name) => b.literal(name)))
)
)
);
/** @type {import('estree').Expression[]} */
const args = [b.id('$$props'), b.array(seen.map((name) => b.literal(name)))];

if (state.options.dev) {
// include rest name, so we can provide informative error messages
args.push(
b.literal(/** @type {import('estree').Identifier} */ (property.argument).name)
);
}

declarations.push(b.declarator(property.argument, b.call('$.rest_props', ...args)));
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1376,6 +1376,7 @@ function serialize_event_handler(node, { state, visit }) {
binding.kind === 'legacy_reactive' ||
binding.kind === 'derived' ||
binding.kind === 'prop' ||
binding.kind === 'bindable_prop' ||
binding.kind === 'store_sub')
) {
handler = dynamic_handler();
Expand Down
Loading