Debian Codegraph @

packages/babel-helper-create-class-features-plugin/src/fields.ts

raw
1 import { template, traverse, types as t } from "@babel/core";
2 import type { File } from "@babel/core";
3 import type { NodePath, Visitor, Scope } from "@babel/traverse";
4 import ReplaceSupers from "@babel/helper-replace-supers";
5 import environmentVisitor from "@babel/helper-environment-visitor";
6 import memberExpressionToFunctions from "@babel/helper-member-expression-to-functions";
7 import type {
8 Handler,
9 HandlerState,
10 } from "@babel/helper-member-expression-to-functions";
11 import optimiseCall from "@babel/helper-optimise-call-expression";
12 import annotateAsPure from "@babel/helper-annotate-as-pure";
13 import { isTransparentExprWrapper } from "@babel/helper-skip-transparent-expression-wrappers";
14
15 import * as ts from "./typescript";
16
17 interface PrivateNameMetadata {
18 id: t.Identifier;
19 static: boolean;
20 method: boolean;
21 getId?: t.Identifier;
22 setId?: t.Identifier;
23 methodId?: t.Identifier;
24 initAdded?: boolean;
25 getterDeclared?: boolean;
26 setterDeclared?: boolean;
27 }
28
29 type PrivateNamesMap = Map<string, PrivateNameMetadata>;
30
31 export function buildPrivateNamesMap(props: PropPath[]) {
32 const privateNamesMap: PrivateNamesMap = new Map();
33 for (const prop of props) {
34 if (prop.isPrivate()) {
35 const { name } = prop.node.key.id;
36 const update: PrivateNameMetadata = privateNamesMap.has(name)
37 ? privateNamesMap.get(name)
38 : {
39 id: prop.scope.generateUidIdentifier(name),
40 static: prop.node.static,
41 method: !prop.isProperty(),
42 };
43 if (prop.isClassPrivateMethod()) {
44 if (prop.node.kind === "get") {
45 update.getId = prop.scope.generateUidIdentifier(`get_${name}`);
46 } else if (prop.node.kind === "set") {
47 update.setId = prop.scope.generateUidIdentifier(`set_${name}`);
48 } else if (prop.node.kind === "method") {
49 update.methodId = prop.scope.generateUidIdentifier(name);
50 }
51 }
52 privateNamesMap.set(name, update);
53 }
54 }
55 return privateNamesMap;
56 }
57
58 export function buildPrivateNamesNodes(
59 privateNamesMap: PrivateNamesMap,
60 privateFieldsAsProperties: boolean,
61 state: File,
62 ) {
63 const initNodes: t.Statement[] = [];
64
65 for (const [name, value] of privateNamesMap) {
66 // When the privateFieldsAsProperties assumption is enabled,
67 // both static and instance fields are transpiled using a
68 // secret non-enumerable property. Hence, we also need to generate that
69 // key (using the classPrivateFieldLooseKey helper).
70 // In spec mode, only instance fields need a "private name" initializer
71 // because static fields are directly assigned to a variable in the
72 // buildPrivateStaticFieldInitSpec function.
73 const { static: isStatic, method: isMethod, getId, setId } = value;
74 const isAccessor = getId || setId;
75 const id = t.cloneNode(value.id);
76
77 let init: t.Expression;
78
79 if (privateFieldsAsProperties) {
80 init = t.callExpression(state.addHelper("classPrivateFieldLooseKey"), [
81 t.stringLiteral(name),
82 ]);
83 } else if (!isStatic) {
84 init = t.newExpression(
85 t.identifier(!isMethod || isAccessor ? "WeakMap" : "WeakSet"),
86 [],
87 );
88 }
89
90 if (init) {
91 annotateAsPure(init);
92 initNodes.push(template.statement.ast`var ${id} = ${init}`);
93 }
94 }
95
96 return initNodes;
97 }
98
99 interface PrivateNameVisitorState {
100 privateNamesMap: PrivateNamesMap;
101 privateFieldsAsProperties: boolean;
102 redeclared?: string[];
103 }
104
105 // Traverses the class scope, handling private name references. If an inner
106 // class redeclares the same private name, it will hand off traversal to the
107 // restricted visitor (which doesn't traverse the inner class's inner scope).
108 function privateNameVisitorFactory<S>(
109 visitor: Visitor<PrivateNameVisitorState & S>,
110 ) {
111 // Traverses the outer portion of a class, without touching the class's inner
112 // scope, for private names.
113 const nestedVisitor = traverse.visitors.merge([
114 {
115 ...visitor,
116 },
117 environmentVisitor,
118 ]);
119
120 const privateNameVisitor: Visitor<PrivateNameVisitorState & S> = {
121 ...visitor,
122
123 Class(path) {
124 const { privateNamesMap } = this;
125 const body = path.get("body.body");
126
127 const visiblePrivateNames = new Map(privateNamesMap);
128 const redeclared = [];
129 for (const prop of body) {
130 if (!prop.isPrivate()) continue;
131 const { name } = prop.node.key.id;
132 visiblePrivateNames.delete(name);
133 redeclared.push(name);
134 }
135
136 // If the class doesn't redeclare any private fields, we can continue with
137 // our overall traversal.
138 if (!redeclared.length) {
139 return;
140 }
141
142 // This class redeclares some private field. We need to process the outer
143 // environment with access to all the outer privates, then we can process
144 // the inner environment with only the still-visible outer privates.
145 path.get("body").traverse(nestedVisitor, {
146 ...this,
147 redeclared,
148 });
149 path.traverse(privateNameVisitor, {
150 ...this,
151 privateNamesMap: visiblePrivateNames,
152 });
153
154 // We'll eventually hit this class node again with the overall Class
155 // Features visitor, which'll process the redeclared privates.
156 path.skipKey("body");
157 },
158 };
159
160 return privateNameVisitor;
161 }
162
163 interface PrivateNameState {
164 privateNamesMap: PrivateNamesMap;
165 classRef: t.Identifier;
166 file: File;
167 noDocumentAll: boolean;
168 innerBinding?: t.Identifier;
169 }
170
171 const privateNameVisitor = privateNameVisitorFactory<
172 HandlerState<PrivateNameState> & PrivateNameState
173 >({
174 PrivateName(path, { noDocumentAll }) {
175 const { privateNamesMap, redeclared } = this;
176 const { node, parentPath } = path;
177
178 if (
179 !parentPath.isMemberExpression({ property: node }) &&
180 !parentPath.isOptionalMemberExpression({ property: node })
181 ) {
182 return;
183 }
184 const { name } = node.id;
185 if (!privateNamesMap.has(name)) return;
186 if (redeclared && redeclared.includes(name)) return;
187
188 this.handle(parentPath, noDocumentAll);
189 },
190 });
191
192 // rename all bindings that shadows innerBinding
193 function unshadow(
194 name: string,
195 scope: Scope,
196 innerBinding: t.Identifier | undefined,
197 ) {
198 // in some cases, scope.getBinding(name) === undefined
199 // so we check hasBinding to avoid keeping looping
200 // see: https://github.com/babel/babel/pull/13656#discussion_r686030715
201 while (
202 scope?.hasBinding(name) &&
203 !scope.bindingIdentifierEquals(name, innerBinding)
204 ) {
205 scope.rename(name);
206 scope = scope.parent;
207 }
208 }
209
210 export function buildCheckInRHS(
211 rhs: t.Expression,
212 file: File,
213 inRHSIsObject?: boolean,
214 ) {
215 if (inRHSIsObject || !file.availableHelper?.("checkInRHS")) return rhs;
216 return t.callExpression(file.addHelper("checkInRHS"), [rhs]);
217 }
218
219 const privateInVisitor = privateNameVisitorFactory<{
220 classRef: t.Identifier;
221 file: File;
222 innerBinding?: t.Identifier;
223 }>({
224 BinaryExpression(path, { file }) {
225 const { operator, left, right } = path.node;
226 if (operator !== "in") return;
227 if (!t.isPrivateName(left)) return;
228
229 const { privateFieldsAsProperties, privateNamesMap, redeclared } = this;
230
231 const { name } = left.id;
232
233 if (!privateNamesMap.has(name)) return;
234 if (redeclared && redeclared.includes(name)) return;
235
236 // if there are any local variable shadowing classRef, unshadow it
237 // see #12960
238 unshadow(this.classRef.name, path.scope, this.innerBinding);
239
240 if (privateFieldsAsProperties) {
241 const { id } = privateNamesMap.get(name);
242 path.replaceWith(template.expression.ast`
243 Object.prototype.hasOwnProperty.call(${buildCheckInRHS(
244 right,
245 file,
246 )}, ${t.cloneNode(id)})
247 `);
248 return;
249 }
250
251 const { id, static: isStatic } = privateNamesMap.get(name);
252
253 if (isStatic) {
254 path.replaceWith(
255 template.expression.ast`${buildCheckInRHS(
256 right,
257 file,
258 )} === ${t.cloneNode(this.classRef)}`,
259 );
260 return;
261 }
262
263 path.replaceWith(
264 template.expression.ast`${t.cloneNode(id)}.has(${buildCheckInRHS(
265 right,
266 file,
267 )})`,
268 );
269 },
270 });
271
272 interface Receiver {
273 receiver(
274 this: HandlerState<PrivateNameState> & PrivateNameState,
275 member: NodePath<t.MemberExpression | t.OptionalMemberExpression>,
276 ): t.Expression;
277 }
278
279 const privateNameHandlerSpec: Handler<PrivateNameState & Receiver> & Receiver =
280 {
281 memoise(member, count) {
282 const { scope } = member;
283 const { object } = member.node as { object: t.Expression };
284
285 const memo = scope.maybeGenerateMemoised(object);
286 if (!memo) {
287 return;
288 }
289
290 this.memoiser.set(object, memo, count);
291 },
292
293 receiver(member) {
294 const { object } = member.node as { object: t.Expression };
295
296 if (this.memoiser.has(object)) {
297 return t.cloneNode(this.memoiser.get(object));
298 }
299
300 return t.cloneNode(object);
301 },
302
303 get(member) {
304 const { classRef, privateNamesMap, file, innerBinding } = this;
305 const { name } = (member.node.property as t.PrivateName).id;
306 const {
307 id,
308 static: isStatic,
309 method: isMethod,
310 methodId,
311 getId,
312 setId,
313 } = privateNamesMap.get(name);
314 const isAccessor = getId || setId;
315
316 if (isStatic) {
317 const helperName =
318 isMethod && !isAccessor
319 ? "classStaticPrivateMethodGet"
320 : "classStaticPrivateFieldSpecGet";
321
322 // if there are any local variable shadowing classRef, unshadow it
323 // see #12960
324 unshadow(classRef.name, member.scope, innerBinding);
325
326 return t.callExpression(file.addHelper(helperName), [
327 this.receiver(member),
328 t.cloneNode(classRef),
329 t.cloneNode(id),
330 ]);
331 }
332
333 if (isMethod) {
334 if (isAccessor) {
335 if (!getId && setId) {
336 if (file.availableHelper("writeOnlyError")) {
337 return t.sequenceExpression([
338 this.receiver(member),
339 t.callExpression(file.addHelper("writeOnlyError"), [
340 t.stringLiteral(`#${name}`),
341 ]),
342 ]);
343 }
344 console.warn(
345 `@babel/helpers is outdated, update it to silence this warning.`,
346 );
347 }
348 return t.callExpression(file.addHelper("classPrivateFieldGet"), [
349 this.receiver(member),
350 t.cloneNode(id),
351 ]);
352 }
353 return t.callExpression(file.addHelper("classPrivateMethodGet"), [
354 this.receiver(member),
355 t.cloneNode(id),
356 t.cloneNode(methodId),
357 ]);
358 }
359 return t.callExpression(file.addHelper("classPrivateFieldGet"), [
360 this.receiver(member),
361 t.cloneNode(id),
362 ]);
363 },
364
365 boundGet(member) {
366 this.memoise(member, 1);
367
368 return t.callExpression(
369 t.memberExpression(this.get(member), t.identifier("bind")),
370 [this.receiver(member)],
371 );
372 },
373
374 set(member, value) {
375 const { classRef, privateNamesMap, file } = this;
376 const { name } = (member.node.property as t.PrivateName).id;
377 const {
378 id,
379 static: isStatic,
380 method: isMethod,
381 setId,
382 getId,
383 } = privateNamesMap.get(name);
384 const isAccessor = getId || setId;
385
386 if (isStatic) {
387 const helperName =
388 isMethod && !isAccessor
389 ? "classStaticPrivateMethodSet"
390 : "classStaticPrivateFieldSpecSet";
391
392 return t.callExpression(file.addHelper(helperName), [
393 this.receiver(member),
394 t.cloneNode(classRef),
395 t.cloneNode(id),
396 value,
397 ]);
398 }
399 if (isMethod) {
400 if (setId) {
401 return t.callExpression(file.addHelper("classPrivateFieldSet"), [
402 this.receiver(member),
403 t.cloneNode(id),
404 value,
405 ]);
406 }
407 return t.sequenceExpression([
408 this.receiver(member),
409 value,
410 t.callExpression(file.addHelper("readOnlyError"), [
411 t.stringLiteral(`#${name}`),
412 ]),
413 ]);
414 }
415 return t.callExpression(file.addHelper("classPrivateFieldSet"), [
416 this.receiver(member),
417 t.cloneNode(id),
418 value,
419 ]);
420 },
421
422 destructureSet(member) {
423 const { classRef, privateNamesMap, file } = this;
424 const { name } = (member.node.property as t.PrivateName).id;
425 const { id, static: isStatic } = privateNamesMap.get(name);
426 if (isStatic) {
427 try {
428 // classStaticPrivateFieldDestructureSet was introduced in 7.13.10
429 // eslint-disable-next-line no-var
430 var helper = file.addHelper("classStaticPrivateFieldDestructureSet");
431 } catch {
432 throw new Error(
433 "Babel can not transpile `[C.#p] = [0]` with @babel/helpers < 7.13.10, \n" +
434 "please update @babel/helpers to the latest version.",
435 );
436 }
437 return t.memberExpression(
438 t.callExpression(helper, [
439 this.receiver(member),
440 t.cloneNode(classRef),
441 t.cloneNode(id),
442 ]),
443 t.identifier("value"),
444 );
445 }
446
447 return t.memberExpression(
448 t.callExpression(file.addHelper("classPrivateFieldDestructureSet"), [
449 this.receiver(member),
450 t.cloneNode(id),
451 ]),
452 t.identifier("value"),
453 );
454 },
455
456 call(member, args: (t.Expression | t.SpreadElement)[]) {
457 // The first access (the get) should do the memo assignment.
458 this.memoise(member, 1);
459
460 return optimiseCall(this.get(member), this.receiver(member), args, false);
461 },
462
463 optionalCall(member, args: (t.Expression | t.SpreadElement)[]) {
464 this.memoise(member, 1);
465
466 return optimiseCall(this.get(member), this.receiver(member), args, true);
467 },
468 };
469
470 const privateNameHandlerLoose: Handler<PrivateNameState> = {
471 get(member) {
472 const { privateNamesMap, file } = this;
473 const { object } = member.node;
474 const { name } = (member.node.property as t.PrivateName).id;
475
476 return template.expression`BASE(REF, PROP)[PROP]`({
477 BASE: file.addHelper("classPrivateFieldLooseBase"),
478 REF: t.cloneNode(object),
479 PROP: t.cloneNode(privateNamesMap.get(name).id),
480 });
481 },
482
483 set() {
484 // noop
485 throw new Error("private name handler with loose = true don't need set()");
486 },
487
488 boundGet(member) {
489 return t.callExpression(
490 t.memberExpression(this.get(member), t.identifier("bind")),
491 // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
492 [t.cloneNode(member.node.object as t.Expression)],
493 );
494 },
495
496 simpleSet(member) {
497 return this.get(member);
498 },
499
500 destructureSet(member) {
501 return this.get(member);
502 },
503
504 call(member, args) {
505 return t.callExpression(this.get(member), args);
506 },
507
508 optionalCall(member, args) {
509 return t.optionalCallExpression(this.get(member), args, true);
510 },
511 };
512
513 export function transformPrivateNamesUsage(
514 ref: t.Identifier,
515 path: NodePath<t.Class>,
516 privateNamesMap: PrivateNamesMap,
517 {
518 privateFieldsAsProperties,
519 noDocumentAll,
520 innerBinding,
521 }: {
522 privateFieldsAsProperties: boolean;
523 noDocumentAll: boolean;
524 innerBinding: t.Identifier;
525 },
526 state: File,
527 ) {
528 if (!privateNamesMap.size) return;
529
530 const body = path.get("body");
531 const handler = privateFieldsAsProperties
532 ? privateNameHandlerLoose
533 : privateNameHandlerSpec;
534
535 memberExpressionToFunctions<PrivateNameState>(body, privateNameVisitor, {
536 privateNamesMap,
537 classRef: ref,
538 file: state,
539 ...handler,
540 noDocumentAll,
541 innerBinding,
542 });
543 body.traverse(privateInVisitor, {
544 privateNamesMap,
545 classRef: ref,
546 file: state,
547 privateFieldsAsProperties,
548 innerBinding,
549 });
550 }
551
552 function buildPrivateFieldInitLoose(
553 ref: t.Expression,
554 prop: NodePath<t.ClassPrivateProperty>,
555 privateNamesMap: PrivateNamesMap,
556 ) {
557 const { id } = privateNamesMap.get(prop.node.key.id.name);
558 const value = prop.node.value || prop.scope.buildUndefinedNode();
559
560 return template.statement.ast`
561 Object.defineProperty(${ref}, ${t.cloneNode(id)}, {
562 // configurable is false by default
563 // enumerable is false by default
564 writable: true,
565 value: ${value}
566 });
567 `;
568 }
569
570 function buildPrivateInstanceFieldInitSpec(
571 ref: t.Expression,
572 prop: NodePath<t.ClassPrivateProperty>,
573 privateNamesMap: PrivateNamesMap,
574 state: File,
575 ) {
576 const { id } = privateNamesMap.get(prop.node.key.id.name);
577 const value = prop.node.value || prop.scope.buildUndefinedNode();
578
579 if (!process.env.BABEL_8_BREAKING) {
580 if (!state.availableHelper("classPrivateFieldInitSpec")) {
581 return template.statement.ast`${t.cloneNode(id)}.set(${ref}, {
582 // configurable is always false for private elements
583 // enumerable is always false for private elements
584 writable: true,
585 value: ${value},
586 })`;
587 }
588 }
589
590 const helper = state.addHelper("classPrivateFieldInitSpec");
591 return template.statement.ast`${helper}(
592 ${t.thisExpression()},
593 ${t.cloneNode(id)},
594 {
595 writable: true,
596 value: ${value}
597 },
598 )`;
599 }
600
601 function buildPrivateStaticFieldInitSpec(
602 prop: NodePath<t.ClassPrivateProperty>,
603 privateNamesMap: PrivateNamesMap,
604 ) {
605 const privateName = privateNamesMap.get(prop.node.key.id.name);
606 const { id, getId, setId, initAdded } = privateName;
607 const isAccessor = getId || setId;
608
609 if (!prop.isProperty() && (initAdded || !isAccessor)) return;
610
611 if (isAccessor) {
612 privateNamesMap.set(prop.node.key.id.name, {
613 ...privateName,
614 initAdded: true,
615 });
616
617 return template.statement.ast`
618 var ${t.cloneNode(id)} = {
619 // configurable is false by default
620 // enumerable is false by default
621 // writable is false by default
622 get: ${getId ? getId.name : prop.scope.buildUndefinedNode()},
623 set: ${setId ? setId.name : prop.scope.buildUndefinedNode()}
624 }
625 `;
626 }
627
628 const value = prop.node.value || prop.scope.buildUndefinedNode();
629 return template.statement.ast`
630 var ${t.cloneNode(id)} = {
631 // configurable is false by default
632 // enumerable is false by default
633 writable: true,
634 value: ${value}
635 };
636 `;
637 }
638
639 function buildPrivateMethodInitLoose(
640 ref: t.Expression,
641 prop: NodePath<t.ClassPrivateMethod>,
642 privateNamesMap: PrivateNamesMap,
643 ) {
644 const privateName = privateNamesMap.get(prop.node.key.id.name);
645 const { methodId, id, getId, setId, initAdded } = privateName;
646 if (initAdded) return;
647
648 if (methodId) {
649 return template.statement.ast`
650 Object.defineProperty(${ref}, ${id}, {
651 // configurable is false by default
652 // enumerable is false by default
653 // writable is false by default
654 value: ${methodId.name}
655 });
656 `;
657 }
658 const isAccessor = getId || setId;
659 if (isAccessor) {
660 privateNamesMap.set(prop.node.key.id.name, {
661 ...privateName,
662 initAdded: true,
663 });
664
665 return template.statement.ast`
666 Object.defineProperty(${ref}, ${id}, {
667 // configurable is false by default
668 // enumerable is false by default
669 // writable is false by default
670 get: ${getId ? getId.name : prop.scope.buildUndefinedNode()},
671 set: ${setId ? setId.name : prop.scope.buildUndefinedNode()}
672 });
673 `;
674 }
675 }
676
677 function buildPrivateInstanceMethodInitSpec(
678 ref: t.Expression,
679 prop: NodePath<t.ClassPrivateMethod>,
680 privateNamesMap: PrivateNamesMap,
681 state: File,
682 ) {
683 const privateName = privateNamesMap.get(prop.node.key.id.name);
684 const { getId, setId, initAdded } = privateName;
685
686 if (initAdded) return;
687
688 const isAccessor = getId || setId;
689 if (isAccessor) {
690 return buildPrivateAccessorInitialization(
691 ref,
692 prop,
693 privateNamesMap,
694 state,
695 );
696 }
697
698 return buildPrivateInstanceMethodInitalization(
699 ref,
700 prop,
701 privateNamesMap,
702 state,
703 );
704 }
705
706 function buildPrivateAccessorInitialization(
707 ref: t.Expression,
708 prop: NodePath<t.ClassPrivateMethod>,
709 privateNamesMap: PrivateNamesMap,
710 state: File,
711 ) {
712 const privateName = privateNamesMap.get(prop.node.key.id.name);
713 const { id, getId, setId } = privateName;
714
715 privateNamesMap.set(prop.node.key.id.name, {
716 ...privateName,
717 initAdded: true,
718 });
719
720 if (!process.env.BABEL_8_BREAKING) {
721 if (!state.availableHelper("classPrivateFieldInitSpec")) {
722 return template.statement.ast`
723 ${id}.set(${ref}, {
724 get: ${getId ? getId.name : prop.scope.buildUndefinedNode()},
725 set: ${setId ? setId.name : prop.scope.buildUndefinedNode()}
726 });
727 `;
728 }
729 }
730
731 const helper = state.addHelper("classPrivateFieldInitSpec");
732 return template.statement.ast`${helper}(
733 ${t.thisExpression()},
734 ${t.cloneNode(id)},
735 {
736 get: ${getId ? getId.name : prop.scope.buildUndefinedNode()},
737 set: ${setId ? setId.name : prop.scope.buildUndefinedNode()}
738 },
739 )`;
740 }
741
742 function buildPrivateInstanceMethodInitalization(
743 ref: t.Expression,
744 prop: NodePath<t.ClassPrivateMethod>,
745 privateNamesMap: PrivateNamesMap,
746 state: File,
747 ) {
748 const privateName = privateNamesMap.get(prop.node.key.id.name);
749 const { id } = privateName;
750
751 if (!process.env.BABEL_8_BREAKING) {
752 if (!state.availableHelper("classPrivateMethodInitSpec")) {
753 return template.statement.ast`${id}.add(${ref})`;
754 }
755 }
756
757 const helper = state.addHelper("classPrivateMethodInitSpec");
758 return template.statement.ast`${helper}(
759 ${t.thisExpression()},
760 ${t.cloneNode(id)}
761 )`;
762 }
763
764 function buildPublicFieldInitLoose(
765 ref: t.Expression,
766 prop: NodePath<t.ClassProperty>,
767 ) {
768 const { key, computed } = prop.node;
769 const value = prop.node.value || prop.scope.buildUndefinedNode();
770
771 return t.expressionStatement(
772 t.assignmentExpression(
773 "=",
774 t.memberExpression(ref, key, computed || t.isLiteral(key)),
775 value,
776 ),
777 );
778 }
779
780 function buildPublicFieldInitSpec(
781 ref: t.Expression,
782 prop: NodePath<t.ClassProperty>,
783 state: File,
784 ) {
785 const { key, computed } = prop.node;
786 const value = prop.node.value || prop.scope.buildUndefinedNode();
787
788 return t.expressionStatement(
789 t.callExpression(state.addHelper("defineProperty"), [
790 ref,
791 computed || t.isLiteral(key)
792 ? key
793 : t.stringLiteral((key as t.Identifier).name),
794 value,
795 ]),
796 );
797 }
798
799 function buildPrivateStaticMethodInitLoose(
800 ref: t.Expression,
801 prop: NodePath<t.ClassPrivateMethod>,
802 state: File,
803 privateNamesMap: PrivateNamesMap,
804 ) {
805 const privateName = privateNamesMap.get(prop.node.key.id.name);
806 const { id, methodId, getId, setId, initAdded } = privateName;
807
808 if (initAdded) return;
809
810 const isAccessor = getId || setId;
811 if (isAccessor) {
812 privateNamesMap.set(prop.node.key.id.name, {
813 ...privateName,
814 initAdded: true,
815 });
816
817 return template.statement.ast`
818 Object.defineProperty(${ref}, ${id}, {
819 // configurable is false by default
820 // enumerable is false by default
821 // writable is false by default
822 get: ${getId ? getId.name : prop.scope.buildUndefinedNode()},
823 set: ${setId ? setId.name : prop.scope.buildUndefinedNode()}
824 })
825 `;
826 }
827
828 return template.statement.ast`
829 Object.defineProperty(${ref}, ${id}, {
830 // configurable is false by default
831 // enumerable is false by default
832 // writable is false by default
833 value: ${methodId.name}
834 });
835 `;
836 }
837
838 function buildPrivateMethodDeclaration(
839 prop: NodePath<t.ClassPrivateMethod>,
840 privateNamesMap: PrivateNamesMap,
841 privateFieldsAsProperties = false,
842 ) {
843 const privateName = privateNamesMap.get(prop.node.key.id.name);
844 const {
845 id,
846 methodId,
847 getId,
848 setId,
849 getterDeclared,
850 setterDeclared,
851 static: isStatic,
852 } = privateName;
853 const { params, body, generator, async } = prop.node;
854 const isGetter = getId && !getterDeclared && params.length === 0;
855 const isSetter = setId && !setterDeclared && params.length > 0;
856
857 let declId = methodId;
858
859 if (isGetter) {
860 privateNamesMap.set(prop.node.key.id.name, {
861 ...privateName,
862 getterDeclared: true,
863 });
864 declId = getId;
865 } else if (isSetter) {
866 privateNamesMap.set(prop.node.key.id.name, {
867 ...privateName,
868 setterDeclared: true,
869 });
870 declId = setId;
871 } else if (isStatic && !privateFieldsAsProperties) {
872 declId = id;
873 }
874
875 return t.functionDeclaration(
876 t.cloneNode(declId),
877 // @ts-expect-error params for ClassMethod has TSParameterProperty
878 params,
879 body,
880 generator,
881 async,
882 );
883 }
884
885 type ReplaceThisState = {
886 classRef: t.Identifier;
887 needsClassRef: boolean;
888 innerBinding: t.Identifier | null;
889 };
890
891 const thisContextVisitor = traverse.visitors.merge<ReplaceThisState>([
892 {
893 ThisExpression(path, state) {
894 // Replace `delete this` with `true`
895 const parent = path.findParent(
896 path => !isTransparentExprWrapper(path.node),
897 );
898 if (t.isUnaryExpression(parent.node, { operator: "delete" })) {
899 path.parentPath.replaceWith(t.booleanLiteral(true));
900 return;
901 }
902
903 state.needsClassRef = true;
904 path.replaceWith(t.cloneNode(state.classRef));
905 },
906 MetaProperty(path) {
907 const meta = path.get("meta");
908 const property = path.get("property");
909 const { scope } = path;
910 // if there are `new.target` in static field
911 // we should replace it with `undefined`
912 if (
913 meta.isIdentifier({ name: "new" }) &&
914 property.isIdentifier({ name: "target" })
915 ) {
916 path.replaceWith(scope.buildUndefinedNode());
917 }
918 },
919 },
920 environmentVisitor,
921 ]);
922
923 const innerReferencesVisitor: Visitor<ReplaceThisState> = {
924 ReferencedIdentifier(path, state) {
925 if (
926 path.scope.bindingIdentifierEquals(path.node.name, state.innerBinding)
927 ) {
928 state.needsClassRef = true;
929 path.node.name = state.classRef.name;
930 }
931 },
932 };
933
934 function replaceThisContext(
935 path: PropPath,
936 ref: t.Identifier,
937 getSuperRef: () => t.Identifier,
938 file: File,
939 isStaticBlock: boolean,
940 constantSuper: boolean,
941 innerBindingRef: t.Identifier | null,
942 ) {
943 const state: ReplaceThisState = {
944 classRef: ref,
945 needsClassRef: false,
946 innerBinding: innerBindingRef,
947 };
948
949 const replacer = new ReplaceSupers({
950 methodPath: path,
951 constantSuper,
952 file,
953 refToPreserve: ref,
954 getSuperRef,
955 getObjectRef() {
956 state.needsClassRef = true;
957 // @ts-expect-error: TS doesn't infer that path.node is not a StaticBlock
958 return t.isStaticBlock?.(path.node) || path.node.static
959 ? ref
960 : t.memberExpression(ref, t.identifier("prototype"));
961 },
962 });
963 replacer.replace();
964 if (isStaticBlock || path.isProperty()) {
965 path.traverse(thisContextVisitor, state);
966 }
967
968 // todo: use innerBinding.referencePaths to avoid full traversal
969 if (
970 innerBindingRef != null &&
971 state.classRef?.name &&
972 state.classRef.name !== innerBindingRef?.name
973 ) {
974 path.traverse(innerReferencesVisitor, state);
975 }
976
977 return state.needsClassRef;
978 }
979
980 export type PropNode =
981 | t.ClassProperty
982 | t.ClassPrivateMethod
983 | t.ClassPrivateProperty
984 | t.StaticBlock;
985 export type PropPath = NodePath<PropNode>;
986
987 function isNameOrLength({ key, computed }: t.ClassProperty) {
988 if (key.type === "Identifier") {
989 return !computed && (key.name === "name" || key.name === "length");
990 }
991 if (key.type === "StringLiteral") {
992 return key.value === "name" || key.value === "length";
993 }
994 return false;
995 }
996
997 export function buildFieldsInitNodes(
998 ref: t.Identifier,
999 superRef: t.Expression | undefined,
1000 props: PropPath[],
1001 privateNamesMap: PrivateNamesMap,
1002 state: File,
1003 setPublicClassFields: boolean,
1004 privateFieldsAsProperties: boolean,
1005 constantSuper: boolean,
1006 innerBindingRef: t.Identifier,
1007 ) {
1008 let needsClassRef = false;
1009 let injectSuperRef: t.Identifier;
1010 const staticNodes: t.Statement[] = [];
1011 const instanceNodes: t.Statement[] = [];
1012 // These nodes are pure and can be moved to the closest statement position
1013 const pureStaticNodes: t.FunctionDeclaration[] = [];
1014
1015 const getSuperRef = t.isIdentifier(superRef)
1016 ? () => superRef
1017 : () => {
1018 injectSuperRef ??=
1019 props[0].scope.generateUidIdentifierBasedOnNode(superRef);
1020 return injectSuperRef;
1021 };
1022
1023 for (const prop of props) {
1024 prop.isClassProperty() && ts.assertFieldTransformed(prop);
1025
1026 // @ts-expect-error: TS doesn't infer that prop.node is not a StaticBlock
1027 const isStatic = !t.isStaticBlock?.(prop.node) && prop.node.static;
1028 const isInstance = !isStatic;
1029 const isPrivate = prop.isPrivate();
1030 const isPublic = !isPrivate;
1031 const isField = prop.isProperty();
1032 const isMethod = !isField;
1033 const isStaticBlock = prop.isStaticBlock?.();
1034
1035 if (isStatic || (isMethod && isPrivate) || isStaticBlock) {
1036 const replaced = replaceThisContext(
1037 prop,
1038 ref,
1039 getSuperRef,
1040 state,
1041 isStaticBlock,
1042 constantSuper,
1043 innerBindingRef,
1044 );
1045 needsClassRef = needsClassRef || replaced;
1046 }
1047
1048 // TODO(ts): there are so many `ts-expect-error` inside cases since
1049 // ts can not infer type from pre-computed values (or a case test)
1050 // even change `isStaticBlock` to `t.isStaticBlock(prop)` will not make prop
1051 // a `NodePath<t.StaticBlock>`
1052 // this maybe a bug for ts
1053 switch (true) {
1054 case isStaticBlock: {
1055 const blockBody = (prop.node as t.StaticBlock).body;
1056 // We special-case the single expression case to avoid the iife, since
1057 // it's common.
1058 if (blockBody.length === 1 && t.isExpressionStatement(blockBody[0])) {
1059 staticNodes.push(blockBody[0]);
1060 } else {
1061 staticNodes.push(template.statement.ast`(() => { ${blockBody} })()`);
1062 }
1063 break;
1064 }
1065 case isStatic && isPrivate && isField && privateFieldsAsProperties:
1066 needsClassRef = true;
1067 staticNodes.push(
1068 // @ts-expect-error checked in switch
1069 buildPrivateFieldInitLoose(t.cloneNode(ref), prop, privateNamesMap),
1070 );
1071 break;
1072 case isStatic && isPrivate && isField && !privateFieldsAsProperties:
1073 needsClassRef = true;
1074 staticNodes.push(
1075 // @ts-expect-error checked in switch
1076 buildPrivateStaticFieldInitSpec(prop, privateNamesMap),
1077 );
1078 break;
1079 case isStatic && isPublic && isField && setPublicClassFields:
1080 // Functions always have non-writable .name and .length properties,
1081 // so we must always use [[Define]] for them.
1082 // It might still be possible to a computed static fields whose resulting
1083 // key is "name" or "length", but the assumption is telling us that it's
1084 // not going to happen.
1085 // @ts-expect-error checked in switch
1086 if (!isNameOrLength(prop.node)) {
1087 needsClassRef = true;
1088 // @ts-expect-error checked in switch
1089 staticNodes.push(buildPublicFieldInitLoose(t.cloneNode(ref), prop));
1090 break;
1091 }
1092 // falls through
1093 case isStatic && isPublic && isField && !setPublicClassFields:
1094 needsClassRef = true;
1095 staticNodes.push(
1096 // @ts-expect-error checked in switch
1097 buildPublicFieldInitSpec(t.cloneNode(ref), prop, state),
1098 );
1099 break;
1100 case isInstance && isPrivate && isField && privateFieldsAsProperties:
1101 instanceNodes.push(
1102 // @ts-expect-error checked in switch
1103 buildPrivateFieldInitLoose(t.thisExpression(), prop, privateNamesMap),
1104 );
1105 break;
1106 case isInstance && isPrivate && isField && !privateFieldsAsProperties:
1107 instanceNodes.push(
1108 buildPrivateInstanceFieldInitSpec(
1109 t.thisExpression(),
1110 // @ts-expect-error checked in switch
1111 prop,
1112 privateNamesMap,
1113 state,
1114 ),
1115 );
1116 break;
1117 case isInstance && isPrivate && isMethod && privateFieldsAsProperties:
1118 instanceNodes.unshift(
1119 buildPrivateMethodInitLoose(
1120 t.thisExpression(),
1121 // @ts-expect-error checked in switch
1122 prop,
1123 privateNamesMap,
1124 ),
1125 );
1126 pureStaticNodes.push(
1127 buildPrivateMethodDeclaration(
1128 // @ts-expect-error checked in switch
1129 prop,
1130 privateNamesMap,
1131 privateFieldsAsProperties,
1132 ),
1133 );
1134 break;
1135 case isInstance && isPrivate && isMethod && !privateFieldsAsProperties:
1136 instanceNodes.unshift(
1137 buildPrivateInstanceMethodInitSpec(
1138 t.thisExpression(),
1139 // @ts-expect-error checked in switch
1140 prop,
1141 privateNamesMap,
1142 state,
1143 ),
1144 );
1145 pureStaticNodes.push(
1146 buildPrivateMethodDeclaration(
1147 // @ts-expect-error checked in switch
1148 prop,
1149 privateNamesMap,
1150 privateFieldsAsProperties,
1151 ),
1152 );
1153 break;
1154 case isStatic && isPrivate && isMethod && !privateFieldsAsProperties:
1155 needsClassRef = true;
1156 staticNodes.unshift(
1157 // @ts-expect-error checked in switch
1158 buildPrivateStaticFieldInitSpec(prop, privateNamesMap),
1159 );
1160 pureStaticNodes.push(
1161 buildPrivateMethodDeclaration(
1162 // @ts-expect-error checked in switch
1163 prop,
1164 privateNamesMap,
1165 privateFieldsAsProperties,
1166 ),
1167 );
1168 break;
1169 case isStatic && isPrivate && isMethod && privateFieldsAsProperties:
1170 needsClassRef = true;
1171 staticNodes.unshift(
1172 buildPrivateStaticMethodInitLoose(
1173 t.cloneNode(ref),
1174 // @ts-expect-error checked in switch
1175 prop,
1176 state,
1177 privateNamesMap,
1178 ),
1179 );
1180 pureStaticNodes.push(
1181 buildPrivateMethodDeclaration(
1182 // @ts-expect-error checked in switch
1183 prop,
1184 privateNamesMap,
1185 privateFieldsAsProperties,
1186 ),
1187 );
1188 break;
1189 case isInstance && isPublic && isField && setPublicClassFields:
1190 // @ts-expect-error checked in switch
1191 instanceNodes.push(buildPublicFieldInitLoose(t.thisExpression(), prop));
1192 break;
1193 case isInstance && isPublic && isField && !setPublicClassFields:
1194 instanceNodes.push(
1195 // @ts-expect-error checked in switch
1196 buildPublicFieldInitSpec(t.thisExpression(), prop, state),
1197 );
1198 break;
1199 default:
1200 throw new Error("Unreachable.");
1201 }
1202 }
1203
1204 return {
1205 staticNodes: staticNodes.filter(Boolean),
1206 instanceNodes: instanceNodes.filter(Boolean),
1207 pureStaticNodes: pureStaticNodes.filter(Boolean),
1208 wrapClass(path: NodePath<t.Class>) {
1209 for (const prop of props) {
1210 prop.remove();
1211 }
1212
1213 if (injectSuperRef) {
1214 path.scope.push({ id: t.cloneNode(injectSuperRef) });
1215 path.set(
1216 "superClass",
1217 t.assignmentExpression("=", injectSuperRef, path.node.superClass),
1218 );
1219 }
1220
1221 if (!needsClassRef) return path;
1222
1223 if (path.isClassExpression()) {
1224 path.scope.push({ id: ref });
1225 path.replaceWith(
1226 t.assignmentExpression("=", t.cloneNode(ref), path.node),
1227 );
1228 } else if (!path.node.id) {
1229 // Anonymous class declaration
1230 path.node.id = ref;
1231 }
1232
1233 return path;
1234 },
1235 };
1236 }