All files / src/compiler/phases scope.js

99.75% Statements 804/806
98.12% Branches 209/213
100% Functions 40/40
99.74% Lines 797/799

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 8002x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 50107x 50107x 50107x 50107x 50107x 50107x 50107x 50107x 50107x 50107x 50107x 50107x 50107x 50107x 50107x 50107x 50107x 50107x 50107x 50107x 50107x 50107x 50107x 50107x 50107x 50107x 50107x 50107x 50107x 50107x 50107x 50107x 50107x 50107x 50107x 50107x 50107x 50107x 50107x 50107x 50107x 50107x 50107x 50107x 50107x 50107x 50107x 50107x 50107x 50107x 50107x 50107x 50107x 50107x 50107x 50107x 50107x 50107x 50107x 50107x 50107x 50107x 25307x 2x 2x 25305x 25305x 25307x 25307x 25307x 25307x 6x 25307x 1x 1x 25304x 25307x 23326x 1x 1x 23325x 23326x 1802x 1802x 23326x 23501x 25307x 2x 2x 2x 23499x 23499x 23499x 23499x 23499x 23499x 23499x 23499x 23499x 23499x 23499x 23499x 23499x 23499x 23499x 23499x 23499x 23499x 23499x 23499x 23499x 23499x 50107x 50107x 34888x 34888x 50107x 50107x 50107x 50107x 50107x 50107x 16967x 2382x 2382x 14585x 14585x 14585x 14585x 14585x 14585x 16967x 16967x 16967x 14585x 16967x 12291x 12291x 14585x 14585x 14585x 14585x 14585x 50107x 50107x 50107x 50107x 50107x 50107x 530055x 530055x 50107x 50107x 50107x 50107x 50107x 50107x 5700x 5700x     5700x 5700x 50107x 50107x 50107x 50107x 50107x 50107x 1804x 1804x 50107x 50107x 50107x 50107x 50107x 50107x 99132x 99132x 99132x 99132x 99132x 99132x 99132x 99132x 99132x 33269x 99132x 62483x 65863x 3380x 3380x 3380x 3380x 99132x 50107x 2x 2x 5096x 5096x 5096x 5096x 5096x 5096x 5096x 5579x 5579x 5579x 5579x 5579x 4206x 4206x 5579x 5579x 5579x 5579x 5579x 5096x 2x 2x 2x 2x 2x 2x 2x 2x 15219x 15219x 15219x 15219x 15219x 15219x 15219x 15219x 15219x 15219x 15219x 15219x 15219x 15219x 15219x 15219x 15219x 15219x 15219x 15219x 15219x 15219x 15219x 15219x 15219x 15219x 15219x 15219x 15219x 15219x 3625x 1467x 1473x 1473x 1467x 3625x 15219x 15219x 15219x 15219x 15219x 2606x 2606x 2606x 2606x 15219x 15219x 15219x 15219x 15219x 15219x 9522x 9522x 9522x 15219x 15219x 15219x 15219x 15219x 15219x 15219x 10790x 10790x 10790x 10790x 8401x 218x 218x 218x 218x 218x 218x 218x 218x 218x 51x 63x 63x 63x 218x 167x 167x 167x 167x 167x 167x 167x 167x 167x 167x 8401x 207x 207x 8401x 10790x 10790x 10790x 15219x 15219x 15219x 15219x 15219x 421x 421x 421x 91x 91x 15219x 15219x 15219x 15219x 15219x 43625x 43625x 34952x 34952x 15219x 15219x 15219x 325x 325x 317x 317x 317x 317x 317x 317x 325x 244x 325x 205x 195x 190x 190x 195x 205x 317x 317x 15219x 15219x 15219x 15219x 15219x 15219x 15219x 15219x 1268x 1268x 1268x 1268x 1268x 1268x 1268x 1245x 1313x 1313x 1268x 23x 23x 23x 39x 39x 23x 1268x 1268x 1821x 1821x 508x 508x 508x 1821x 186x 186x 186x 1821x 1635x 116x 116x 116x 1634x 1519x 1519x 1635x 1635x 1635x 1821x 15219x 15219x 15219x 15219x 2260x 2260x 15219x 15219x 15219x 371x 371x 371x 371x 371x 371x 371x 15219x 15219x 15219x 1726x 1811x 1811x 15219x 15219x 15219x 308x 308x 308x 308x 308x 308x 308x 15219x 15219x 15219x 1061x 1061x 1061x 1061x 1061x 1061x 1061x 15219x 15219x 15219x 2256x 2256x 2256x 2256x 2256x 15219x 15219x 15219x 15219x 15219x 15219x 15219x 15219x 15219x 88x 88x 15219x 15219x 15219x 7114x 7114x 7796x 7796x 7796x 7796x 7796x 7796x 8294x 8294x 8294x 8294x 8294x 8294x 8294x 8294x 7792x 7110x 7110x 15219x 15219x 15219x 13x 11x 11x 11x 11x 11x 11x 11x 11x 13x 2x 2x 15219x 15219x 15219x 970x 970x 970x 970x 970x 970x 923x 923x 911x 911x 923x 970x 970x 970x 970x 970x 970x 970x 970x 1080x 1080x 1080x 1080x 1080x 1080x 2000x 15x 15x 1080x 1080x 56x 56x 56x 56x 56x 1080x 1080x 1080x 1080x 970x 87x 87x 970x 970x 970x 970x 113x 113x 113x 113x 113x 970x 970x 970x 970x 3370x 3370x 970x 968x 968x 968x 968x 968x 970x 1403x 81x 81x 1403x 968x 968x 968x 970x 970x 970x 970x 970x 970x 970x 970x 970x 15219x 15219x 15219x 179x 179x 179x 96x 96x 179x 179x 151x 151x 139x 139x 139x 139x 139x 191x 191x 191x 139x 151x 179x 179x 101x 101x 93x 93x 93x 93x 93x 149x 149x 149x 93x 101x 15219x 15219x 15219x 110x 110x 110x 110x 110x 84x 84x 110x 110x 110x 110x 110x 110x 70x 70x 70x 70x 110x 110x 15219x 15219x 15219x 16227x 16227x 16227x 15219x 15219x 15219x 964x 964x 964x 964x 964x 964x 964x 15219x 15219x 15219x 15219x 15219x 15219x 15219x 15219x 15219x 15219x 15219x 78x 15x 15x 78x 78x 15219x 15219x 15219x 15219x 15219x 190x 190x 146x 146x 146x 15214x 15214x 15214x 15219x 34945x 34945x 15214x 15219x 3595x 965x 965x 108x 108x 965x 965x 965x 3593x 2630x 2728x 2728x 2728x 2728x 2728x 2463x 2463x 2463x 2630x 2630x 3595x 15214x 15214x 15214x 15214x 15214x 15214x 2x 2x 2x 2x 2x 2x 2x 41773x 41773x 41773x 41773x 41773x 41773x 41773x 319939x 319939x 319939x 41773x 41773x 2x 2x 2x 2x 2x 2x 2x 2x 20503x 20503x 19764x 19764x 19764x 19764x 19764x 20503x 6073x 6073x 6013x 6013x 6013x 19704x 20503x 57x 57x 57x 19704x 20501x 19411x 19411x 19411x 20299x 10199x 10199x 16985x 10121x 10121x 10121x  
import is_reference from 'is-reference';
import { walk } from 'zimmerframe';
import { is_element_node } from './nodes.js';
import * as b from '../utils/builders.js';
import * as e from '../errors.js';
import {
	extract_identifiers,
	extract_identifiers_from_destructuring,
	object,
	unwrap_pattern
} from '../utils/ast.js';
import { JsKeywords, Runes } from './constants.js';
 
export class Scope {
	/** @type {ScopeRoot} */
	root;
 
	/**
	 * The immediate parent scope
	 * @type {Scope | null}
	 */
	parent;
 
	/**
	 * Whether or not `var` declarations are contained by this scope
	 * @type {boolean}
	 */
	#porous;
 
	/**
	 * A map of every identifier declared by this scope, and all the
	 * identifiers that reference it
	 * @type {Map<string, import('#compiler').Binding>}
	 */
	declarations = new Map();
 
	/**
	 * A map of declarators to the bindings they declare
	 * @type {Map<import('estree').VariableDeclarator | import('#compiler').LetDirective, import('#compiler').Binding[]>}
	 */
	declarators = new Map();
 
	/**
	 * A set of all the names referenced with this scope
	 * — useful for generating unique names
	 * @type {Map<string, { node: import('estree').Identifier; path: import('#compiler').SvelteNode[] }[]>}
	 */
	references = new Map();
 
	/**
	 * The scope depth allows us to determine if a state variable is referenced in its own scope,
	 * which is usually an error. Block statements do not increase this value
	 */
	function_depth = 0;
 
	/**
	 *
	 * @param {ScopeRoot} root
	 * @param {Scope | null} parent
	 * @param {boolean} porous
	 */
	constructor(root, parent, porous) {
		this.root = root;
		this.parent = parent;
		this.#porous = porous;
		this.function_depth = parent ? parent.function_depth + (porous ? 0 : 1) : 0;
	}
 
	/**
	 * @param {import('estree').Identifier} node
	 * @param {import('#compiler').Binding['kind']} kind
	 * @param {import('#compiler').DeclarationKind} declaration_kind
	 * @param {null | import('estree').Expression | import('estree').FunctionDeclaration | import('estree').ClassDeclaration | import('estree').ImportDeclaration | import('../types/template.js').EachBlock} initial
	 * @returns {import('#compiler').Binding}
	 */
	declare(node, kind, declaration_kind, initial = null) {
		if (node.name === '$') {
			e.dollar_binding_invalid(node);
		}
 
		if (
			node.name.startsWith('$') &&
			declaration_kind !== 'synthetic' &&
			declaration_kind !== 'param' &&
			declaration_kind !== 'rest_param' &&
			this.function_depth <= 1
		) {
			e.dollar_prefix_invalid(node);
		}
 
		if (this.parent) {
			if (declaration_kind === 'var' && this.#porous) {
				return this.parent.declare(node, kind, declaration_kind);
			}
 
			if (declaration_kind === 'import') {
				return this.parent.declare(node, kind, declaration_kind, initial);
			}
		}
 
		if (this.declarations.has(node.name)) {
			// This also errors on var/function types, but that's arguably a good thing
			e.declaration_duplicate(node, node.name);
		}
 
		/** @type {import('#compiler').Binding} */
		const binding = {
			node,
			references: [],
			legacy_dependencies: [],
			initial,
			mutated: false,
			scope: this,
			kind,
			declaration_kind,
			is_called: false,
			prop_alias: null,
			expression: null,
			mutation: null,
			reassigned: false,
			metadata: null
		};
		this.declarations.set(node.name, binding);
		this.root.conflicts.add(node.name);
		return binding;
	}
 
	child(porous = false) {
		return new Scope(this.root, this, porous);
	}
 
	/**
	 * @param {string} preferred_name
	 * @returns {string}
	 */
	generate(preferred_name) {
		if (this.#porous) {
			return /** @type {Scope} */ (this.parent).generate(preferred_name);
		}
 
		preferred_name = preferred_name.replace(/[^a-zA-Z0-9_$]/g, '_').replace(/^[0-9]/, '_');
		let name = preferred_name;
		let n = 1;
 
		while (
			this.references.has(name) ||
			this.declarations.has(name) ||
			this.root.conflicts.has(name) ||
			JsKeywords.includes(name)
		) {
			name = `${preferred_name}_${n++}`;
		}
 
		this.references.set(name, []);
		this.root.conflicts.add(name);
		return name;
	}
 
	/**
	 * @param {string} name
	 * @returns {import('#compiler').Binding | null}
	 */
	get(name) {
		return this.declarations.get(name) ?? this.parent?.get(name) ?? null;
	}
 
	/**
	 * @param {import('estree').VariableDeclarator | import('#compiler').LetDirective} node
	 * @returns {import('#compiler').Binding[]}
	 */
	get_bindings(node) {
		const bindings = this.declarators.get(node);
		if (!bindings) {
			throw new Error('No binding found for declarator');
		}
		return bindings;
	}
 
	/**
	 * @param {string} name
	 * @returns {Scope | null}
	 */
	owner(name) {
		return this.declarations.has(name) ? this : this.parent && this.parent.owner(name);
	}
 
	/**
	 * @param {import('estree').Identifier} node
	 * @param {import('#compiler').SvelteNode[]} path
	 */
	reference(node, path) {
		path = [...path]; // ensure that mutations to path afterwards don't affect this reference
		let references = this.references.get(node.name);
 
		if (!references) this.references.set(node.name, (references = []));
 
		references.push({ node, path });
 
		const binding = this.declarations.get(node.name);
		if (binding) {
			binding.references.push({ node, path });
		} else if (this.parent) {
			this.parent.reference(node, path);
		} else {
			// no binding was found, and this is the top level scope,
			// which means this is a global
			this.root.conflicts.add(node.name);
		}
	}
}
 
export class ScopeRoot {
	/** @type {Set<string>} */
	conflicts = new Set();
 
	/**
	 * @param {string} preferred_name
	 */
	unique(preferred_name) {
		preferred_name = preferred_name.replace(/[^a-zA-Z0-9_$]/g, '_');
		let final_name = preferred_name;
		let n = 1;
 
		while (this.conflicts.has(final_name)) {
			final_name = `${preferred_name}_${n++}`;
		}
 
		this.conflicts.add(final_name);
		const id = b.id(final_name);
		return id;
	}
}
 
/**
 * @param {import('#compiler').SvelteNode} ast
 * @param {ScopeRoot} root
 * @param {boolean} allow_reactive_declarations
 * @param {Scope | null} parent
 */
export function create_scopes(ast, root, allow_reactive_declarations, parent) {
	/** @typedef {{ scope: Scope }} State */
 
	/**
	 * A map of node->associated scope. A node appearing in this map does not necessarily mean that it created a scope
	 * @type {Map<import('#compiler').SvelteNode, Scope>}
	 */
	const scopes = new Map();
	const scope = new Scope(root, parent, false);
	scopes.set(ast, scope);
 
	/** @type {State} */
	const state = { scope };
 
	/** @type {[Scope, { node: import('estree').Identifier; path: import('#compiler').SvelteNode[] }][]} */
	const references = [];
 
	/** @type {[Scope, import('estree').Pattern | import('estree').MemberExpression][]} */
	const updates = [];
 
	/**
	 * An array of reactive declarations, i.e. the `a` in `$: a = b * 2`
	 * @type {import('estree').Identifier[]}
	 */
	const possible_implicit_declarations = [];
 
	/**
	 * @param {Scope} scope
	 * @param {import('estree').Pattern[]} params
	 */
	function add_params(scope, params) {
		for (const param of params) {
			for (const node of extract_identifiers(param)) {
				scope.declare(node, 'normal', param.type === 'RestElement' ? 'rest_param' : 'param');
			}
		}
	}
 
	/**
	 * @type {import('zimmerframe').Visitor<import('estree').Node, State, import('#compiler').SvelteNode>}
	 */
	const create_block_scope = (node, { state, next }) => {
		const scope = state.scope.child(true);
		scopes.set(node, scope);
 
		next({ scope });
	};
 
	/**
	 * @type {import('zimmerframe').Visitor<import('#compiler').ElementLike, State, import('#compiler').SvelteNode>}
	 */
	const SvelteFragment = (node, { state, next }) => {
		const [scope] = analyze_let_directives(node, state.scope);
		scopes.set(node, scope);
		next({ scope });
	};
 
	/**
	 * @param {import('#compiler').ElementLike} node
	 * @param {Scope} parent
	 */
	function analyze_let_directives(node, parent) {
		const scope = parent.child();
		let is_default_slot = true;
 
		for (const attribute of node.attributes) {
			if (attribute.type === 'LetDirective') {
				/** @type {import('#compiler').Binding[]} */
				const bindings = [];
				scope.declarators.set(attribute, bindings);
 
				// attach the scope to the directive itself, as well as the
				// contents to which it applies
				scopes.set(attribute, scope);
 
				if (attribute.expression) {
					for (const id of extract_identifiers_from_destructuring(attribute.expression)) {
						const binding = scope.declare(id, 'derived', 'const');
						bindings.push(binding);
					}
				} else {
					/** @type {import('estree').Identifier} */
					const id = {
						name: attribute.name,
						type: 'Identifier',
						start: attribute.start,
						end: attribute.end
					};
					const binding = scope.declare(id, 'derived', 'const');
					bindings.push(binding);
				}
			} else if (attribute.type === 'Attribute' && attribute.name === 'slot') {
				is_default_slot = false;
			}
		}
 
		return /** @type {const} */ ([scope, is_default_slot]);
	}
 
	/**
	 * @type {import('zimmerframe').Visitor<import('#compiler').AnimateDirective | import('#compiler').TransitionDirective | import('#compiler').UseDirective, State, import('#compiler').SvelteNode>}
	 */
	const SvelteDirective = (node, { state, path, visit }) => {
		state.scope.reference(b.id(node.name.split('.')[0]), path);
 
		if (node.expression) {
			visit(node.expression);
		}
	};
 
	walk(ast, state, {
		// references
		Identifier(node, { path, state }) {
			const parent = path.at(-1);
			if (parent && is_reference(node, /** @type {import('estree').Node} */ (parent))) {
				references.push([state.scope, { node, path: path.slice() }]);
			}
		},
 
		LabeledStatement(node, { path, next }) {
			if (path.length > 1 || !allow_reactive_declarations) return next();
			if (node.label.name !== '$') return next();
 
			// create a scope for the $: block
			const scope = state.scope.child();
			scopes.set(node, scope);
 
			if (
				node.body.type === 'ExpressionStatement' &&
				node.body.expression.type === 'AssignmentExpression'
			) {
				for (const id of extract_identifiers(node.body.expression.left)) {
					if (!id.name.startsWith('$')) {
						possible_implicit_declarations.push(id);
					}
				}
			}
 
			next({ scope });
		},
 
		SvelteFragment,
		SlotElement: SvelteFragment,
		SvelteElement: SvelteFragment,
		RegularElement: SvelteFragment,
 
		Component(node, { state, visit, path }) {
			state.scope.reference(b.id(node.name), path);
 
			// let:x is super weird:
			// - for the default slot, its scope only applies to children that are not slots themselves
			// - for named slots, its scope applies to the component itself, too
			const [scope, is_default_slot] = analyze_let_directives(node, state.scope);
			if (is_default_slot) {
				for (const attribute of node.attributes) {
					visit(attribute);
				}
			} else {
				scopes.set(node, scope);
 
				for (const attribute of node.attributes) {
					visit(attribute, { ...state, scope });
				}
			}
 
			for (const child of node.fragment.nodes) {
				if (
					is_element_node(child) &&
					child.attributes.some(
						(attribute) => attribute.type === 'Attribute' && attribute.name === 'slot'
					)
				) {
					// <div slot="..."> inherits the scope above the component unless the component is a named slot itself, because slots are hella weird
					scopes.set(child, is_default_slot ? state.scope : scope);
					visit(child, { scope: is_default_slot ? state.scope : scope });
				} else {
					if (child.type === 'ExpressionTag') {
						// expression tag is a special case — we don't visit it directly, but via process_children,
						// so we need to set the scope on the expression rather than the tag itself
						scopes.set(child.expression, scope);
					} else {
						scopes.set(child, scope);
					}
 
					visit(child, { scope });
				}
			}
		},
 
		// updates
		AssignmentExpression(node, { state, next }) {
			updates.push([state.scope, node.left]);
			next();
		},
 
		UpdateExpression(node, { state, next }) {
			updates.push([
				state.scope,
				/** @type {import('estree').Identifier | import('estree').MemberExpression} */ (
					node.argument
				)
			]);
			next();
		},
 
		ImportDeclaration(node, { state }) {
			for (const specifier of node.specifiers) {
				state.scope.declare(specifier.local, 'normal', 'import', node);
			}
		},
 
		FunctionExpression(node, { state, next }) {
			const scope = state.scope.child();
			scopes.set(node, scope);
 
			if (node.id) scope.declare(node.id, 'normal', 'function');
 
			add_params(scope, node.params);
			next({ scope });
		},
 
		FunctionDeclaration(node, { state, next }) {
			if (node.id) state.scope.declare(node.id, 'normal', 'function', node);
 
			const scope = state.scope.child();
			scopes.set(node, scope);
 
			add_params(scope, node.params);
			next({ scope });
		},
 
		ArrowFunctionExpression(node, { state, next }) {
			const scope = state.scope.child();
			scopes.set(node, scope);
 
			add_params(scope, node.params);
			next({ scope });
		},
 
		ForStatement: create_block_scope,
		ForInStatement: create_block_scope,
		ForOfStatement: create_block_scope,
		BlockStatement: create_block_scope,
		SwitchStatement: create_block_scope,
 
		ClassDeclaration(node, { state, next }) {
			if (node.id) state.scope.declare(node.id, 'normal', 'let', node);
			next();
		},
 
		VariableDeclaration(node, { state, path, next }) {
			const is_parent_const_tag = path.at(-1)?.type === 'ConstTag';
			for (const declarator of node.declarations) {
				/** @type {import('#compiler').Binding[]} */
				const bindings = [];
 
				state.scope.declarators.set(declarator, bindings);
 
				for (const id of extract_identifiers(declarator.id)) {
					const binding = state.scope.declare(
						id,
						is_parent_const_tag ? 'derived' : 'normal',
						node.kind,
						declarator.init
					);
					bindings.push(binding);
				}
			}
 
			next();
		},
 
		CatchClause(node, { state, next }) {
			if (node.param) {
				const scope = state.scope.child(true);
				scopes.set(node, scope);
 
				for (const id of extract_identifiers(node.param)) {
					scope.declare(id, 'normal', 'let');
				}
 
				next({ scope });
			} else {
				next();
			}
		},
 
		EachBlock(node, { state, visit }) {
			// Array part is still from the scope above
			/** @type {Set<import('estree').Identifier>} */
			const references_within = new Set();
			const idx = references.length;
			visit(node.expression);
			for (let i = idx; i < references.length; i++) {
				const [scope, { node: id }] = references[i];
				if (scope === state.scope) {
					references_within.add(id);
				}
			}
			scopes.set(node.expression, state.scope);
 
			// context and children are a new scope
			const scope = state.scope.child();
			scopes.set(node, scope);
 
			// declarations
			for (const id of extract_identifiers(node.context)) {
				const binding = scope.declare(id, 'each', 'const');
 
				let inside_rest = false;
				let is_rest_id = false;
				walk(node.context, null, {
					Identifier(node) {
						if (inside_rest && node === id) {
							is_rest_id = true;
						}
					},
					RestElement(_, { next }) {
						const prev = inside_rest;
						inside_rest = true;
						next();
						inside_rest = prev;
					}
				});
 
				binding.metadata = { inside_rest: is_rest_id };
			}
			if (node.context.type !== 'Identifier') {
				scope.declare(b.id('$$item'), 'derived', 'synthetic');
			}
			// Visit to pick up references from default initializers
			visit(node.context, { scope });
 
			if (node.index) {
				const is_keyed =
					node.key &&
					(node.key.type !== 'Identifier' || !node.index || node.key.name !== node.index);
				scope.declare(b.id(node.index), is_keyed ? 'derived' : 'normal', 'const', node);
			}
			if (node.key) visit(node.key, { scope });
 
			// children
			for (const child of node.body.nodes) {
				visit(child, { scope });
			}
			if (node.fallback) visit(node.fallback, { scope });
 
			// Check if inner scope shadows something from outer scope.
			// This is necessary because we need access to the array expression of the each block
			// in the inner scope if bindings are used, in order to invalidate the array.
			let needs_array_deduplication = false;
			for (const [name] of scope.declarations) {
				if (state.scope.get(name) !== null) {
					needs_array_deduplication = true;
				}
			}
 
			node.metadata = {
				contains_group_binding: false,
				array_name: needs_array_deduplication ? state.scope.root.unique('$$array') : null,
				index: scope.root.unique('$$index'),
				item: node.context.type === 'Identifier' ? node.context : b.id('$$item'),
				declarations: scope.declarations,
				references: [...references_within]
					.map((id) => /** @type {import('#compiler').Binding} */ (state.scope.get(id.name)))
					.filter(Boolean),
				is_controlled: false
			};
		},
 
		AwaitBlock(node, context) {
			context.visit(node.expression);
 
			if (node.pending) {
				context.visit(node.pending);
			}
 
			if (node.then) {
				context.visit(node.then);
				if (node.value) {
					const then_scope = /** @type {Scope} */ (scopes.get(node.then));
					const value_scope = context.state.scope.child();
					scopes.set(node.value, value_scope);
					context.visit(node.value, { scope: value_scope });
					for (const id of extract_identifiers(node.value)) {
						then_scope.declare(id, 'derived', 'const');
						value_scope.declare(id, 'normal', 'const');
					}
				}
			}
 
			if (node.catch) {
				context.visit(node.catch);
				if (node.error) {
					const catch_scope = /** @type {Scope} */ (scopes.get(node.catch));
					const error_scope = context.state.scope.child();
					scopes.set(node.error, error_scope);
					context.visit(node.error, { scope: error_scope });
					for (const id of extract_identifiers(node.error)) {
						catch_scope.declare(id, 'derived', 'const');
						error_scope.declare(id, 'normal', 'const');
					}
				}
			}
		},
 
		SnippetBlock(node, context) {
			const state = context.state;
			// Special-case for root-level snippets: they become part of the instance scope
			const is_top_level = !context.path.at(-2);
			let scope = state.scope;
			if (is_top_level) {
				scope = /** @type {Scope} */ (parent);
			}
			scope.declare(node.expression, 'normal', 'function', node.expression);
 
			const child_scope = state.scope.child();
			scopes.set(node, child_scope);
 
			for (const param of node.parameters) {
				for (const id of extract_identifiers(param)) {
					child_scope.declare(id, 'snippet', 'let');
				}
			}
 
			context.next({ scope: child_scope });
		},
 
		Fragment: (node, context) => {
			const scope = context.state.scope.child(node.transparent);
			scopes.set(node, scope);
			context.next({ scope });
		},
 
		BindDirective(node, context) {
			updates.push([
				context.state.scope,
				/** @type {import('estree').Identifier | import('estree').MemberExpression} */ (
					node.expression
				)
			]);
			context.next();
		},
 
		TransitionDirective: SvelteDirective,
		AnimateDirective: SvelteDirective,
		UseDirective: SvelteDirective,
		// using it's own function instead of `SvelteDirective` because
		// StyleDirective doesn't have expressions and are generally already
		// handled by `Identifier`. This is the special case for the shorthand
		// eg <button style:height /> where the variable has the same name of
		// the css property
		StyleDirective(node, { path, state, next }) {
			if (node.value === true) {
				state.scope.reference(b.id(node.name), path);
			}
			next();
		}
 
		// TODO others
	});
 
	for (const id of possible_implicit_declarations) {
		const binding = scope.get(id.name);
		if (binding) continue; // TODO can also be legacy_reactive if declared outside of reactive statement
 
		scope.declare(id, 'legacy_reactive', 'let');
	}
 
	// we do this after the fact, so that we don't need to worry
	// about encountering references before their declarations
	for (const [scope, { node, path }] of references) {
		scope.reference(node, path);
	}
 
	for (const [scope, node] of updates) {
		if (node.type === 'MemberExpression') {
			let object = node.object;
			while (object.type === 'MemberExpression') {
				object = object.object;
			}
 
			const binding = scope.get(/** @type {import('estree').Identifier} */ (object).name);
			if (binding) binding.mutated = true;
		} else {
			unwrap_pattern(node).forEach((node) => {
				let id = node.type === 'Identifier' ? node : object(node);
				if (id === null) return;
 
				const binding = scope.get(id.name);
				if (binding && id !== binding.node) {
					binding.mutated = true;
					binding.reassigned = node.type === 'Identifier';
				}
			});
		}
	}
 
	return {
		scope,
		scopes
	};
}
 
/**
 * @template {{ scope: Scope }} State
 * @param {Map<import('#compiler').SvelteNode, Scope>} scopes
 * @returns {import('zimmerframe').Visitors<import('#compiler').SvelteNode, State>}
 */
export function set_scope(scopes) {
	return {
		/**
		 *
		 * @param {import('#compiler').SvelteNode} node
		 * @param {import('zimmerframe').Context<import('#compiler').SvelteNode, State>} context
		 */
		_(node, { next, state }) {
			const scope = scopes.get(node);
			next(scope !== undefined && scope !== state.scope ? { ...state, scope } : state);
		}
	};
}
 
/**
 * Returns the name of the rune if the given expression is a `CallExpression` using a rune.
 * @param {import('estree').Node | import('../types/template.js').EachBlock | null | undefined} node
 * @param {Scope} scope
 * @returns {Runes[number] | null}
 */
export function get_rune(node, scope) {
	if (!node) return null;
	if (node.type !== 'CallExpression') return null;
 
	let n = node.callee;
 
	let joined = '';
 
	while (n.type === 'MemberExpression') {
		if (n.computed) return null;
		if (n.property.type !== 'Identifier') return null;
		joined = '.' + n.property.name + joined;
		n = n.object;
	}
 
	if (n.type === 'CallExpression' && n.callee.type === 'Identifier') {
		joined = '()' + joined;
		n = n.callee;
	}
 
	if (n.type !== 'Identifier') return null;
 
	joined = n.name + joined;
 
	if (!Runes.includes(/** @type {any} */ (joined))) return null;
 
	const binding = scope.get(n.name);
	if (binding !== null) return null; // rune name, but references a variable or store
 
	return /** @type {typeof Runes[number] | null} */ (joined);
}