All files / src/compiler/phases/3-transform/client/visitors ClassBody.js

95.87% Statements 209/218
93.84% Branches 61/65
100% Functions 2/2
95.77% Lines 204/213

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 2142x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 44x 3x 3x 3x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 110x 110x 60x 60x 60x 110x 60x 60x 60x 60x 60x 60x 60x 60x 54x 54x 54x 54x 54x 1x 54x 54x 54x 54x 54x 54x 54x 17x 17x 13x 54x 54x 54x 54x 54x 54x 12x 53x 42x 42x 54x 54x 60x 110x 41x 41x 41x 42x 42x 6x 6x 42x 42x 42x 42x 41x 41x 41x 41x 41x 41x 41x 41x 110x 110x 60x 60x 60x 110x 60x 60x 60x 60x 60x 60x 60x 54x 54x 54x 43x 43x 43x 43x 43x 43x 43x 27x 27x 27x 43x 16x 16x 13x 43x 54x 11x 11x 11x 54x 54x 12x 53x 42x 42x 42x 42x 42x 42x 42x 42x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 42x 42x 2x 2x 2x 2x 2x 2x 42x 42x                   42x 54x 54x 60x 56x 56x 56x 41x 44x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 41x 41x 41x 2x 2x 2x 2x 120x 120x 2x 120x 118x 118x 120x  
/** @import { ClassBody, Expression, Identifier, Literal, MethodDefinition, PrivateIdentifier, PropertyDefinition } from 'estree' */
/** @import {  } from '#compiler' */
/** @import { Context, StateField } from '../types' */
import { dev, is_ignored } from '../../../../state.js';
import * as b from '../../../../utils/builders.js';
import { regex_invalid_identifier_chars } from '../../../patterns.js';
import { get_rune } from '../../../scope.js';
import { build_proxy_reassignment, should_proxy } from '../utils.js';
 
/**
 * @param {ClassBody} node
 * @param {Context} context
 */
export function ClassBody(node, context) {
	if (!context.state.analysis.runes) {
		context.next();
		return;
	}
 
	/** @type {Map<string, StateField>} */
	const public_state = new Map();
 
	/** @type {Map<string, StateField>} */
	const private_state = new Map();
 
	/** @type {string[]} */
	const private_ids = [];
 
	for (const definition of node.body) {
		if (
			definition.type === 'PropertyDefinition' &&
			(definition.key.type === 'Identifier' ||
				definition.key.type === 'PrivateIdentifier' ||
				definition.key.type === 'Literal')
		) {
			const type = definition.key.type;
			const name = get_name(definition.key);
			if (!name) continue;
 
			const is_private = type === 'PrivateIdentifier';
			if (is_private) private_ids.push(name);
 
			if (definition.value?.type === 'CallExpression') {
				const rune = get_rune(definition.value, context.state.scope);
				if (
					rune === '$state' ||
					rune === '$state.raw' ||
					rune === '$derived' ||
					rune === '$derived.by'
				) {
					/** @type {StateField} */
					const field = {
						kind:
							rune === '$state'
								? 'state'
								: rune === '$state.raw'
									? 'raw_state'
									: rune === '$derived.by'
										? 'derived_by'
										: 'derived',
						// @ts-expect-error this is set in the next pass
						id: is_private ? definition.key : null
					};
 
					if (is_private) {
						private_state.set(name, field);
					} else {
						public_state.set(name, field);
					}
				}
			}
		}
	}
 
	// each `foo = $state()` needs a backing `#foo` field
	for (const [name, field] of public_state) {
		let deconflicted = name;
		while (private_ids.includes(deconflicted)) {
			deconflicted = '_' + deconflicted;
		}
 
		private_ids.push(deconflicted);
		field.id = b.private_id(deconflicted);
	}
 
	/** @type {Array<MethodDefinition | PropertyDefinition>} */
	const body = [];
 
	const child_state = { ...context.state, public_state, private_state };
 
	// Replace parts of the class body
	for (const definition of node.body) {
		if (
			definition.type === 'PropertyDefinition' &&
			(definition.key.type === 'Identifier' ||
				definition.key.type === 'PrivateIdentifier' ||
				definition.key.type === 'Literal')
		) {
			const name = get_name(definition.key);
			if (!name) continue;
 
			const is_private = definition.key.type === 'PrivateIdentifier';
			const field = (is_private ? private_state : public_state).get(name);
 
			if (definition.value?.type === 'CallExpression' && field !== undefined) {
				let value = null;
 
				if (definition.value.arguments.length > 0) {
					const init = /** @type {Expression} **/ (
						context.visit(definition.value.arguments[0], child_state)
					);
 
					value =
						field.kind === 'state'
							? b.call(
									'$.source',
									should_proxy(init, context.state.scope) ? b.call('$.proxy', init) : init
								)
							: field.kind === 'raw_state'
								? b.call('$.source', init)
								: field.kind === 'derived_by'
									? b.call('$.derived', init)
									: b.call('$.derived', b.thunk(init));
				} else {
					// if no arguments, we know it's state as `$derived()` is a compile error
					value = b.call('$.source');
				}
 
				if (is_private) {
					body.push(b.prop_def(field.id, value));
				} else {
					// #foo;
					const member = b.member(b.this, field.id);
					body.push(b.prop_def(field.id, value));
 
					// get foo() { return this.#foo; }
					body.push(b.method('get', definition.key, [], [b.return(b.call('$.get', member))]));
 
					if (field.kind === 'state') {
						// set foo(value) { this.#foo = value; }
						const value = b.id('value');
						body.push(
							b.method(
								'set',
								definition.key,
								[value],
								[b.stmt(b.call('$.set', member, build_proxy_reassignment(value, field.id)))]
							)
						);
					}
 
					if (field.kind === 'raw_state') {
						// set foo(value) { this.#foo = value; }
						const value = b.id('value');
						body.push(
							b.method('set', definition.key, [value], [b.stmt(b.call('$.set', member, value))])
						);
					}
 
					if (dev && (field.kind === 'derived' || field.kind === 'derived_by')) {
						body.push(
							b.method(
								'set',
								definition.key,
								[b.id('_')],
								[b.throw_error(`Cannot update a derived property ('${name}')`)]
							)
						);
					}
				}
				continue;
			}
		}
 
		body.push(/** @type {MethodDefinition} **/ (context.visit(definition, child_state)));
	}
 
	if (dev && public_state.size > 0) {
		// add an `[$.ADD_OWNER]` method so that a class with state fields can widen ownership
		body.push(
			b.method(
				'method',
				b.id('$.ADD_OWNER'),
				[b.id('owner')],
				Array.from(public_state.keys()).map((name) =>
					b.stmt(
						b.call(
							'$.add_owner',
							b.call('$.get', b.member(b.this, b.private_id(name))),
							b.id('owner'),
							b.literal(false),
							is_ignored(node, 'ownership_invalid_binding') && b.true
						)
					)
				),
				true
			)
		);
	}
 
	return { ...node, body };
}
 
/**
 * @param {Identifier | PrivateIdentifier | Literal} node
 */
function get_name(node) {
	if (node.type === 'Literal') {
		return node.value?.toString().replace(regex_invalid_identifier_chars, '_');
	} else {
		return node.name;
	}
}