Debian Codegraph @

packages/babel-plugin-proposal-pipeline-operator/src/buildOptimizedSequenceExpression.ts

raw symbols SCIP
1 import { types as t } from "@babel/core";
2 import type { NodePath } from "@babel/traverse";
3
4 // tries to optimize sequence expressions in the format
5 // (a = b, (c => c + e)(a))
6 // to
7 // (a = b, a + e)
8
9 type Options = {
10 call: t.CallExpression | t.AwaitExpression;
11 path: NodePath<t.BinaryExpression & { operator: "|>" }>;
12 placeholder: t.Identifier;
13 };
14
15 function isConciseArrowExpression(
16 node: t.Node,
17 ): node is t.ArrowFunctionExpression & { body: t.Expression } {
18 return (
19 t.isArrowFunctionExpression(node) &&
20 t.isExpression(node.body) &&
21 !node.async
22 );
23 }
24
25 const buildOptimizedSequenceExpression = ({
26 call,
27 path,
28 placeholder,
29 }: Options) => {
30 // @ts-expect-error AwaitExpression does not have callee property
31 const { callee: calledExpression } = call;
32 // pipelineLeft must not be a PrivateName
33 const pipelineLeft = path.node.left as t.Expression;
34 const assign = t.assignmentExpression(
35 "=",
36 t.cloneNode(placeholder),
37 pipelineLeft,
38 );
39
40 const expressionIsArrow = isConciseArrowExpression(calledExpression);
41
42 if (expressionIsArrow) {
43 let param;
44 let optimizeArrow = true;
45 const { params } = calledExpression;
46 if (params.length === 1 && t.isIdentifier(params[0])) {
47 param = params[0];
48 } else if (params.length > 0) {
49 optimizeArrow = false;
50 }
51 if (optimizeArrow && !param) {
52 // fixme: arrow function with 1 pattern argument will also go into this branch
53 // Arrow function with 0 arguments
54 return t.sequenceExpression([pipelineLeft, calledExpression.body]);
55 } else if (param) {
56 path.scope.push({ id: t.cloneNode(placeholder) });
57 path.get("right").scope.rename(param.name, placeholder.name);
58
59 return t.sequenceExpression([assign, calledExpression.body]);
60 }
61 } else if (t.isIdentifier(calledExpression, { name: "eval" })) {
62 const evalSequence = t.sequenceExpression([
63 t.numericLiteral(0),
64 calledExpression,
65 ]);
66
67 (call as t.CallExpression).callee = evalSequence;
68 }
69 path.scope.push({ id: t.cloneNode(placeholder) });
70
71 return t.sequenceExpression([assign, call]);
72 };
73
74 export default buildOptimizedSequenceExpression;