Debian Codegraph @

packages/babel-helper-member-expression-to-functions/src/index.ts

raw symbols SCIP
1 import type { NodePath, Visitor } from "@babel/traverse";
2 import {
3 LOGICAL_OPERATORS,
4 arrowFunctionExpression,
5 assignmentExpression,
6 binaryExpression,
7 booleanLiteral,
8 callExpression,
9 cloneNode,
10 conditionalExpression,
11 identifier,
12 isMemberExpression,
13 isOptionalCallExpression,
14 isOptionalMemberExpression,
15 isUpdateExpression,
16 logicalExpression,
17 memberExpression,
18 nullLiteral,
19 optionalCallExpression,
20 optionalMemberExpression,
21 sequenceExpression,
22 updateExpression,
23 } from "@babel/types";
24 import type * as t from "@babel/types";
25 import { willPathCastToBoolean } from "./util";
26
27 class AssignmentMemoiser {
28 private _map: WeakMap<t.Expression, { count: number; value: t.Identifier }>;
29 constructor() {
30 this._map = new WeakMap();
31 }
32
33 has(key: t.Expression) {
34 return this._map.has(key);
35 }
36
37 get(key: t.Expression) {
38 if (!this.has(key)) return;
39
40 const record = this._map.get(key);
41 const { value } = record;
42
43 record.count--;
44 if (record.count === 0) {
45 // The `count` access is the outermost function call (hopefully), so it
46 // does the assignment.
47 return assignmentExpression("=", value, key);
48 }
49 return value;
50 }
51
52 set(key: t.Expression, value: t.Identifier, count: number) {
53 return this._map.set(key, { count, value });
54 }
55 }
56
57 function toNonOptional(
58 path: NodePath<t.Expression>,
59 base: t.Expression,
60 ): t.Expression {
61 const { node } = path;
62 if (isOptionalMemberExpression(node)) {
63 return memberExpression(base, node.property, node.computed);
64 }
65
66 if (path.isOptionalCallExpression()) {
67 const callee = path.get("callee");
68 if (path.node.optional && callee.isOptionalMemberExpression()) {
69 // object must be a conditional expression because the optional private access in object has been transformed
70 const object = callee.node.object as t.ConditionalExpression;
71 const context = path.scope.maybeGenerateMemoised(object);
72 callee
73 .get("object")
74 .replaceWith(assignmentExpression("=", context, object));
75
76 return callExpression(memberExpression(base, identifier("call")), [
77 context,
78 ...path.node.arguments,
79 ]);
80 }
81
82 return callExpression(base, path.node.arguments);
83 }
84
85 return path.node;
86 }
87
88 // Determines if the current path is in a detached tree. This can happen when
89 // we are iterating on a path, and replace an ancestor with a new node. Babel
90 // doesn't always stop traversing the old node tree, and that can cause
91 // inconsistencies.
92 function isInDetachedTree(path: NodePath) {
93 while (path) {
94 if (path.isProgram()) break;
95
96 const { parentPath, container, listKey } = path;
97 const parentNode = parentPath.node;
98 if (listKey) {
99 if (
100 container !==
101 // @ts-expect-error listKey must be a valid parent node key
102 parentNode[listKey]
103 ) {
104 return true;
105 }
106 } else {
107 if (container !== parentNode) return true;
108 }
109
110 path = parentPath;
111 }
112
113 return false;
114 }
115
116 type Member = NodePath<t.OptionalMemberExpression | t.MemberExpression>;
117
118 const handle = {
119 memoise() {
120 // noop.
121 },
122
123 handle(this: HandlerState, member: Member, noDocumentAll: boolean) {
124 const { node, parent, parentPath, scope } = member;
125
126 if (member.isOptionalMemberExpression()) {
127 // Transforming optional chaining requires we replace ancestors.
128 if (isInDetachedTree(member)) return;
129
130 // We're looking for the end of _this_ optional chain, which is actually
131 // the "rightmost" property access of the chain. This is because
132 // everything up to that property access is "optional".
133 //
134 // Let's take the case of `FOO?.BAR.baz?.qux`, with `FOO?.BAR` being our
135 // member. The "end" to most users would be `qux` property access.
136 // Everything up to it could be skipped if it `FOO` were nullish. But
137 // actually, we can consider the `baz` access to be the end. So we're
138 // looking for the nearest optional chain that is `optional: true`.
139 const endPath = member.find(({ node, parent }) => {
140 if (isOptionalMemberExpression(parent)) {
141 // We need to check `parent.object` since we could be inside the
142 // computed expression of a `bad?.[FOO?.BAR]`. In this case, the
143 // endPath is the `FOO?.BAR` member itself.
144 return parent.optional || parent.object !== node;
145 }
146 if (isOptionalCallExpression(parent)) {
147 // Checking `parent.callee` since we could be in the arguments, eg
148 // `bad?.(FOO?.BAR)`.
149 // Also skip `FOO?.BAR` in `FOO?.BAR?.()` since we need to transform the optional call to ensure proper this
150 return (
151 // In FOO?.#BAR?.(), endPath points the optional call expression so we skip FOO?.#BAR
152 (node !== member.node && parent.optional) || parent.callee !== node
153 );
154 }
155 return true;
156 }) as NodePath<t.OptionalMemberExpression>;
157
158 // Replace `function (a, x = a.b?.#c) {}` to `function (a, x = (() => a.b?.#c)() ){}`
159 // so the temporary variable can be injected in correct scope
160 // This can be further optimized to avoid unecessary IIFE
161 if (scope.path.isPattern()) {
162 endPath.replaceWith(
163 // The injected member will be queued and eventually transformed when visited
164 callExpression(arrowFunctionExpression([], endPath.node), []),
165 );
166 return;
167 }
168
169 const willEndPathCastToBoolean = willPathCastToBoolean(endPath);
170
171 const rootParentPath = endPath.parentPath;
172 if (
173 rootParentPath.isUpdateExpression({ argument: node }) ||
174 rootParentPath.isAssignmentExpression({ left: node })
175 ) {
176 throw member.buildCodeFrameError(`can't handle assignment`);
177 }
178 const isDeleteOperation = rootParentPath.isUnaryExpression({
179 operator: "delete",
180 });
181 if (
182 isDeleteOperation &&
183 endPath.isOptionalMemberExpression() &&
184 endPath.get("property").isPrivateName()
185 ) {
186 // @babel/parser will throw error on `delete obj?.#x`.
187 // This error serves as fallback when `delete obj?.#x` is constructed from babel types
188 throw member.buildCodeFrameError(
189 `can't delete a private class element`,
190 );
191 }
192
193 // Now, we're looking for the start of this optional chain, which is
194 // optional to the left of this member.
195 //
196 // Let's take the case of `foo?.bar?.baz.QUX?.BAM`, with `QUX?.BAM` being
197 // our member. The "start" to most users would be `foo` object access.
198 // But actually, we can consider the `bar` access to be the start. So
199 // we're looking for the nearest optional chain that is `optional: true`,
200 // which is guaranteed to be somewhere in the object/callee tree.
201 let startingOptional: NodePath<t.Expression> = member;
202 for (;;) {
203 if (startingOptional.isOptionalMemberExpression()) {
204 if (startingOptional.node.optional) break;
205 startingOptional = startingOptional.get("object");
206 continue;
207 } else if (startingOptional.isOptionalCallExpression()) {
208 if (startingOptional.node.optional) break;
209 startingOptional = startingOptional.get("callee");
210 continue;
211 }
212 // prevent infinite loop: unreachable if the AST is well-formed
213 throw new Error(
214 `Internal error: unexpected ${startingOptional.node.type}`,
215 );
216 }
217
218 // @ts-expect-error isOptionalMemberExpression does not work with NodePath union
219 const startingNode = startingOptional.isOptionalMemberExpression()
220 ? // @ts-expect-error isOptionalMemberExpression does not work with NodePath union
221 startingOptional.node.object
222 : // @ts-expect-error isOptionalMemberExpression does not work with NodePath union
223 startingOptional.node.callee;
224 const baseNeedsMemoised = scope.maybeGenerateMemoised(startingNode);
225 const baseRef = baseNeedsMemoised ?? startingNode;
226
227 // Compute parentIsOptionalCall before `startingOptional` is replaced
228 // as `node` may refer to `startingOptional.node` before replaced.
229 const parentIsOptionalCall = parentPath.isOptionalCallExpression({
230 callee: node,
231 });
232 // here we use a function to wrap `parentIsOptionalCall` to get type
233 // for parent, do not use it anywhere else
234 // See https://github.com/microsoft/TypeScript/issues/10421
235 const isOptionalCall = (
236 parent: t.Node,
237 ): parent is t.OptionalCallExpression => parentIsOptionalCall;
238 // if parentIsCall is true, it implies that node.extra.parenthesized is always true
239 const parentIsCall = parentPath.isCallExpression({ callee: node });
240 startingOptional.replaceWith(toNonOptional(startingOptional, baseRef));
241 if (isOptionalCall(parent)) {
242 if (parent.optional) {
243 parentPath.replaceWith(this.optionalCall(member, parent.arguments));
244 } else {
245 parentPath.replaceWith(this.call(member, parent.arguments));
246 }
247 } else if (parentIsCall) {
248 // `(a?.#b)()` to `(a == null ? void 0 : a.#b.bind(a))()`
249 member.replaceWith(this.boundGet(member));
250 } else if (
251 this.delete &&
252 parentPath.isUnaryExpression({ operator: "delete" })
253 ) {
254 parentPath.replaceWith(this.delete(member));
255 } else {
256 member.replaceWith(this.get(member));
257 }
258
259 let regular: t.Expression = member.node;
260 for (let current: NodePath = member; current !== endPath; ) {
261 const parentPath = current.parentPath as NodePath<t.Expression>;
262 // skip transforming `Foo.#BAR?.call(FOO)`
263 if (
264 parentPath === endPath &&
265 isOptionalCall(parent) &&
266 parent.optional
267 ) {
268 regular = parentPath.node;
269 break;
270 }
271 regular = toNonOptional(parentPath, regular);
272 current = parentPath;
273 }
274
275 let context: t.Identifier;
276 const endParentPath = endPath.parentPath as NodePath<t.Expression>;
277 if (
278 isMemberExpression(regular) &&
279 endParentPath.isOptionalCallExpression({
280 callee: endPath.node,
281 optional: true,
282 })
283 ) {
284 const { object } = regular;
285 context = member.scope.maybeGenerateMemoised(object);
286 if (context) {
287 regular.object = assignmentExpression(
288 "=",
289 context,
290 // object must not be Super when `context` is an identifier
291 // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
292 object as t.Expression,
293 );
294 }
295 }
296
297 let replacementPath: NodePath = endPath;
298 if (isDeleteOperation) {
299 replacementPath = endParentPath;
300 regular = endParentPath.node;
301 }
302
303 const baseMemoised = baseNeedsMemoised
304 ? assignmentExpression(
305 "=",
306 // When base needs memoised, the baseRef must be an identifier
307 cloneNode(baseRef as t.Identifier),
308 cloneNode(startingNode),
309 )
310 : cloneNode(baseRef);
311
312 if (willEndPathCastToBoolean) {
313 let nonNullishCheck;
314 if (noDocumentAll) {
315 nonNullishCheck = binaryExpression("!=", baseMemoised, nullLiteral());
316 } else {
317 nonNullishCheck = logicalExpression(
318 "&&",
319 binaryExpression("!==", baseMemoised, nullLiteral()),
320 binaryExpression(
321 "!==",
322 cloneNode(baseRef),
323 scope.buildUndefinedNode(),
324 ),
325 );
326 }
327 replacementPath.replaceWith(
328 logicalExpression("&&", nonNullishCheck, regular),
329 );
330 } else {
331 let nullishCheck;
332 if (noDocumentAll) {
333 nullishCheck = binaryExpression("==", baseMemoised, nullLiteral());
334 } else {
335 nullishCheck = logicalExpression(
336 "||",
337 binaryExpression("===", baseMemoised, nullLiteral()),
338 binaryExpression(
339 "===",
340 cloneNode(baseRef),
341 scope.buildUndefinedNode(),
342 ),
343 );
344 }
345
346 replacementPath.replaceWith(
347 conditionalExpression(
348 nullishCheck,
349 isDeleteOperation
350 ? booleanLiteral(true)
351 : scope.buildUndefinedNode(),
352 regular,
353 ),
354 );
355 }
356
357 // context and isDeleteOperation can not be both truthy
358 if (context) {
359 const endParent = endParentPath.node as t.OptionalCallExpression;
360 endParentPath.replaceWith(
361 optionalCallExpression(
362 optionalMemberExpression(
363 endParent.callee,
364 identifier("call"),
365 false,
366 true,
367 ),
368 [cloneNode(context), ...endParent.arguments],
369 false,
370 ),
371 );
372 }
373
374 return;
375 }
376
377 // MEMBER++ -> _set(MEMBER, (ref = _get(MEMBER), ref2 = ref++, ref)), ref2
378 // ++MEMBER -> _set(MEMBER, (ref = _get(MEMBER), ++ref))
379 if (isUpdateExpression(parent, { argument: node })) {
380 if (this.simpleSet) {
381 member.replaceWith(this.simpleSet(member));
382 return;
383 }
384
385 const { operator, prefix } = parent;
386
387 // Give the state handler a chance to memoise the member, since we'll
388 // reference it twice. The second access (the set) should do the memo
389 // assignment.
390 this.memoise(member, 2);
391
392 const ref = scope.generateUidIdentifierBasedOnNode(node);
393 scope.push({ id: ref });
394
395 const seq: t.Expression[] = [
396 // ref = _get(MEMBER)
397 assignmentExpression("=", cloneNode(ref), this.get(member)),
398 ];
399
400 if (prefix) {
401 seq.push(updateExpression(operator, cloneNode(ref), prefix));
402
403 // (ref = _get(MEMBER), ++ref)
404 const value = sequenceExpression(seq);
405 parentPath.replaceWith(this.set(member, value));
406
407 return;
408 } else {
409 const ref2 = scope.generateUidIdentifierBasedOnNode(node);
410 scope.push({ id: ref2 });
411
412 seq.push(
413 assignmentExpression(
414 "=",
415 cloneNode(ref2),
416 updateExpression(operator, cloneNode(ref), prefix),
417 ),
418 cloneNode(ref),
419 );
420
421 // (ref = _get(MEMBER), ref2 = ref++, ref)
422 const value = sequenceExpression(seq);
423 parentPath.replaceWith(
424 sequenceExpression([this.set(member, value), cloneNode(ref2)]),
425 );
426
427 return;
428 }
429 }
430
431 // MEMBER = VALUE -> _set(MEMBER, VALUE)
432 // MEMBER += VALUE -> _set(MEMBER, _get(MEMBER) + VALUE)
433 // MEMBER ??= VALUE -> _get(MEMBER) ?? _set(MEMBER, VALUE)
434 if (parentPath.isAssignmentExpression({ left: node })) {
435 if (this.simpleSet) {
436 member.replaceWith(this.simpleSet(member));
437 return;
438 }
439
440 const { operator, right: value } = parentPath.node;
441
442 if (operator === "=") {
443 parentPath.replaceWith(this.set(member, value));
444 } else {
445 const operatorTrunc = operator.slice(0, -1);
446 if (LOGICAL_OPERATORS.includes(operatorTrunc)) {
447 // Give the state handler a chance to memoise the member, since we'll
448 // reference it twice. The first access (the get) should do the memo
449 // assignment.
450 this.memoise(member, 1);
451 parentPath.replaceWith(
452 logicalExpression(
453 operatorTrunc as t.LogicalExpression["operator"],
454 this.get(member),
455 this.set(member, value),
456 ),
457 );
458 } else {
459 // Here, the second access (the set) is evaluated first.
460 this.memoise(member, 2);
461 parentPath.replaceWith(
462 this.set(
463 member,
464 binaryExpression(
465 operatorTrunc as t.BinaryExpression["operator"],
466 this.get(member),
467 value,
468 ),
469 ),
470 );
471 }
472 }
473 return;
474 }
475
476 // MEMBER(ARGS) -> _call(MEMBER, ARGS)
477 if (parentPath.isCallExpression({ callee: node })) {
478 parentPath.replaceWith(this.call(member, parentPath.node.arguments));
479 return;
480 }
481
482 // MEMBER?.(ARGS) -> _optionalCall(MEMBER, ARGS)
483 if (parentPath.isOptionalCallExpression({ callee: node })) {
484 // Replace `function (a, x = a.b.#c?.()) {}` to `function (a, x = (() => a.b.#c?.())() ){}`
485 // so the temporary variable can be injected in correct scope
486 // This can be further optimized to avoid unecessary IIFE
487 if (scope.path.isPattern()) {
488 parentPath.replaceWith(
489 // The injected member will be queued and eventually transformed when visited
490 callExpression(arrowFunctionExpression([], parentPath.node), []),
491 );
492 return;
493 }
494 parentPath.replaceWith(
495 this.optionalCall(member, parentPath.node.arguments),
496 );
497 return;
498 }
499
500 // delete MEMBER -> _delete(MEMBER)
501 if (this.delete && parentPath.isUnaryExpression({ operator: "delete" })) {
502 parentPath.replaceWith(this.delete(member));
503 return;
504 }
505
506 // for (MEMBER of ARR)
507 // for (MEMBER in ARR)
508 // { KEY: MEMBER } = OBJ -> { KEY: _destructureSet(MEMBER) } = OBJ
509 // { KEY: MEMBER = _VALUE } = OBJ -> { KEY: _destructureSet(MEMBER) = _VALUE } = OBJ
510 // {...MEMBER} -> {..._destructureSet(MEMBER)}
511 //
512 // [MEMBER] = ARR -> [_destructureSet(MEMBER)] = ARR
513 // [MEMBER = _VALUE] = ARR -> [_destructureSet(MEMBER) = _VALUE] = ARR
514 // [...MEMBER] -> [..._destructureSet(MEMBER)]
515 if (
516 // for (MEMBER of ARR)
517 // for (MEMBER in ARR)
518 parentPath.isForXStatement({ left: node }) ||
519 // { KEY: MEMBER } = OBJ
520 (parentPath.isObjectProperty({ value: node }) &&
521 parentPath.parentPath.isObjectPattern()) ||
522 // { KEY: MEMBER = _VALUE } = OBJ
523 (parentPath.isAssignmentPattern({ left: node }) &&
524 parentPath.parentPath.isObjectProperty({ value: parent }) &&
525 parentPath.parentPath.parentPath.isObjectPattern()) ||
526 // [MEMBER] = ARR
527 parentPath.isArrayPattern() ||
528 // [MEMBER = _VALUE] = ARR
529 (parentPath.isAssignmentPattern({ left: node }) &&
530 parentPath.parentPath.isArrayPattern()) ||
531 // {...MEMBER}
532 // [...MEMBER]
533 parentPath.isRestElement()
534 ) {
535 member.replaceWith(this.destructureSet(member));
536 return;
537 }
538
539 if (parentPath.isTaggedTemplateExpression()) {
540 // MEMBER -> _get(MEMBER).bind(this)
541 member.replaceWith(this.boundGet(member));
542 } else {
543 // MEMBER -> _get(MEMBER)
544 member.replaceWith(this.get(member));
545 }
546 },
547 };
548
549 export interface Handler<State> {
550 memoise?(
551 this: HandlerState<State> & State,
552 member: Member,
553 count: number,
554 ): void;
555 destructureSet(
556 this: HandlerState<State> & State,
557 member: Member,
558 ): t.Expression;
559 boundGet(this: HandlerState<State> & State, member: Member): t.Expression;
560 simpleSet?(this: HandlerState<State> & State, member: Member): t.Expression;
561 get(this: HandlerState<State> & State, member: Member): t.Expression;
562 set(
563 this: HandlerState<State> & State,
564 member: Member,
565 value: t.Expression,
566 ): t.Expression;
567 call(
568 this: HandlerState<State> & State,
569 member: Member,
570 args: t.CallExpression["arguments"],
571 ): t.Expression;
572 optionalCall(
573 this: HandlerState<State> & State,
574 member: Member,
575 args: t.OptionalCallExpression["arguments"],
576 ): t.Expression;
577 // TODO(Babel 8): Consider making this required, since `.get` doesn't
578 // really work as a fallback for `.delete`
579 delete?(this: HandlerState<State> & State, member: Member): t.Expression;
580 }
581
582 export interface HandlerState<State = {}> extends Handler<State> {
583 handle(
584 this: HandlerState<State> & State,
585 member: Member,
586 noDocumentAll?: boolean,
587 ): void;
588 memoiser: AssignmentMemoiser;
589 }
590
591 // We do not provide a default traversal visitor
592 // Instead, caller passes one, and must call `state.handle` on the members
593 // it wishes to be transformed.
594 // Additionally, the caller must pass in a state object with at least
595 // get, set, and call methods.
596 // Optionally, a memoise method may be defined on the state, which will be
597 // called when the member is a self-referential update.
598 export default function memberExpressionToFunctions<CustomState = {}>(
599 path: NodePath,
600 visitor: Visitor<HandlerState<CustomState>>,
601 state: Handler<CustomState> & CustomState,
602 ) {
603 path.traverse(visitor, {
604 ...handle,
605 ...state,
606 memoiser: new AssignmentMemoiser(),
607 });
608 }