Debian Codegraph @

packages/babel-plugin-proposal-object-rest-spread/src/index.ts

raw ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 import { declare } from "@babel/helper-plugin-utils";
2 import syntaxObjectRestSpread from "@babel/plugin-syntax-object-rest-spread";
3 import { types as t } from "@babel/core";
4 import type { PluginPass } from "@babel/core";
5 import type { NodePath, Scope } from "@babel/traverse";
6 import { convertFunctionParams } from "@babel/plugin-transform-parameters";
7 import { isRequired } from "@babel/helper-compilation-targets";
8 import compatData from "@babel/compat-data/corejs2-built-ins";
9 import shouldStoreRHSInTemporaryVariable from "./shouldStoreRHSInTemporaryVariable";
10
11 const { isAssignmentPattern, isObjectProperty } = t;
12 // @babel/types <=7.3.3 counts FOO as referenced in var { x: FOO }.
13 // We need to detect this bug to know if "unused" means 0 or 1 references.
14 if (!process.env.BABEL_8_BREAKING) {
15 const node = t.identifier("a");
16 const property = t.objectProperty(t.identifier("key"), node);
17 const pattern = t.objectPattern([property]);
18
19 // eslint-disable-next-line no-var
20 var ZERO_REFS = t.isReferenced(node, property, pattern) ? 1 : 0;
21 }
22
23 type Param = NodePath<t.Function["params"][number]>;
24 export interface Options {
25 useBuiltIns?: boolean;
26 loose?: boolean;
27 }
28
29 export default declare((api, opts: Options) => {
30 api.assertVersion(7);
31
32 const targets = api.targets();
33 const supportsObjectAssign = !isRequired("es6.object.assign", targets, {
34 compatData,
35 });
36
37 const { useBuiltIns = supportsObjectAssign, loose = false } = opts;
38
39 if (typeof loose !== "boolean") {
40 throw new Error(".loose must be a boolean, or undefined");
41 }
42
43 const ignoreFunctionLength = api.assumption("ignoreFunctionLength") ?? loose;
44 const objectRestNoSymbols = api.assumption("objectRestNoSymbols") ?? loose;
45 const pureGetters = api.assumption("pureGetters") ?? loose;
46 const setSpreadProperties = api.assumption("setSpreadProperties") ?? loose;
47
48 function getExtendsHelper(
49 file: PluginPass,
50 ): t.MemberExpression | t.Identifier {
51 return useBuiltIns
52 ? t.memberExpression(t.identifier("Object"), t.identifier("assign"))
53 : file.addHelper("extends");
54 }
55
56 function hasRestElement(path: Param) {
57 let foundRestElement = false;
58 visitRestElements(path, restElement => {
59 foundRestElement = true;
60 restElement.stop();
61 });
62 return foundRestElement;
63 }
64
65 function hasObjectPatternRestElement(path: NodePath): boolean {
66 let foundRestElement = false;
67 visitRestElements(path, restElement => {
68 if (restElement.parentPath.isObjectPattern()) {
69 foundRestElement = true;
70 restElement.stop();
71 }
72 });
73 return foundRestElement;
74 }
75
76 function visitRestElements(
77 path: NodePath,
78 visitor: (path: NodePath<t.RestElement>) => any,
79 ) {
80 path.traverse({
81 Expression(path) {
82 const { parent, key } = path;
83 if (
84 (isAssignmentPattern(parent) && key === "right") ||
85 (isObjectProperty(parent) && parent.computed && key === "key")
86 ) {
87 path.skip();
88 }
89 },
90 RestElement: visitor,
91 });
92 }
93
94 function hasSpread(node: t.ObjectExpression): boolean {
95 for (const prop of node.properties) {
96 if (t.isSpreadElement(prop)) {
97 return true;
98 }
99 }
100 return false;
101 }
102
103 // returns an array of all keys of an object, and a status flag indicating if all extracted keys
104 // were converted to stringLiterals or not
105 // e.g. extracts {keys: ["a", "b", "3", ++x], allLiteral: false }
106 // from ast of {a: "foo", b, 3: "bar", [++x]: "baz"}
107 function extractNormalizedKeys(node: t.ObjectPattern) {
108 // RestElement has been removed in createObjectRest
109 const props = node.properties as t.ObjectProperty[];
110 const keys: t.Expression[] = [];
111 let allLiteral = true;
112 let hasTemplateLiteral = false;
113
114 for (const prop of props) {
115 if (t.isIdentifier(prop.key) && !prop.computed) {
116 // since a key {a: 3} is equivalent to {"a": 3}, use the latter
117 keys.push(t.stringLiteral(prop.key.name));
118 } else if (t.isTemplateLiteral(prop.key)) {
119 keys.push(t.cloneNode(prop.key));
120 hasTemplateLiteral = true;
121 } else if (t.isLiteral(prop.key)) {
122 keys.push(
123 t.stringLiteral(
124 String(
125 // @ts-expect-error prop.key can not be a NullLiteral
126 prop.key.value,
127 ),
128 ),
129 );
130 } else {
131 // @ts-expect-error private name has been handled by destructuring-private
132 keys.push(t.cloneNode(prop.key));
133 allLiteral = false;
134 }
135 }
136
137 return { keys, allLiteral, hasTemplateLiteral };
138 }
139
140 // replaces impure computed keys with new identifiers
141 // and returns variable declarators of these new identifiers
142 function replaceImpureComputedKeys(
143 properties: NodePath<t.ObjectProperty>[],
144 scope: Scope,
145 ) {
146 const impureComputedPropertyDeclarators: t.VariableDeclarator[] = [];
147 for (const propPath of properties) {
148 // PrivateName is handled in destructuring-private plugin
149 const key = propPath.get("key") as NodePath<t.Expression>;
150 if (propPath.node.computed && !key.isPure()) {
151 const name = scope.generateUidBasedOnNode(key.node);
152 const declarator = t.variableDeclarator(t.identifier(name), key.node);
153 impureComputedPropertyDeclarators.push(declarator);
154 key.replaceWith(t.identifier(name));
155 }
156 }
157 return impureComputedPropertyDeclarators;
158 }
159
160 function removeUnusedExcludedKeys(path: NodePath<t.ObjectPattern>): void {
161 const bindings = path.getOuterBindingIdentifierPaths();
162
163 Object.keys(bindings).forEach(bindingName => {
164 const bindingParentPath = bindings[bindingName].parentPath;
165 if (
166 path.scope.getBinding(bindingName).references >
167 (process.env.BABEL_8_BREAKING ? 0 : ZERO_REFS) ||
168 !bindingParentPath.isObjectProperty()
169 ) {
170 return;
171 }
172 bindingParentPath.remove();
173 });
174 }
175
176 //expects path to an object pattern
177 function createObjectRest(
178 path: NodePath<t.ObjectPattern>,
179 file: PluginPass,
180 objRef: t.Identifier | t.MemberExpression,
181 ): [t.VariableDeclarator[], t.LVal, t.CallExpression] {
182 const props = path.get("properties");
183 const last = props[props.length - 1];
184 t.assertRestElement(last.node);
185 const restElement = t.cloneNode(last.node);
186 last.remove();
187
188 const impureComputedPropertyDeclarators = replaceImpureComputedKeys(
189 path.get("properties") as NodePath<t.ObjectProperty>[],
190 path.scope,
191 );
192 const { keys, allLiteral, hasTemplateLiteral } = extractNormalizedKeys(
193 path.node,
194 );
195
196 if (keys.length === 0) {
197 return [
198 impureComputedPropertyDeclarators,
199 restElement.argument,
200 t.callExpression(getExtendsHelper(file), [
201 t.objectExpression([]),
202 t.sequenceExpression([
203 t.callExpression(file.addHelper("objectDestructuringEmpty"), [
204 t.cloneNode(objRef),
205 ]),
206 t.cloneNode(objRef),
207 ]),
208 ]),
209 ];
210 }
211
212 let keyExpression;
213 if (!allLiteral) {
214 // map to toPropertyKey to handle the possible non-string values
215 keyExpression = t.callExpression(
216 t.memberExpression(t.arrayExpression(keys), t.identifier("map")),
217 [file.addHelper("toPropertyKey")],
218 );
219 } else {
220 keyExpression = t.arrayExpression(keys);
221
222 if (!hasTemplateLiteral && !t.isProgram(path.scope.block)) {
223 // Hoist definition of excluded keys, so that it's not created each time.
224 const program = path.findParent(path => path.isProgram());
225 const id = path.scope.generateUidIdentifier("excluded");
226
227 program.scope.push({
228 id,
229 init: keyExpression,
230 kind: "const",
231 });
232
233 keyExpression = t.cloneNode(id);
234 }
235 }
236
237 return [
238 impureComputedPropertyDeclarators,
239 restElement.argument,
240 t.callExpression(
241 file.addHelper(
242 `objectWithoutProperties${objectRestNoSymbols ? "Loose" : ""}`,
243 ),
244 [t.cloneNode(objRef), keyExpression],
245 ),
246 ];
247 }
248
249 function replaceRestElement(
250 parentPath: NodePath<t.Function | t.CatchClause>,
251 paramPath: NodePath<
252 t.Function["params"][number] | t.AssignmentPattern["left"]
253 >,
254 container?: t.VariableDeclaration[],
255 ): void {
256 if (paramPath.isAssignmentPattern()) {
257 replaceRestElement(parentPath, paramPath.get("left"), container);
258 return;
259 }
260
261 if (paramPath.isArrayPattern() && hasRestElement(paramPath)) {
262 const elements = paramPath.get("elements");
263
264 for (let i = 0; i < elements.length; i++) {
265 replaceRestElement(parentPath, elements[i], container);
266 }
267 }
268
269 if (paramPath.isObjectPattern() && hasRestElement(paramPath)) {
270 const uid = parentPath.scope.generateUidIdentifier("ref");
271
272 const declar = t.variableDeclaration("let", [
273 t.variableDeclarator(paramPath.node, uid),
274 ]);
275
276 if (container) {
277 container.push(declar);
278 } else {
279 parentPath.ensureBlock();
280 parentPath.get("body").unshiftContainer("body", declar);
281 }
282 paramPath.replaceWith(t.cloneNode(uid));
283 }
284 }
285
286 return {
287 name: "proposal-object-rest-spread",
288 inherits: syntaxObjectRestSpread.default,
289
290 visitor: {
291 // function a({ b, ...c }) {}
292 Function(path) {
293 const params = path.get("params");
294 const paramsWithRestElement = new Set<number>();
295 const idsInRestParams = new Set();
296 for (let i = 0; i < params.length; ++i) {
297 const param = params[i];
298 if (hasRestElement(param)) {
299 paramsWithRestElement.add(i);
300 for (const name of Object.keys(param.getBindingIdentifiers())) {
301 idsInRestParams.add(name);
302 }
303 }
304 }
305
306 // if true, a parameter exists that has an id in its initializer
307 // that is also an id bound in a rest parameter
308 // example: f({...R}, a = R)
309 let idInRest = false;
310
311 const IdentifierHandler = function (
312 path: NodePath<t.Identifier>,
313 functionScope: Scope,
314 ) {
315 const name = path.node.name;
316 if (
317 path.scope.getBinding(name) === functionScope.getBinding(name) &&
318 idsInRestParams.has(name)
319 ) {
320 idInRest = true;
321 path.stop();
322 }
323 };
324
325 let i: number;
326 for (i = 0; i < params.length && !idInRest; ++i) {
327 const param = params[i];
328 if (!paramsWithRestElement.has(i)) {
329 if (param.isReferencedIdentifier() || param.isBindingIdentifier()) {
330 IdentifierHandler(param, path.scope);
331 } else {
332 param.traverse(
333 {
334 "Scope|TypeAnnotation|TSTypeAnnotation": path => path.skip(),
335 "ReferencedIdentifier|BindingIdentifier": IdentifierHandler,
336 },
337 path.scope,
338 );
339 }
340 }
341 }
342
343 if (!idInRest) {
344 for (let i = 0; i < params.length; ++i) {
345 const param = params[i];
346 if (paramsWithRestElement.has(i)) {
347 replaceRestElement(path, param);
348 }
349 }
350 } else {
351 const shouldTransformParam = (idx: number) =>
352 idx >= i - 1 || paramsWithRestElement.has(idx);
353 convertFunctionParams(
354 path,
355 ignoreFunctionLength,
356 shouldTransformParam,
357 replaceRestElement,
358 );
359 }
360 },
361
362 // adapted from transform-destructuring/src/index.js#pushObjectRest
363 // const { a, ...b } = c;
364 VariableDeclarator(path, file) {
365 if (!path.get("id").isObjectPattern()) {
366 return;
367 }
368
369 let insertionPath = path;
370 const originalPath = path;
371
372 visitRestElements(path.get("id"), path => {
373 if (!path.parentPath.isObjectPattern()) {
374 // Return early if the parent is not an ObjectPattern, but
375 // (for example) an ArrayPattern or Function, because that
376 // means this RestElement is an not an object property.
377 return;
378 }
379
380 if (
381 // skip single-property case, e.g.
382 // const { ...x } = foo();
383 // since the RHS will not be duplicated
384 shouldStoreRHSInTemporaryVariable(originalPath.node.id) &&
385 !t.isIdentifier(originalPath.node.init)
386 ) {
387 // const { a, ...b } = foo();
388 // to avoid calling foo() twice, as a first step convert it to:
389 // const _foo = foo(),
390 // { a, ...b } = _foo;
391 const initRef = path.scope.generateUidIdentifierBasedOnNode(
392 originalPath.node.init,
393 "ref",
394 );
395 // insert _foo = foo()
396 originalPath.insertBefore(
397 t.variableDeclarator(initRef, originalPath.node.init),
398 );
399 // replace foo() with _foo
400 originalPath.replaceWith(
401 t.variableDeclarator(originalPath.node.id, t.cloneNode(initRef)),
402 );
403
404 return;
405 }
406
407 let ref = originalPath.node.init;
408 const refPropertyPath: NodePath<t.ObjectProperty>[] = [];
409 let kind;
410
411 path.findParent((path: NodePath): boolean => {
412 if (path.isObjectProperty()) {
413 refPropertyPath.unshift(path);
414 } else if (path.isVariableDeclarator()) {
415 kind = path.parentPath.node.kind;
416 return true;
417 }
418 });
419
420 const impureObjRefComputedDeclarators = replaceImpureComputedKeys(
421 refPropertyPath,
422 path.scope,
423 );
424 refPropertyPath.forEach(prop => {
425 const { node } = prop;
426 ref = t.memberExpression(
427 ref,
428 t.cloneNode(node.key),
429 node.computed || t.isLiteral(node.key),
430 );
431 });
432
433 //@ts-expect-error: findParent can not apply assertions on result shape
434 const objectPatternPath: NodePath<t.ObjectPattern> = path.findParent(
435 path => path.isObjectPattern(),
436 );
437
438 const [impureComputedPropertyDeclarators, argument, callExpression] =
439 createObjectRest(
440 objectPatternPath,
441 file,
442 ref as t.MemberExpression,
443 );
444
445 if (pureGetters) {
446 removeUnusedExcludedKeys(objectPatternPath);
447 }
448
449 t.assertIdentifier(argument);
450
451 insertionPath.insertBefore(impureComputedPropertyDeclarators);
452
453 insertionPath.insertBefore(impureObjRefComputedDeclarators);
454
455 insertionPath = insertionPath.insertAfter(
456 t.variableDeclarator(argument, callExpression),
457 )[0] as NodePath<t.VariableDeclarator>;
458
459 path.scope.registerBinding(kind, insertionPath);
460
461 if (objectPatternPath.node.properties.length === 0) {
462 objectPatternPath
463 .findParent(
464 path => path.isObjectProperty() || path.isVariableDeclarator(),
465 )
466 .remove();
467 }
468 });
469 },
470
471 // taken from transform-destructuring/src/index.js#visitor
472 // export var { a, ...b } = c;
473 ExportNamedDeclaration(path) {
474 const declaration = path.get("declaration");
475 if (!declaration.isVariableDeclaration()) return;
476
477 const hasRest = declaration
478 .get("declarations")
479 .some(path => hasObjectPatternRestElement(path.get("id")));
480 if (!hasRest) return;
481
482 const specifiers = [];
483
484 for (const name of Object.keys(path.getOuterBindingIdentifiers(true))) {
485 specifiers.push(
486 t.exportSpecifier(t.identifier(name), t.identifier(name)),
487 );
488 }
489
490 // Split the declaration and export list into two declarations so that the variable
491 // declaration can be split up later without needing to worry about not being a
492 // top-level statement.
493 path.replaceWith(declaration.node);
494 path.insertAfter(t.exportNamedDeclaration(null, specifiers));
495 },
496
497 // try {} catch ({a, ...b}) {}
498 CatchClause(path) {
499 const paramPath = path.get("param");
500 replaceRestElement(path, paramPath);
501 },
502
503 // ({a, ...b} = c);
504 AssignmentExpression(path, file) {
505 const leftPath = path.get("left");
506 if (leftPath.isObjectPattern() && hasRestElement(leftPath)) {
507 const nodes = [];
508
509 const refName = path.scope.generateUidBasedOnNode(
510 path.node.right,
511 "ref",
512 );
513
514 nodes.push(
515 t.variableDeclaration("var", [
516 t.variableDeclarator(t.identifier(refName), path.node.right),
517 ]),
518 );
519
520 const [impureComputedPropertyDeclarators, argument, callExpression] =
521 createObjectRest(leftPath, file, t.identifier(refName));
522
523 if (impureComputedPropertyDeclarators.length > 0) {
524 nodes.push(
525 t.variableDeclaration("var", impureComputedPropertyDeclarators),
526 );
527 }
528
529 const nodeWithoutSpread = t.cloneNode(path.node);
530 nodeWithoutSpread.right = t.identifier(refName);
531 nodes.push(t.expressionStatement(nodeWithoutSpread));
532 nodes.push(
533 t.expressionStatement(
534 t.assignmentExpression("=", argument, callExpression),
535 ),
536 );
537 nodes.push(t.expressionStatement(t.identifier(refName)));
538
539 path.replaceWithMultiple(nodes);
540 }
541 },
542
543 // taken from transform-destructuring/src/index.js#visitor
544 ForXStatement(path: NodePath<t.ForXStatement>) {
545 const { node, scope } = path;
546 const leftPath = path.get("left");
547 const left = node.left;
548
549 if (!hasObjectPatternRestElement(leftPath)) {
550 return;
551 }
552
553 if (!t.isVariableDeclaration(left)) {
554 // for ({a, ...b} of []) {}
555 const temp = scope.generateUidIdentifier("ref");
556
557 node.left = t.variableDeclaration("var", [
558 t.variableDeclarator(temp),
559 ]);
560
561 path.ensureBlock();
562 const body = path.node.body;
563
564 if (body.body.length === 0 && path.isCompletionRecord()) {
565 body.body.unshift(
566 t.expressionStatement(scope.buildUndefinedNode()),
567 );
568 }
569
570 body.body.unshift(
571 t.expressionStatement(
572 t.assignmentExpression("=", left, t.cloneNode(temp)),
573 ),
574 );
575 } else {
576 // for (var {a, ...b} of []) {}
577 const pattern = left.declarations[0].id;
578
579 const key = scope.generateUidIdentifier("ref");
580 node.left = t.variableDeclaration(left.kind, [
581 t.variableDeclarator(key, null),
582 ]);
583
584 path.ensureBlock();
585 const body = node.body as t.BlockStatement;
586
587 body.body.unshift(
588 t.variableDeclaration(node.left.kind, [
589 t.variableDeclarator(pattern, t.cloneNode(key)),
590 ]),
591 );
592 }
593 },
594
595 // [{a, ...b}] = c;
596 ArrayPattern(path) {
597 const objectPatterns: t.VariableDeclarator[] = [];
598
599 visitRestElements(path, path => {
600 if (!path.parentPath.isObjectPattern()) {
601 // Return early if the parent is not an ObjectPattern, but
602 // (for example) an ArrayPattern or Function, because that
603 // means this RestElement is an not an object property.
604 return;
605 }
606
607 const objectPattern = path.parentPath;
608
609 const uid = path.scope.generateUidIdentifier("ref");
610 objectPatterns.push(t.variableDeclarator(objectPattern.node, uid));
611
612 objectPattern.replaceWith(t.cloneNode(uid));
613 path.skip();
614 });
615
616 if (objectPatterns.length > 0) {
617 const statementPath = path.getStatementParent();
618 const statementNode = statementPath.node;
619 const kind =
620 statementNode.type === "VariableDeclaration"
621 ? statementNode.kind
622 : "var";
623 statementPath.insertAfter(
624 t.variableDeclaration(kind, objectPatterns),
625 );
626 }
627 },
628
629 // var a = { ...b, ...c }
630 ObjectExpression(path, file) {
631 if (!hasSpread(path.node)) return;
632
633 let helper: t.Identifier | t.MemberExpression;
634 if (setSpreadProperties) {
635 helper = getExtendsHelper(file);
636 } else {
637 try {
638 helper = file.addHelper("objectSpread2");
639 } catch {
640 // TODO: This is needed to workaround https://github.com/babel/babel/issues/10187
641 // and https://github.com/babel/babel/issues/10179 for older @babel/core versions
642 // where #10187 isn't fixed.
643 this.file.declarations["objectSpread2"] = null;
644
645 // objectSpread2 has been introduced in v7.5.0
646 // We have to maintain backward compatibility.
647 helper = file.addHelper("objectSpread");
648 }
649 }
650
651 let exp: t.CallExpression = null;
652 let props: t.ObjectMember[] = [];
653
654 function make() {
655 const hadProps = props.length > 0;
656 const obj = t.objectExpression(props);
657 props = [];
658
659 if (!exp) {
660 exp = t.callExpression(helper, [obj]);
661 return;
662 }
663
664 // When we can assume that getters are pure and don't depend on
665 // the order of evaluation, we can avoid making multiple calls.
666 if (pureGetters) {
667 if (hadProps) {
668 exp.arguments.push(obj);
669 }
670 return;
671 }
672
673 exp = t.callExpression(t.cloneNode(helper), [
674 exp,
675 // If we have static props, we need to insert an empty object
676 // because the odd arguments are copied with [[Get]], not
677 // [[GetOwnProperty]]
678 ...(hadProps ? [t.objectExpression([]), obj] : []),
679 ]);
680 }
681
682 for (const prop of path.node.properties) {
683 if (t.isSpreadElement(prop)) {
684 make();
685 exp.arguments.push(prop.argument);
686 } else {
687 props.push(prop);
688 }
689 }
690
691 if (props.length) make();
692
693 path.replaceWith(exp);
694 },
695 },
696 };
697 });