Debian Codegraph @

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

raw ◀ ▶
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 // @ts-ignore
152 const name = scope.generateUidBasedOnNode(key.node);
•153 // @ts-ignore
154 const declarator = t.variableDeclarator(t.identifier(name), key.node);
155 impureComputedPropertyDeclarators.push(declarator);
•156 // @ts-ignore
157 key.replaceWith(t.identifier(name));
158 }
159 }
160 return impureComputedPropertyDeclarators;
161 }
162
163 function removeUnusedExcludedKeys(path: NodePath<t.ObjectPattern>): void {
164 const bindings = path.getOuterBindingIdentifierPaths();
165
166 Object.keys(bindings).forEach(bindingName => {
167 const bindingParentPath = bindings[bindingName].parentPath;
168 if (
169 path.scope.getBinding(bindingName).references >
170 (process.env.BABEL_8_BREAKING ? 0 : ZERO_REFS) ||
171 !bindingParentPath.isObjectProperty()
172 ) {
173 return;
174 }
175 bindingParentPath.remove();
176 });
177 }
178
179 //expects path to an object pattern
180 function createObjectRest(
181 path: NodePath<t.ObjectPattern>,
182 file: PluginPass,
183 objRef: t.Identifier | t.MemberExpression,
184 ): [t.VariableDeclarator[], t.LVal, t.CallExpression] {
185 const props = path.get("properties");
186 const last = props[props.length - 1];
187 t.assertRestElement(last.node);
188 const restElement = t.cloneNode(last.node);
189 last.remove();
190
191 const impureComputedPropertyDeclarators = replaceImpureComputedKeys(
192 path.get("properties") as NodePath<t.ObjectProperty>[],
193 path.scope,
194 );
195 const { keys, allLiteral, hasTemplateLiteral } = extractNormalizedKeys(
196 path.node,
197 );
198
199 if (keys.length === 0) {
200 return [
201 impureComputedPropertyDeclarators,
202 restElement.argument,
203 t.callExpression(getExtendsHelper(file), [
204 t.objectExpression([]),
205 t.sequenceExpression([
206 t.callExpression(file.addHelper("objectDestructuringEmpty"), [
207 t.cloneNode(objRef),
208 ]),
209 t.cloneNode(objRef),
210 ]),
211 ]),
212 ];
213 }
214
215 let keyExpression;
216 if (!allLiteral) {
217 // map to toPropertyKey to handle the possible non-string values
218 keyExpression = t.callExpression(
219 t.memberExpression(t.arrayExpression(keys), t.identifier("map")),
220 [file.addHelper("toPropertyKey")],
221 );
222 } else {
223 keyExpression = t.arrayExpression(keys);
224
225 if (!hasTemplateLiteral && !t.isProgram(path.scope.block)) {
226 // Hoist definition of excluded keys, so that it's not created each time.
227 const program = path.findParent(path => path.isProgram());
228 const id = path.scope.generateUidIdentifier("excluded");
229
230 program.scope.push({
231 id,
232 init: keyExpression,
233 kind: "const",
234 });
235
236 keyExpression = t.cloneNode(id);
237 }
238 }
239
240 return [
241 impureComputedPropertyDeclarators,
242 restElement.argument,
243 t.callExpression(
244 file.addHelper(
245 `objectWithoutProperties${objectRestNoSymbols ? "Loose" : ""}`,
246 ),
247 [t.cloneNode(objRef), keyExpression],
248 ),
249 ];
250 }
251
252 function replaceRestElement(
253 parentPath: NodePath<t.Function | t.CatchClause>,
254 paramPath: NodePath<
255 t.Function["params"][number] | t.AssignmentPattern["left"]
256 >,
257 container?: t.VariableDeclaration[],
258 ): void {
259 if (paramPath.isAssignmentPattern()) {
260 replaceRestElement(parentPath, paramPath.get("left"), container);
261 return;
262 }
263
264 if (paramPath.isArrayPattern() && hasRestElement(paramPath)) {
265 const elements = paramPath.get("elements");
266
267 for (let i = 0; i < elements.length; i++) {
268 replaceRestElement(parentPath, elements[i], container);
269 }
270 }
271
272 if (paramPath.isObjectPattern() && hasRestElement(paramPath)) {
273 const uid = parentPath.scope.generateUidIdentifier("ref");
274
275 const declar = t.variableDeclaration("let", [
276 t.variableDeclarator(paramPath.node, uid),
277 ]);
278
279 if (container) {
280 container.push(declar);
281 } else {
282 parentPath.ensureBlock();
283 parentPath.get("body").unshiftContainer("body", declar);
284 }
285 paramPath.replaceWith(t.cloneNode(uid));
286 }
287 }
288
289 return {
290 name: "proposal-object-rest-spread",
291 inherits: syntaxObjectRestSpread.default,
292
293 visitor: {
294 // function a({ b, ...c }) {}
295 Function(path) {
296 const params = path.get("params");
297 const paramsWithRestElement = new Set<number>();
298 const idsInRestParams = new Set();
299 for (let i = 0; i < params.length; ++i) {
300 const param = params[i];
301 if (hasRestElement(param)) {
302 paramsWithRestElement.add(i);
303 for (const name of Object.keys(param.getBindingIdentifiers())) {
304 idsInRestParams.add(name);
305 }
306 }
307 }
308
309 // if true, a parameter exists that has an id in its initializer
310 // that is also an id bound in a rest parameter
311 // example: f({...R}, a = R)
312 let idInRest = false;
313
314 const IdentifierHandler = function (
315 path: NodePath<t.Identifier>,
316 functionScope: Scope,
317 ) {
318 const name = path.node.name;
319 if (
320 path.scope.getBinding(name) === functionScope.getBinding(name) &&
321 idsInRestParams.has(name)
322 ) {
323 idInRest = true;
324 path.stop();
325 }
326 };
327
328 let i: number;
329 for (i = 0; i < params.length && !idInRest; ++i) {
330 const param = params[i];
331 if (!paramsWithRestElement.has(i)) {
•332 // @ts-ignore
333 if (param.isReferencedIdentifier() || param.isBindingIdentifier()) {
•334 // @ts-ignore
335 IdentifierHandler(param, path.scope);
336 } else {
•337 // @ts-ignore
338 param.traverse(
339 {
•340 // @ts-ignore
341 "Scope|TypeAnnotation|TSTypeAnnotation": path => path.skip(),
342 "ReferencedIdentifier|BindingIdentifier": IdentifierHandler,
343 },
344 path.scope,
345 );
346 }
347 }
348 }
349
350 if (!idInRest) {
351 for (let i = 0; i < params.length; ++i) {
352 const param = params[i];
353 if (paramsWithRestElement.has(i)) {
354 replaceRestElement(path, param);
355 }
356 }
357 } else {
358 const shouldTransformParam = (idx: number) =>
359 idx >= i - 1 || paramsWithRestElement.has(idx);
360 convertFunctionParams(
361 path,
362 ignoreFunctionLength,
363 shouldTransformParam,
364 replaceRestElement,
365 );
366 }
367 },
368
369 // adapted from transform-destructuring/src/index.js#pushObjectRest
370 // const { a, ...b } = c;
371 VariableDeclarator(path, file) {
372 if (!path.get("id").isObjectPattern()) {
373 return;
374 }
375
376 let insertionPath = path;
377 const originalPath = path;
378
379 visitRestElements(path.get("id"), path => {
380 if (!path.parentPath.isObjectPattern()) {
381 // Return early if the parent is not an ObjectPattern, but
382 // (for example) an ArrayPattern or Function, because that
383 // means this RestElement is an not an object property.
384 return;
385 }
386
387 if (
388 // skip single-property case, e.g.
389 // const { ...x } = foo();
390 // since the RHS will not be duplicated
391 shouldStoreRHSInTemporaryVariable(originalPath.node.id) &&
392 !t.isIdentifier(originalPath.node.init)
393 ) {
394 // const { a, ...b } = foo();
395 // to avoid calling foo() twice, as a first step convert it to:
396 // const _foo = foo(),
397 // { a, ...b } = _foo;
398 const initRef = path.scope.generateUidIdentifierBasedOnNode(
399 originalPath.node.init,
400 "ref",
401 );
402 // insert _foo = foo()
403 originalPath.insertBefore(
404 t.variableDeclarator(initRef, originalPath.node.init),
405 );
406 // replace foo() with _foo
407 originalPath.replaceWith(
408 t.variableDeclarator(originalPath.node.id, t.cloneNode(initRef)),
409 );
410
411 return;
412 }
413
414 let ref = originalPath.node.init;
415 const refPropertyPath: NodePath<t.ObjectProperty>[] = [];
416 let kind;
417
418 path.findParent((path: NodePath): boolean => {
419 if (path.isObjectProperty()) {
420 refPropertyPath.unshift(path);
421 } else if (path.isVariableDeclarator()) {
422 kind = path.parentPath.node.kind;
423 return true;
424 }
425 });
426
427 const impureObjRefComputedDeclarators = replaceImpureComputedKeys(
428 refPropertyPath,
429 path.scope,
430 );
431 refPropertyPath.forEach(prop => {
432 const { node } = prop;
433 ref = t.memberExpression(
434 ref,
435 t.cloneNode(node.key),
436 node.computed || t.isLiteral(node.key),
437 );
438 });
439
440 //@ts-expect-error: findParent can not apply assertions on result shape
441 const objectPatternPath: NodePath<t.ObjectPattern> = path.findParent(
442 path => path.isObjectPattern(),
443 );
444
445 const [impureComputedPropertyDeclarators, argument, callExpression] =
446 createObjectRest(
447 objectPatternPath,
448 file,
449 ref as t.MemberExpression,
450 );
451
452 if (pureGetters) {
453 removeUnusedExcludedKeys(objectPatternPath);
454 }
455
456 t.assertIdentifier(argument);
457
458 insertionPath.insertBefore(impureComputedPropertyDeclarators);
459
460 insertionPath.insertBefore(impureObjRefComputedDeclarators);
461
462 insertionPath = insertionPath.insertAfter(
463 t.variableDeclarator(argument, callExpression),
464 )[0] as NodePath<t.VariableDeclarator>;
465
466 path.scope.registerBinding(kind, insertionPath);
467
468 if (objectPatternPath.node.properties.length === 0) {
469 objectPatternPath
470 .findParent(
471 path => path.isObjectProperty() || path.isVariableDeclarator(),
472 )
473 .remove();
474 }
475 });
476 },
477
478 // taken from transform-destructuring/src/index.js#visitor
479 // export var { a, ...b } = c;
480 ExportNamedDeclaration(path) {
481 const declaration = path.get("declaration");
482 if (!declaration.isVariableDeclaration()) return;
483
484 const hasRest = declaration
485 .get("declarations")
486 .some(path => hasObjectPatternRestElement(path.get("id")));
487 if (!hasRest) return;
488
489 const specifiers = [];
490
491 for (const name of Object.keys(path.getOuterBindingIdentifiers(true))) {
492 specifiers.push(
493 t.exportSpecifier(t.identifier(name), t.identifier(name)),
494 );
495 }
496
497 // Split the declaration and export list into two declarations so that the variable
498 // declaration can be split up later without needing to worry about not being a
499 // top-level statement.
500 path.replaceWith(declaration.node);
501 path.insertAfter(t.exportNamedDeclaration(null, specifiers));
502 },
503
504 // try {} catch ({a, ...b}) {}
505 CatchClause(path) {
506 const paramPath = path.get("param");
507 replaceRestElement(path, paramPath);
508 },
509
510 // ({a, ...b} = c);
511 AssignmentExpression(path, file) {
512 const leftPath = path.get("left");
513 if (leftPath.isObjectPattern() && hasRestElement(leftPath)) {
514 const nodes = [];
515
516 const refName = path.scope.generateUidBasedOnNode(
517 path.node.right,
518 "ref",
519 );
520
521 nodes.push(
522 t.variableDeclaration("var", [
523 t.variableDeclarator(t.identifier(refName), path.node.right),
524 ]),
525 );
526
527 const [impureComputedPropertyDeclarators, argument, callExpression] =
528 createObjectRest(leftPath, file, t.identifier(refName));
529
530 if (impureComputedPropertyDeclarators.length > 0) {
531 nodes.push(
532 t.variableDeclaration("var", impureComputedPropertyDeclarators),
533 );
534 }
535
536 const nodeWithoutSpread = t.cloneNode(path.node);
537 nodeWithoutSpread.right = t.identifier(refName);
538 nodes.push(t.expressionStatement(nodeWithoutSpread));
539 nodes.push(
540 t.expressionStatement(
541 t.assignmentExpression("=", argument, callExpression),
542 ),
543 );
544 nodes.push(t.expressionStatement(t.identifier(refName)));
545
546 path.replaceWithMultiple(nodes);
547 }
548 },
549
550 // taken from transform-destructuring/src/index.js#visitor
551 ForXStatement(path: NodePath<t.ForXStatement>) {
552 const { node, scope } = path;
553 const leftPath = path.get("left");
554 const left = node.left;
555
556 if (!hasObjectPatternRestElement(leftPath)) {
557 return;
558 }
559
560 if (!t.isVariableDeclaration(left)) {
561 // for ({a, ...b} of []) {}
562 const temp = scope.generateUidIdentifier("ref");
563
564 node.left = t.variableDeclaration("var", [
565 t.variableDeclarator(temp),
566 ]);
567
568 path.ensureBlock();
569 const body = path.node.body;
570
571 if (body.body.length === 0 && path.isCompletionRecord()) {
572 body.body.unshift(
573 t.expressionStatement(scope.buildUndefinedNode()),
574 );
575 }
576
577 body.body.unshift(
578 t.expressionStatement(
579 t.assignmentExpression("=", left, t.cloneNode(temp)),
580 ),
581 );
582 } else {
583 // for (var {a, ...b} of []) {}
584 const pattern = left.declarations[0].id;
585
586 const key = scope.generateUidIdentifier("ref");
587 node.left = t.variableDeclaration(left.kind, [
588 t.variableDeclarator(key, null),
589 ]);
590
591 path.ensureBlock();
592 const body = node.body as t.BlockStatement;
593
594 body.body.unshift(
595 t.variableDeclaration(node.left.kind, [
596 t.variableDeclarator(pattern, t.cloneNode(key)),
597 ]),
598 );
599 }
600 },
601
602 // [{a, ...b}] = c;
603 ArrayPattern(path) {
604 const objectPatterns: t.VariableDeclarator[] = [];
605
606 visitRestElements(path, path => {
607 if (!path.parentPath.isObjectPattern()) {
608 // Return early if the parent is not an ObjectPattern, but
609 // (for example) an ArrayPattern or Function, because that
610 // means this RestElement is an not an object property.
611 return;
612 }
613
614 const objectPattern = path.parentPath;
615
616 const uid = path.scope.generateUidIdentifier("ref");
617 objectPatterns.push(t.variableDeclarator(objectPattern.node, uid));
618
619 objectPattern.replaceWith(t.cloneNode(uid));
620 path.skip();
621 });
622
623 if (objectPatterns.length > 0) {
624 const statementPath = path.getStatementParent();
625 const statementNode = statementPath.node;
626 const kind =
627 statementNode.type === "VariableDeclaration"
628 ? statementNode.kind
629 : "var";
630 statementPath.insertAfter(
631 t.variableDeclaration(kind, objectPatterns),
632 );
633 }
634 },
635
636 // var a = { ...b, ...c }
637 ObjectExpression(path, file) {
638 if (!hasSpread(path.node)) return;
639
640 let helper: t.Identifier | t.MemberExpression;
641 if (setSpreadProperties) {
642 helper = getExtendsHelper(file);
643 } else {
644 try {
645 helper = file.addHelper("objectSpread2");
646 } catch {
647 // TODO: This is needed to workaround https://github.com/babel/babel/issues/10187
648 // and https://github.com/babel/babel/issues/10179 for older @babel/core versions
649 // where #10187 isn't fixed.
650 this.file.declarations["objectSpread2"] = null;
651
652 // objectSpread2 has been introduced in v7.5.0
653 // We have to maintain backward compatibility.
654 helper = file.addHelper("objectSpread");
655 }
656 }
657
658 let exp: t.CallExpression = null;
659 let props: t.ObjectMember[] = [];
660
661 function make() {
662 const hadProps = props.length > 0;
663 const obj = t.objectExpression(props);
664 props = [];
665
666 if (!exp) {
667 exp = t.callExpression(helper, [obj]);
668 return;
669 }
670
671 // When we can assume that getters are pure and don't depend on
672 // the order of evaluation, we can avoid making multiple calls.
673 if (pureGetters) {
674 if (hadProps) {
675 exp.arguments.push(obj);
676 }
677 return;
678 }
679
680 exp = t.callExpression(t.cloneNode(helper), [
681 exp,
682 // If we have static props, we need to insert an empty object
683 // because the odd arguments are copied with [[Get]], not
684 // [[GetOwnProperty]]
685 ...(hadProps ? [t.objectExpression([]), obj] : []),
686 ]);
687 }
688
689 for (const prop of path.node.properties) {
690 if (t.isSpreadElement(prop)) {
691 make();
692 exp.arguments.push(prop.argument);
693 } else {
694 props.push(prop);
695 }
696 }
697
698 if (props.length) make();
699
700 path.replaceWith(exp);
701 },
702 },
703 };
704 });