Debian Codegraph @

packages/babel-types/src/converters/gatherSequenceExpressions.ts

raw
1 import getBindingIdentifiers from "../retrievers/getBindingIdentifiers";
2 import {
3 isExpression,
4 isExpressionStatement,
5 isVariableDeclaration,
6 isIfStatement,
7 isBlockStatement,
8 isEmptyStatement,
9 } from "../validators/generated";
10 import {
11 sequenceExpression,
12 assignmentExpression,
13 conditionalExpression,
14 } from "../builders/generated";
15 import cloneNode from "../clone/cloneNode";
16 import type * as t from "..";
17 import type { Scope } from "@babel/traverse";
18
19 export type DeclarationInfo = {
20 kind: t.VariableDeclaration["kind"];
21 id: t.Identifier;
22 };
23
24 export default function gatherSequenceExpressions(
25 nodes: ReadonlyArray<t.Node>,
26 scope: Scope,
27 declars: Array<DeclarationInfo>,
28 ) {
29 const exprs: t.Expression[] = [];
30 let ensureLastUndefined = true;
31
32 for (const node of nodes) {
33 // if we encounter emptyStatement before a non-emptyStatement
34 // we want to disregard that
35 if (!isEmptyStatement(node)) {
36 ensureLastUndefined = false;
37 }
38
39 if (isExpression(node)) {
40 exprs.push(node);
41 } else if (isExpressionStatement(node)) {
42 exprs.push(node.expression);
43 } else if (isVariableDeclaration(node)) {
44 if (node.kind !== "var") return; // bailed
45
46 for (const declar of node.declarations) {
47 const bindings = getBindingIdentifiers(declar);
48 for (const key of Object.keys(bindings)) {
49 declars.push({
50 kind: node.kind,
51 id: cloneNode(bindings[key]),
52 });
53 }
54
55 if (declar.init) {
56 exprs.push(assignmentExpression("=", declar.id, declar.init));
57 }
58 }
59
60 ensureLastUndefined = true;
61 } else if (isIfStatement(node)) {
62 const consequent = node.consequent
63 ? gatherSequenceExpressions([node.consequent], scope, declars)
64 : scope.buildUndefinedNode();
65 const alternate = node.alternate
66 ? gatherSequenceExpressions([node.alternate], scope, declars)
67 : scope.buildUndefinedNode();
68 if (!consequent || !alternate) return; // bailed
69
70 exprs.push(conditionalExpression(node.test, consequent, alternate));
71 } else if (isBlockStatement(node)) {
72 const body = gatherSequenceExpressions(node.body, scope, declars);
73 if (!body) return; // bailed
74
75 exprs.push(body);
76 } else if (isEmptyStatement(node)) {
77 // empty statement so ensure the last item is undefined if we're last
78 // checks if emptyStatement is first
79 if (nodes.indexOf(node) === 0) {
80 ensureLastUndefined = true;
81 }
82 } else {
83 // bailed, we can't turn this statement into an expression
84 return;
85 }
86 }
87
88 if (ensureLastUndefined) {
89 exprs.push(scope.buildUndefinedNode());
90 }
91
92 if (exprs.length === 1) {
93 return exprs[0];
94 } else {
95 return sequenceExpression(exprs);
96 }
97 }