Debian Codegraph @

packages/babel-plugin-proposal-destructuring-private/src/util.ts

raw
1 import type * as t from "@babel/types";
2 import type { Scope } from "@babel/traverse";
3 import { types } from "@babel/core";
4 import type { File } from "@babel/core";
5 import { buildObjectExcludingKeys } from "@babel/plugin-transform-destructuring";
6 const {
7 assignmentExpression,
8 binaryExpression,
9 conditionalExpression,
10 cloneNode,
11 isObjectProperty,
12 isPrivateName,
13 memberExpression,
14 numericLiteral,
15 objectPattern,
16 restElement,
17 variableDeclarator,
18 variableDeclaration,
19 unaryExpression,
20 } = types;
21
22 function buildUndefinedNode() {
23 return unaryExpression("void", numericLiteral(0));
24 }
25
26 function transformAssignmentPattern(
27 initializer: t.Expression,
28 tempId: t.Identifier,
29 ) {
30 return conditionalExpression(
31 binaryExpression("===", cloneNode(tempId), buildUndefinedNode()),
32 initializer,
33 cloneNode(tempId),
34 );
35 }
36
37 function initRestExcludingKeys(pattern: t.LVal): ExcludingKey[] | null {
38 if (pattern.type === "ObjectPattern") {
39 const { properties } = pattern;
40 if (properties[properties.length - 1].type === "RestElement") {
41 return [];
42 }
43 }
44 return null;
45 }
46
47 /**
48 * grow `excludingKeys` from given properties. This routine mutates properties by
49 * memoising the computed non-static keys.
50 *
51 * @param {ExcludingKey[]} excludingKeys
52 * @param {t.ObjectProperty[]} properties An array of object properties that should be excluded by rest element transform
53 * @param {Scope} scope Where should we register the memoised id
54 */
55 function growRestExcludingKeys(
56 excludingKeys: ExcludingKey[],
57 properties: t.ObjectProperty[],
58 scope: Scope,
59 ) {
60 if (excludingKeys === null) return;
61 for (const property of properties) {
62 const propertyKey = property.key;
63 if (property.computed && !scope.isStatic(propertyKey)) {
64 const tempId = scope.generateDeclaredUidIdentifier("m");
65 // @ts-expect-error A computed property key must not be a private name
66 property.key = assignmentExpression("=", tempId, propertyKey);
67 excludingKeys.push({ key: tempId, computed: true });
68 } else if (propertyKey.type !== "PrivateName") {
69 excludingKeys.push(property);
70 }
71 }
72 }
73
74 /**
75 * Prepare var declarations for params. Only param initializers
76 * will be transformed to undefined coalescing, other features are preserved.
77 * This function does NOT mutate given AST structures.
78 *
79 * @export
80 * @param {Function["params"]} params An array of function params
81 * @param {Scope} scope A scope used to generate uid for function params
82 * @returns {{ params: Identifier[]; variableDeclaration: VariableDeclaration }} An array of new id for params
83 * and variable declaration to be prepended to the function body
84 */
85 export function buildVariableDeclarationFromParams(
86 params: t.Function["params"],
87 scope: Scope,
88 ): {
89 params: (t.Identifier | t.RestElement)[];
90 variableDeclaration: t.VariableDeclaration;
91 } {
92 const { elements, transformed } = buildAssignmentsFromPatternList(
93 params,
94 scope,
95 /* isAssignment */ false,
96 );
97 return {
98 params: elements,
99 variableDeclaration: variableDeclaration(
100 "var",
101 transformed.map(({ left, right }) => variableDeclarator(left, right)),
102 ),
103 };
104 }
105
106 interface Transformed {
107 left: Exclude<LHS, t.AssignmentPattern>;
108 right: t.Expression;
109 }
110
111 function buildAssignmentsFromPatternList(
112 elements: (t.LVal | null)[],
113 scope: Scope,
114 isAssignment: boolean,
115 ): {
116 elements: (t.Identifier | t.RestElement | null)[];
117 transformed: Transformed[];
118 } {
119 const newElements: (t.Identifier | t.RestElement)[] = [],
120 transformed: Transformed[] = [];
121 for (let element of elements) {
122 if (element === null) {
123 newElements.push(null);
124 transformed.push(null);
125 continue;
126 }
127 const tempId = scope.generateUidIdentifier("p");
128 if (isAssignment) {
129 scope.push({ id: cloneNode(tempId) });
130 }
131 if (element.type === "RestElement") {
132 newElements.push(restElement(tempId));
133 // The argument of a RestElement within a BindingPattern must be either Identifier or BindingPattern
134 element = element.argument as t.Identifier | t.Pattern;
135 } else {
136 newElements.push(tempId);
137 }
138 if (element.type === "AssignmentPattern") {
139 transformed.push({
140 left: element.left,
141 right: transformAssignmentPattern(element.right, tempId),
142 });
143 } else {
144 transformed.push({
145 left: element as Transformed["left"],
146 right: cloneNode(tempId),
147 });
148 }
149 }
150 return { elements: newElements, transformed };
151 }
152
153 type StackItem = {
154 node: t.LVal | t.ObjectProperty | null;
155 index: number;
156 depth: number;
157 };
158
159 /**
160 * A DFS simplified pattern traverser. It skips computed property keys and assignment pattern
161 * initializers. The following nodes will be delegated to the visitor:
162 * - ArrayPattern
163 * - ArrayPattern elements
164 * - AssignmentPattern
165 * - ObjectPattern
166 * - ObjectProperty
167 * - RestElement
168 * @param root
169 * @param visitor
170 */
171 export function* traversePattern(
172 root: t.LVal,
173 visitor: (
174 node: t.LVal | t.ObjectProperty,
175 index: number,
176 depth: number,
177 ) => Generator<any, void, any>,
178 ) {
179 const stack: StackItem[] = [];
180 stack.push({ node: root, index: 0, depth: 0 });
181 let item: StackItem;
182 while ((item = stack.pop()) !== undefined) {
183 const { node, index } = item;
184 if (node === null) continue;
185 yield* visitor(node, index, item.depth);
186 const depth = item.depth + 1;
187 switch (node.type) {
188 case "AssignmentPattern":
189 stack.push({ node: node.left, index: 0, depth });
190 break;
191 case "ObjectProperty":
192 // inherit the depth and index as an object property can not be an LHS without object pattern
193 stack.push({ node: node.value as t.LVal, index, depth: item.depth });
194 break;
195 case "RestElement":
196 stack.push({ node: node.argument, index: 0, depth });
197 break;
198 case "ObjectPattern":
199 for (let list = node.properties, i = list.length - 1; i >= 0; i--) {
200 stack.push({ node: list[i], index: i, depth });
201 }
202 break;
203 case "ArrayPattern":
204 for (let list = node.elements, i = list.length - 1; i >= 0; i--) {
205 stack.push({ node: list[i], index: i, depth });
206 }
207 break;
208 case "TSParameterProperty":
209 case "TSAsExpression":
210 case "TSTypeAssertion":
211 case "TSNonNullExpression":
212 throw new Error(
213 `TypeScript features must first be transformed by ` +
214 `@babel/plugin-transform-typescript.\n` +
215 `If you have already enabled that plugin (or '@babel/preset-typescript'), make sure ` +
216 `that it runs before @babel/plugin-proposal-destructuring-private.`,
217 );
218 default:
219 break;
220 }
221 }
222 }
223
224 export function hasPrivateKeys(pattern: t.LVal) {
225 let result = false;
226 traversePattern(pattern, function* (node) {
227 if (isObjectProperty(node) && isPrivateName(node.key)) {
228 result = true;
229 // stop the traversal
230 yield;
231 }
232 }).next();
233 return result;
234 }
235
236 export function hasPrivateClassElement(node: t.ClassBody): boolean {
237 return node.body.some(element =>
238 isPrivateName(
239 // @ts-expect-error: for those class element without `key`, they must
240 // not be a private element
241 element.key,
242 ),
243 );
244 }
245
246 /**
247 * Traverse the given pattern and report the private key path.
248 * A private key path is analagous to an array of `key` from the pattern NodePath
249 * to the private key NodePath. See also test/util.skip-bundled.js for an example output
250 *
251 * @export
252 * @param {t.LVal} pattern
253 */
254 export function* privateKeyPathIterator(pattern: t.LVal) {
255 const indexPath: number[] = [];
256 yield* traversePattern(pattern, function* (node, index, depth) {
257 indexPath[depth] = index;
258 if (isObjectProperty(node) && isPrivateName(node.key)) {
259 // The indexPath[0, depth] contains the path from root pattern to the object property
260 // with private key. The indexPath may have more than depth + 1 elements because we
261 // don't shrink the indexPath when the traverser returns to parent nodes.
262 yield indexPath.slice(1, depth + 1);
263 }
264 });
265 }
266
267 type LHS = Exclude<t.LVal, t.RestElement | t.TSParameterProperty>;
268
269 type ExcludingKey = {
270 key: t.ObjectProperty["key"];
271 computed: t.ObjectProperty["computed"];
272 };
273 type Item = {
274 left: LHS;
275 right: t.Expression;
276 restExcludingKeys?: ExcludingKey[] | null;
277 };
278
279 function rightWillBeReferencedOnce(left: LHS) {
280 switch (left.type) {
281 // Skip memoising the right when left is an identifier or
282 // an array pattern
283 case "Identifier":
284 case "ArrayPattern":
285 return true;
286 case "ObjectPattern":
287 return left.properties.length === 1;
288 default:
289 return false;
290 }
291 }
292 /**
293 * Transform private destructuring. It returns a generator
294 * which yields a pair of transformed LHS and RHS, which can form VariableDeclaration or
295 * AssignmentExpression later.
296 *
297 * @export
298 * @param {LHS} left The root pattern
299 * @param {t.Expression} right The initializer or the RHS of pattern
300 * @param {Scope} scope The scope where memoized id should be registered
301 * @param {boolean} isAssignment Whether we are transforming from an AssignmengExpression of VariableDeclaration
302 * @returns {Generator<Transformed, void, void>}
303 */
304 export function* transformPrivateKeyDestructuring(
305 left: LHS,
306 right: t.Expression,
307 scope: Scope,
308 isAssignment: boolean,
309 shouldPreserveCompletion: boolean,
310 addHelper: File["addHelper"],
311 objectRestNoSymbols: boolean,
312 useBuiltIns: boolean,
313 ): Generator<Transformed, void, void> {
314 const stack: Item[] = [];
315 const rootRight = right;
316 // The stack holds patterns that we don't known whether they contain private key
317 stack.push({
318 left,
319 right,
320 restExcludingKeys: initRestExcludingKeys(left),
321 });
322 let item: Item;
323 while ((item = stack.pop()) !== undefined) {
324 const { restExcludingKeys } = item;
325 let { left, right } = item;
326 const searchPrivateKey = privateKeyPathIterator(left).next();
327 if (searchPrivateKey.done) {
328 if (restExcludingKeys?.length > 0) {
329 // optimize out the rest element because `objectWithoutProperties`
330 // returns a new object
331 // `{ ...z } = babelHelpers.objectWithoutProperties(m, ["x"])`
332 // to
333 // `z = babelHelpers.objectWithoutProperties(m, ["x"])`
334 const { properties } = left as t.ObjectPattern;
335 if (properties.length === 1) {
336 // The argument of an object rest element must be an Identifier
337 left = (properties[0] as t.RestElement).argument as t.Identifier;
338 }
339 yield {
340 left: left as t.ObjectPattern,
341 right: buildObjectExcludingKeys(
342 restExcludingKeys,
343 right,
344 scope,
345 addHelper,
346 objectRestNoSymbols,
347 useBuiltIns,
348 ),
349 };
350 } else {
351 yield {
352 left:
353 // An assignment pattern will not be pushed to the stack
354 left as Transformed["left"],
355 right,
356 };
357 }
358 } else {
359 // now we need to split according to the indexPath;
360 const indexPath = searchPrivateKey.value;
361 for (
362 let indexPathIndex = 0, index;
363 (indexPathIndex < indexPath.length &&
364 (index = indexPath[indexPathIndex]) !== undefined) ||
365 left.type === "AssignmentPattern";
366 indexPathIndex++
367 ) {
368 const isRightSafeToReuse =
369 // If we should preserve completion and the right is the rootRight, then the
370 // right is NOT safe to reuse because we will insert a new memoising statement
371 // in the AssignmentExpression visitor, which causes right to be referenced more
372 // than once
373 !(shouldPreserveCompletion && right === rootRight) &&
374 (rightWillBeReferencedOnce(left) || scope.isStatic(right));
375 if (!isRightSafeToReuse) {
376 const tempId = scope.generateUidIdentifier("m");
377 if (isAssignment) {
378 scope.push({ id: cloneNode(tempId) });
379 }
380 yield { left: tempId, right };
381 right = cloneNode(tempId);
382 }
383 // invariant: at this point right must be a static identifier;
384 switch (left.type) {
385 case "ObjectPattern": {
386 const { properties } = left;
387 if (index > 0) {
388 // properties[0, index) must not contain private keys
389 const propertiesSlice = properties.slice(0, index);
390 yield {
391 left: objectPattern(propertiesSlice),
392 right: cloneNode(right),
393 };
394 }
395 if (index < properties.length - 1) {
396 // for properties after `index`, push them to stack so we can process them later
397 // inherit the restExcludingKeys on the stack if we are at
398 // the first level, otherwise initialize a new restExcludingKeys
399 const nextRestExcludingKeys =
400 indexPathIndex === 0
401 ? restExcludingKeys
402 : initRestExcludingKeys(left);
403 growRestExcludingKeys(
404 nextRestExcludingKeys,
405 // @ts-expect-error properties[0, index] must not contain rest element
406 // because properties[index] contains a private key
407 properties.slice(0, index + 1),
408 scope,
409 );
410 stack.push({
411 left: objectPattern(properties.slice(index + 1)),
412 right: cloneNode(right),
413 restExcludingKeys: nextRestExcludingKeys,
414 });
415 }
416 // An object rest element must not contain a private key
417 const property = properties[index] as t.ObjectProperty;
418 // The value of ObjectProperty under ObjectPattern must be an LHS
419 left = property.value as LHS;
420 const { key } = property;
421 const computed =
422 property.computed ||
423 // `{ 0: x } = RHS` is transformed to a computed member expression `x = RHS[0]`
424 (key.type !== "Identifier" && key.type !== "PrivateName");
425 right = memberExpression(right, key, computed);
426 break;
427 }
428 case "AssignmentPattern": {
429 right = transformAssignmentPattern(
430 left.right,
431 right as t.Identifier,
432 );
433 left = left.left;
434 break;
435 }
436 case "ArrayPattern": {
437 // todo: the transform here assumes that any expression within
438 // the array pattern, when evluated, do not interfere with the iterable
439 // in RHS. Otherwise we have to pause the iterable and interleave
440 // the expressions.
441 // See also https://gist.github.com/nicolo-ribaudo/f8ac7916f89450f2ead77d99855b2098
442 // and ordering/array-pattern-side-effect-iterable test
443 const leftElements = left.elements;
444 const leftElementsAfterIndex = leftElements.splice(index);
445 const { elements, transformed } = buildAssignmentsFromPatternList(
446 leftElementsAfterIndex,
447 scope,
448 isAssignment,
449 );
450 leftElements.push(...elements);
451 yield { left, right: cloneNode(right) };
452 // for elements after `index`, push them to stack so we can process them later
453 for (let i = transformed.length - 1; i > 0; i--) {
454 // skipping array holes
455 if (transformed[i] !== null) {
456 stack.push(transformed[i]);
457 }
458 }
459 ({ left, right } = transformed[0]);
460 break;
461 }
462 default:
463 break;
464 }
465 }
466 stack.push({
467 left,
468 right,
469 restExcludingKeys: initRestExcludingKeys(left),
470 });
471 }
472 }
473 }