Debian Codegraph @

packages/babel-plugin-transform-for-of/src/index.ts

raw symbols SCIP
1 import { declare } from "@babel/helper-plugin-utils";
2 import { template, types as t } from "@babel/core";
3 import type { NodePath } from "@babel/traverse";
4
5 import transformWithoutHelper from "./no-helper-implementation";
6
7 export interface Options {
8 allowArrayLike?: boolean;
9 assumeArray?: boolean;
10 loose?: boolean;
11 }
12
13 function buildLoopBody(
14 path: NodePath<t.ForXStatement>,
15 declar: t.Statement,
16 newBody?: t.Statement | t.Expression,
17 ) {
18 let block;
19 const bodyPath = path.get("body");
20 const body = newBody ?? bodyPath.node;
21 if (
22 t.isBlockStatement(body) &&
23 Object.keys(path.getBindingIdentifiers()).some(id =>
24 bodyPath.scope.hasOwnBinding(id),
25 )
26 ) {
27 block = t.blockStatement([declar, body]);
28 } else {
29 block = t.toBlock(body);
30 block.body.unshift(declar);
31 }
32 return block;
33 }
34
35 export default declare((api, options: Options) => {
36 api.assertVersion(7);
37
38 {
39 const { assumeArray, allowArrayLike, loose } = options;
40
41 if (loose === true && assumeArray === true) {
42 throw new Error(
43 `The loose and assumeArray options cannot be used together in @babel/plugin-transform-for-of`,
44 );
45 }
46
47 if (assumeArray === true && allowArrayLike === true) {
48 throw new Error(
49 `The assumeArray and allowArrayLike options cannot be used together in @babel/plugin-transform-for-of`,
50 );
51 }
52
53 // TODO: Remove in Babel 8
54 if (allowArrayLike && /^7\.\d\./.test(api.version)) {
55 throw new Error(
56 `The allowArrayLike is only supported when using @babel/core@^7.10.0`,
57 );
58 }
59 }
60
61 const iterableIsArray =
62 options.assumeArray ??
63 // Loose mode is not compatible with 'assumeArray', so we shouldn't read
64 // 'iterableIsArray' if 'loose' is true.
65 (!options.loose && api.assumption("iterableIsArray"));
66
67 const arrayLikeIsIterable =
68 options.allowArrayLike ?? api.assumption("arrayLikeIsIterable");
69
70 const skipteratorClosing =
71 api.assumption("skipForOfIteratorClosing") ?? options.loose;
72
73 if (iterableIsArray && arrayLikeIsIterable) {
74 throw new Error(
75 `The "iterableIsArray" and "arrayLikeIsIterable" assumptions are not compatible.`,
76 );
77 }
78
79 if (iterableIsArray) {
80 return {
81 name: "transform-for-of",
82
83 visitor: {
84 ForOfStatement(path) {
85 const { scope } = path;
86 const { left, right, await: isAwait } = path.node;
87 if (isAwait) {
88 return;
89 }
90 const i = scope.generateUidIdentifier("i");
91 let array: t.Identifier | t.ThisExpression =
92 scope.maybeGenerateMemoised(right, true);
93
94 const inits = [t.variableDeclarator(i, t.numericLiteral(0))];
95 if (array) {
96 inits.push(t.variableDeclarator(array, right));
97 } else {
98 array = right as t.Identifier | t.ThisExpression;
99 }
100
101 const item = t.memberExpression(
102 t.cloneNode(array),
103 t.cloneNode(i),
104 true,
105 );
106 let assignment;
107 if (t.isVariableDeclaration(left)) {
108 assignment = left;
109 assignment.declarations[0].init = item;
110 } else {
111 assignment = t.expressionStatement(
112 t.assignmentExpression("=", left, item),
113 );
114 }
115
116 path.replaceWith(
117 t.forStatement(
118 t.variableDeclaration("let", inits),
119 t.binaryExpression(
120 "<",
121 t.cloneNode(i),
122 t.memberExpression(t.cloneNode(array), t.identifier("length")),
123 ),
124 t.updateExpression("++", t.cloneNode(i)),
125 buildLoopBody(path, assignment),
126 ),
127 );
128 },
129 },
130 };
131 }
132
133 const buildForOfArray = template`
134 for (var KEY = 0, NAME = ARR; KEY < NAME.length; KEY++) BODY;
135 `;
136
137 const buildForOfNoIteratorClosing = template.statements`
138 for (var ITERATOR_HELPER = CREATE_ITERATOR_HELPER(OBJECT, ARRAY_LIKE_IS_ITERABLE), STEP_KEY;
139 !(STEP_KEY = ITERATOR_HELPER()).done;) BODY;
140 `;
141
142 const buildForOf = template.statements`
143 var ITERATOR_HELPER = CREATE_ITERATOR_HELPER(OBJECT, ARRAY_LIKE_IS_ITERABLE), STEP_KEY;
144 try {
145 for (ITERATOR_HELPER.s(); !(STEP_KEY = ITERATOR_HELPER.n()).done;) BODY;
146 } catch (err) {
147 ITERATOR_HELPER.e(err);
148 } finally {
149 ITERATOR_HELPER.f();
150 }
151 `;
152
153 const builder = skipteratorClosing
154 ? {
155 build: buildForOfNoIteratorClosing,
156 helper: "createForOfIteratorHelperLoose",
157 getContainer: (nodes: t.Statement[]): [t.ForStatement] =>
158 nodes as [t.ForStatement],
159 }
160 : {
161 build: buildForOf,
162 helper: "createForOfIteratorHelper",
163 getContainer: (nodes: t.Statement[]): [t.ForStatement] =>
164 (nodes[1] as t.TryStatement).block.body as [t.ForStatement],
165 };
166
167 function _ForOfStatementArray(path: NodePath<t.ForOfStatement>) {
168 const { node, scope } = path;
169
170 const right = scope.generateUidIdentifierBasedOnNode(node.right, "arr");
171 const iterationKey = scope.generateUidIdentifier("i");
172
173 const loop = buildForOfArray({
174 BODY: node.body,
175 KEY: iterationKey,
176 NAME: right,
177 ARR: node.right,
178 }) as t.For;
179
180 t.inherits(loop, node);
181
182 const iterationValue = t.memberExpression(
183 t.cloneNode(right),
184 t.cloneNode(iterationKey),
185 true,
186 );
187
188 let declar;
189 const left = node.left;
190 if (t.isVariableDeclaration(left)) {
191 left.declarations[0].init = iterationValue;
192 declar = left;
193 } else {
194 declar = t.expressionStatement(
195 t.assignmentExpression("=", left, iterationValue),
196 );
197 }
198
199 loop.body = buildLoopBody(path, declar, loop.body);
200
201 return loop;
202 }
203
204 return {
205 name: "transform-for-of",
206 visitor: {
207 ForOfStatement(path, state) {
208 const right = path.get("right");
209 if (
210 right.isArrayExpression() ||
211 (process.env.BABEL_8_BREAKING
212 ? right.isGenericType("Array")
213 : right.isGenericType("Array") ||
214 t.isArrayTypeAnnotation(right.getTypeAnnotation()))
215 ) {
216 path.replaceWith(_ForOfStatementArray(path));
217 return;
218 }
219
220 if (!state.availableHelper(builder.helper)) {
221 // Babel <7.9.0 doesn't support this helper
222 transformWithoutHelper(skipteratorClosing, path, state);
223 return;
224 }
225
226 const { node, parent, scope } = path;
227 const left = node.left;
228 let declar;
229
230 const stepKey = scope.generateUid("step");
231 const stepValue = t.memberExpression(
232 t.identifier(stepKey),
233 t.identifier("value"),
234 );
235
236 if (t.isVariableDeclaration(left)) {
237 // for (let i of test)
238 declar = t.variableDeclaration(left.kind, [
239 t.variableDeclarator(left.declarations[0].id, stepValue),
240 ]);
241 } else {
242 // for (i of test), for ({ i } of test)
243 declar = t.expressionStatement(
244 t.assignmentExpression("=", left, stepValue),
245 );
246 }
247
248 const nodes = builder.build({
249 CREATE_ITERATOR_HELPER: state.addHelper(builder.helper),
250 ITERATOR_HELPER: scope.generateUidIdentifier("iterator"),
251 ARRAY_LIKE_IS_ITERABLE: arrayLikeIsIterable
252 ? t.booleanLiteral(true)
253 : null,
254 STEP_KEY: t.identifier(stepKey),
255 OBJECT: node.right,
256 BODY: buildLoopBody(path, declar),
257 });
258 const container = builder.getContainer(nodes);
259
260 t.inherits(container[0], node);
261 t.inherits(container[0].body, node.body);
262
263 if (t.isLabeledStatement(parent)) {
264 // @ts-expect-error replacing node types
265 container[0] = t.labeledStatement(parent.label, container[0]);
266
267 path.parentPath.replaceWithMultiple(nodes);
268
269 // The parent has been replaced, prevent Babel from traversing a detatched path
270 path.skip();
271 } else {
272 path.replaceWithMultiple(nodes);
273 }
274 },
275 },
276 };
277 });