All files / src/compiler/utils ast.js

91.5% Statements 506/553
85.61% Branches 125/146
95.83% Functions 23/24
91.47% Lines 504/551

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 5522x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 6281x 3843x 3843x 6281x 6281x 95x 95x 6186x 6186x 6186x 2x 2x 2x 2x 2x 2x 2x 25566x 25566x 25566x 24713x 25566x 25566x 2x 2x 2x 2x 2x 2x 2x 2x 2x 17444x 17444x 12356x 12356x 12356x 17444x 17444x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2234x 2234x 2234x 2234x 2x 2x 2x 2x 2x 2x 2x 5991x 5991x 2x 2x 2x 2x 2x 2x 2x 12751x 12751x 2x 2x 2x 2x 2x 2x 2x 2x 35084x 35084x 32538x 32538x 35084x 35084x 76x 76x 76x 76x 35084x 35084x 1417x 2493x 96x 2493x 2397x 2397x 2493x 1417x 1417x 35084x 35084x 495x 1300x 1300x 495x 495x 35084x 35084x 152x 152x 35084x 35084x 406x 406x 35084x 35084x 35084x 35084x 2x 2x 2x 2x 2x 2x 2x 28118x 28118x 2x 2x 2x 2x 2x 2x 2x 2x 164x 164x 164x 164x 164x 164x 164x 164x 164x 164x 216x 216x 176x 176x 216x 216x 10x 216x 206x 206x 164x 164x 2x 2x 2x 2x 2x     164x 164x       164x 164x 164x 164x 164x 2x 2x 2x 2x 2x 2x 2x 2x 79x 79x 79x 63x 63x 79x 79x 12x 20x 20x 20x     20x 12x 12x 79x 79x 4x 8x 8x 4x 4x 79x 79x 79x 79x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1477x 1477x 1477x 1477x 1477x 1477x 1477x 1477x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2301x 2301x 2301x 2301x 1621x 1621x 1621x 1621x 1621x 1621x 1621x 1621x 2301x 2301x 402x 649x 31x 31x 6x 6x 6x 6x 28x 22x 14x 22x 6x 8x 2x 2x 22x 28x 6x 6x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x 31x                 649x 618x 618x 618x 618x 618x 618x 618x 618x 618x 618x 618x 649x 402x 402x 2301x 2301x 99x 211x 211x 204x 16x 16x 16x 16x               16x 16x 16x 16x 16x 16x 16x 16x 16x 204x 188x 188x 188x 188x 188x 188x 188x 188x 188x 188x 204x 211x 211x 211x 2301x 2301x 179x 179x 55x 55x 20x 20x 179x 179x 179x 177x 177x 177x 177x 177x 177x 177x 179x 2x 2x 179x 179x 179x 2301x 2301x 2301x 2301x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 5162x 5162x 5162x     5162x 5162x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1020x 1020x 1020x 1020x 236x 1020x 784x 784x 236x 1009x             236x 1020x 7x 7x 229x 229x 229x 2x 2x 2x 2x 2x 2x 2x 765x 765x 2x 2x 2x 2x 2x 2x 2709x 2709x 41x 41x 2709x     2709x 167x 277x   277x   277x 277x 277x 167x 167x 2709x 2709x 2709x 2709x 42x 42x 2709x 2709x 152x 152x 149x 208x   208x 208x 208x 149x 152x 152x 2709x     2709x 2x 2x 2x   2x 2x 2709x     2709x 100x 100x 99x 99x 100x 100x 2709x 2709x 190x 304x   304x 304x 304x 304x 304x 304x 190x 190x 2709x     2709x 2709x 7x 7x 2709x     2709x 2709x 1x 1x 2709x     2709x 2007x 2709x 2709x  
/** @import { Attribute, Text, ExpressionTag, SvelteNode } from '#compiler' */
/** @import * as ESTree from 'estree' */
import { walk } from 'zimmerframe';
import * as b from '../utils/builders.js';
 
/**
 * Gets the left-most identifier of a member expression or identifier.
 * @param {ESTree.MemberExpression | ESTree.Identifier} expression
 * @returns {ESTree.Identifier | null}
 */
export function object(expression) {
	while (expression.type === 'MemberExpression') {
		expression = /** @type {ESTree.MemberExpression | ESTree.Identifier} */ (expression.object);
	}
 
	if (expression.type !== 'Identifier') {
		return null;
	}
 
	return expression;
}
 
/**
 * Returns true if the attribute contains a single static text node.
 * @param {Attribute} attribute
 * @returns {attribute is Attribute & { value: [Text] }}
 */
export function is_text_attribute(attribute) {
	return (
		Array.isArray(attribute.value) &&
		attribute.value.length === 1 &&
		attribute.value[0].type === 'Text'
	);
}
 
/**
 * Returns true if the attribute contains a single expression node.
 * In Svelte 5, this also includes a single expression node wrapped in an array.
 * TODO change that in a future version
 * @param {Attribute} attribute
 * @returns {attribute is Attribute & { value: [ExpressionTag] | ExpressionTag }}
 */
export function is_expression_attribute(attribute) {
	return (
		(attribute.value !== true && !Array.isArray(attribute.value)) ||
		(Array.isArray(attribute.value) &&
			attribute.value.length === 1 &&
			attribute.value[0].type === 'ExpressionTag')
	);
}
 
/**
 * Returns the single attribute expression node.
 * In Svelte 5, this also includes a single expression node wrapped in an array.
 * TODO change that in a future version
 * @param { Attribute & { value: [ExpressionTag] | ExpressionTag }} attribute
 * @returns {ESTree.Expression}
 */
export function get_attribute_expression(attribute) {
	return Array.isArray(attribute.value)
		? /** @type {ExpressionTag} */ (attribute.value[0]).expression
		: attribute.value.expression;
}
 
/**
 * Returns the expression chunks of an attribute value
 * @param {Attribute['value']} value
 * @returns {Array<Text | ExpressionTag>}
 */
export function get_attribute_chunks(value) {
	return Array.isArray(value) ? value : typeof value === 'boolean' ? [] : [value];
}
 
/**
 * Returns true if the attribute starts with `on` and contains a single expression node.
 * @param {Attribute} attribute
 * @returns {attribute is Attribute & { value: [ExpressionTag] | ExpressionTag }}
 */
export function is_event_attribute(attribute) {
	return is_expression_attribute(attribute) && attribute.name.startsWith('on');
}
 
/**
 * Extracts all identifiers and member expressions from a pattern.
 * @param {ESTree.Pattern} pattern
 * @param {Array<ESTree.Identifier | ESTree.MemberExpression>} [nodes]
 * @returns {Array<ESTree.Identifier | ESTree.MemberExpression>}
 */
export function unwrap_pattern(pattern, nodes = []) {
	switch (pattern.type) {
		case 'Identifier':
			nodes.push(pattern);
			break;
 
		case 'MemberExpression':
			// member expressions can be part of an assignment pattern, but not a binding pattern
			// see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#binding_and_assignment
			nodes.push(pattern);
			break;
 
		case 'ObjectPattern':
			for (const prop of pattern.properties) {
				if (prop.type === 'RestElement') {
					unwrap_pattern(prop.argument, nodes);
				} else {
					unwrap_pattern(prop.value, nodes);
				}
			}
 
			break;
 
		case 'ArrayPattern':
			for (const element of pattern.elements) {
				if (element) unwrap_pattern(element, nodes);
			}
 
			break;
 
		case 'RestElement':
			unwrap_pattern(pattern.argument, nodes);
			break;
 
		case 'AssignmentPattern':
			unwrap_pattern(pattern.left, nodes);
			break;
	}
 
	return nodes;
}
 
/**
 * Extracts all identifiers from a pattern.
 * @param {ESTree.Pattern} pattern
 * @returns {ESTree.Identifier[]}
 */
export function extract_identifiers(pattern) {
	return unwrap_pattern(pattern, []).filter((node) => node.type === 'Identifier');
}
 
/**
 * Extracts all identifiers and a stringified keypath from an expression.
 * TODO replace this with `expression.dependencies`
 * @param {ESTree.Expression} expr
 * @returns {[keypath: string, ids: ESTree.Identifier[]]}
 */
export function extract_all_identifiers_from_expression(expr) {
	/** @type {ESTree.Identifier[]} */
	let nodes = [];
	/** @type {string[]} */
	let keypath = [];
 
	walk(
		expr,
		{},
		{
			Identifier(node, { path }) {
				const parent = path.at(-1);
				if (parent?.type !== 'MemberExpression' || parent.property !== node || parent.computed) {
					nodes.push(node);
				}
 
				if (parent?.type === 'MemberExpression' && parent.computed && parent.property === node) {
					keypath.push(`[${node.name}]`);
				} else {
					keypath.push(node.name);
				}
			},
			Literal(node, { path }) {
				const value = typeof node.value === 'string' ? `"${node.value}"` : String(node.value);
				const parent = path.at(-1);
				if (parent?.type === 'MemberExpression' && parent.computed && parent.property === node) {
					keypath.push(`[${value}]`);
				} else {
					keypath.push(value);
				}
			},
			ThisExpression(_, { next }) {
				keypath.push('this');
				next();
			}
		}
	);
 
	return [keypath.join('.'), nodes];
}
 
/**
 * Extracts all leaf identifiers from a destructuring expression.
 * @param {ESTree.Identifier | ESTree.ObjectExpression | ESTree.ArrayExpression} node
 * @param {ESTree.Identifier[]} [nodes]
 * @returns
 */
export function extract_identifiers_from_destructuring(node, nodes = []) {
	// TODO This isn't complete, but it should be enough for our purposes
	switch (node.type) {
		case 'Identifier':
			nodes.push(node);
			break;
 
		case 'ObjectExpression':
			for (const prop of node.properties) {
				if (prop.type === 'Property') {
					extract_identifiers_from_destructuring(/** @type {any} */ (prop.value), nodes);
				} else {
					extract_identifiers_from_destructuring(/** @type {any} */ (prop.argument), nodes);
				}
			}
 
			break;
 
		case 'ArrayExpression':
			for (const element of node.elements) {
				if (element) extract_identifiers_from_destructuring(/** @type {any} */ (element), nodes);
			}
 
			break;
	}
 
	return nodes;
}
 
/**
 * Represents the path of a destructured assignment from either a declaration
 * or assignment expression. For example, given `const { foo: { bar: baz } } = quux`,
 * the path of `baz` is `foo.bar`
 * @typedef {Object} DestructuredAssignment
 * @property {ESTree.Identifier | ESTree.MemberExpression} node The node the destructuring path end in. Can be a member expression only for assignment expressions
 * @property {boolean} is_rest `true` if this is a `...rest` destructuring
 * @property {boolean} has_default_value `true` if this has a fallback value like `const { foo = 'bar } = ..`
 * @property {(expression: ESTree.Expression) => ESTree.Identifier | ESTree.MemberExpression | ESTree.CallExpression | ESTree.AwaitExpression} expression Returns an expression which walks the path starting at the given expression.
 * This will be a call expression if a rest element or default is involved — e.g. `const { foo: { bar: baz = 42 }, ...rest } = quux` — since we can't represent `baz` or `rest` purely as a path
 * Will be an await expression in case of an async default value (`const { foo = await bar } = ...`)
 * @property {(expression: ESTree.Expression) => ESTree.Identifier | ESTree.MemberExpression | ESTree.CallExpression | ESTree.AwaitExpression} update_expression Like `expression` but without default values.
 */
 
/**
 * Extracts all destructured assignments from a pattern.
 * @param {ESTree.Node} param
 * @returns {DestructuredAssignment[]}
 */
export function extract_paths(param) {
	return _extract_paths(
		[],
		param,
		(node) => /** @type {ESTree.Identifier | ESTree.MemberExpression} */ (node),
		(node) => /** @type {ESTree.Identifier | ESTree.MemberExpression} */ (node),
		false
	);
}
 
/**
 * @param {DestructuredAssignment[]} assignments
 * @param {ESTree.Node} param
 * @param {DestructuredAssignment['expression']} expression
 * @param {DestructuredAssignment['update_expression']} update_expression
 * @param {boolean} has_default_value
 * @returns {DestructuredAssignment[]}
 */
function _extract_paths(assignments = [], param, expression, update_expression, has_default_value) {
	switch (param.type) {
		case 'Identifier':
		case 'MemberExpression':
			assignments.push({
				node: param,
				is_rest: false,
				has_default_value,
				expression,
				update_expression
			});
			break;
 
		case 'ObjectPattern':
			for (const prop of param.properties) {
				if (prop.type === 'RestElement') {
					/** @type {DestructuredAssignment['expression']} */
					const rest_expression = (object) => {
						/** @type {ESTree.Expression[]} */
						const props = [];
 
						for (const p of param.properties) {
							if (p.type === 'Property' && p.key.type !== 'PrivateIdentifier') {
								if (p.key.type === 'Identifier' && !p.computed) {
									props.push(b.literal(p.key.name));
								} else if (p.key.type === 'Literal') {
									props.push(b.literal(String(p.key.value)));
								} else {
									props.push(b.call('String', p.key));
								}
							}
						}
 
						return b.call('$.exclude_from_object', expression(object), b.array(props));
					};
 
					if (prop.argument.type === 'Identifier') {
						assignments.push({
							node: prop.argument,
							is_rest: true,
							has_default_value,
							expression: rest_expression,
							update_expression: rest_expression
						});
					} else {
						_extract_paths(
							assignments,
							prop.argument,
							rest_expression,
							rest_expression,
							has_default_value
						);
					}
				} else {
					/** @type {DestructuredAssignment['expression']} */
					const object_expression = (object) =>
						b.member(expression(object), prop.key, prop.computed || prop.key.type !== 'Identifier');
					_extract_paths(
						assignments,
						prop.value,
						object_expression,
						object_expression,
						has_default_value
					);
				}
			}
 
			break;
 
		case 'ArrayPattern':
			for (let i = 0; i < param.elements.length; i += 1) {
				const element = param.elements[i];
				if (element) {
					if (element.type === 'RestElement') {
						/** @type {DestructuredAssignment['expression']} */
						const rest_expression = (object) =>
							b.call(b.member(expression(object), b.id('slice')), b.literal(i));
						if (element.argument.type === 'Identifier') {
							assignments.push({
								node: element.argument,
								is_rest: true,
								has_default_value,
								expression: rest_expression,
								update_expression: rest_expression
							});
						} else {
							_extract_paths(
								assignments,
								element.argument,
								rest_expression,
								rest_expression,
								has_default_value
							);
						}
					} else {
						/** @type {DestructuredAssignment['expression']} */
						const array_expression = (object) => b.member(expression(object), b.literal(i), true);
						_extract_paths(
							assignments,
							element,
							array_expression,
							array_expression,
							has_default_value
						);
					}
				}
			}
 
			break;
 
		case 'AssignmentPattern': {
			/** @type {DestructuredAssignment['expression']} */
			const fallback_expression = (object) =>
				is_expression_async(param.right)
					? b.await(
							b.call('$.value_or_fallback_async', expression(object), b.thunk(param.right, true))
						)
					: b.call('$.value_or_fallback', expression(object), b.thunk(param.right));
 
			if (param.left.type === 'Identifier') {
				assignments.push({
					node: param.left,
					is_rest: false,
					has_default_value: true,
					expression: fallback_expression,
					update_expression
				});
			} else {
				_extract_paths(assignments, param.left, fallback_expression, update_expression, true);
			}
 
			break;
		}
	}
 
	return assignments;
}
 
/**
 * Like `path.at(x)`, but skips over `TSNonNullExpression` and `TSAsExpression` nodes and eases assertions a bit
 * by removing the `| undefined` from the resulting type.
 *
 * @template {SvelteNode} T
 * @param {T[]} path
 * @param {number} at
 */
export function get_parent(path, at) {
	let node = path.at(at);
	// @ts-expect-error
	if (node.type === 'TSNonNullExpression' || node.type === 'TSAsExpression') {
		return /** @type {T} */ (path.at(at < 0 ? at - 1 : at + 1));
	}
	return /** @type {T} */ (node);
}
 
/**
 * Returns `true` if the expression is an identifier, a literal, a function expression,
 * or a logical expression that only contains simple expressions. Used to determine whether
 * something needs to be treated as though accessing it could have side-effects (i.e.
 * reading signals prematurely)
 * @param {ESTree.Expression} node
 * @returns {boolean}
 */
export function is_simple_expression(node) {
	if (
		node.type === 'Literal' ||
		node.type === 'Identifier' ||
		node.type === 'ArrowFunctionExpression' ||
		node.type === 'FunctionExpression'
	) {
		return true;
	}
 
	if (node.type === 'ConditionalExpression') {
		return (
			is_simple_expression(node.test) &&
			is_simple_expression(node.consequent) &&
			is_simple_expression(node.alternate)
		);
	}
 
	if (node.type === 'BinaryExpression' || node.type === 'LogicalExpression') {
		return is_simple_expression(node.left) && is_simple_expression(node.right);
	}
 
	return false;
}
 
/**
 * @template {ESTree.SimpleCallExpression | ESTree.MemberExpression} T
 * @param {ESTree.ChainExpression & { expression : T } | T} node
 * @returns {T}
 */
export function unwrap_optional(node) {
	return node.type === 'ChainExpression' ? node.expression : node;
}
 
/**
 * @param {ESTree.Expression | ESTree.Pattern} expression
 * @returns {boolean}
 */
export function is_expression_async(expression) {
	switch (expression.type) {
		case 'AwaitExpression': {
			return true;
		}
		case 'ArrayPattern': {
			return expression.elements.some((element) => element && is_expression_async(element));
		}
		case 'ArrayExpression': {
			return expression.elements.some((element) => {
				if (!element) {
					return false;
				} else if (element.type === 'SpreadElement') {
					return is_expression_async(element.argument);
				} else {
					return is_expression_async(element);
				}
			});
		}
		case 'AssignmentPattern':
		case 'AssignmentExpression':
		case 'BinaryExpression':
		case 'LogicalExpression': {
			return is_expression_async(expression.left) || is_expression_async(expression.right);
		}
		case 'CallExpression':
		case 'NewExpression': {
			return (
				(expression.callee.type !== 'Super' && is_expression_async(expression.callee)) ||
				expression.arguments.some((element) => {
					if (element.type === 'SpreadElement') {
						return is_expression_async(element.argument);
					} else {
						return is_expression_async(element);
					}
				})
			);
		}
		case 'ChainExpression': {
			return is_expression_async(expression.expression);
		}
		case 'ConditionalExpression': {
			return (
				is_expression_async(expression.test) ||
				is_expression_async(expression.alternate) ||
				is_expression_async(expression.consequent)
			);
		}
		case 'ImportExpression': {
			return is_expression_async(expression.source);
		}
		case 'MemberExpression': {
			return (
				(expression.object.type !== 'Super' && is_expression_async(expression.object)) ||
				(expression.property.type !== 'PrivateIdentifier' &&
					is_expression_async(expression.property))
			);
		}
		case 'ObjectPattern':
		case 'ObjectExpression': {
			return expression.properties.some((property) => {
				if (property.type === 'SpreadElement') {
					return is_expression_async(property.argument);
				} else if (property.type === 'Property') {
					return (
						(property.key.type !== 'PrivateIdentifier' && is_expression_async(property.key)) ||
						is_expression_async(property.value)
					);
				}
			});
		}
		case 'RestElement': {
			return is_expression_async(expression.argument);
		}
		case 'SequenceExpression':
		case 'TemplateLiteral': {
			return expression.expressions.some((subexpression) => is_expression_async(subexpression));
		}
		case 'TaggedTemplateExpression': {
			return is_expression_async(expression.tag) || is_expression_async(expression.quasi);
		}
		case 'UnaryExpression':
		case 'UpdateExpression': {
			return is_expression_async(expression.argument);
		}
		case 'YieldExpression': {
			return expression.argument ? is_expression_async(expression.argument) : false;
		}
		default:
			return false;
	}
}