Debian Codegraph @

packages/babel-plugin-proposal-async-generator-functions/src/for-await.ts

raw
1 import { types as t, template } from "@babel/core";
2 import type { NodePath } from "@babel/traverse";
3
4 const buildForAwait = template(`
5 async function wrapper() {
6 var ITERATOR_ABRUPT_COMPLETION = false;
7 var ITERATOR_HAD_ERROR_KEY = false;
8 var ITERATOR_ERROR_KEY;
9 try {
10 for (
11 var ITERATOR_KEY = GET_ITERATOR(OBJECT), STEP_KEY;
12 ITERATOR_ABRUPT_COMPLETION = !(STEP_KEY = await ITERATOR_KEY.next()).done;
13 ITERATOR_ABRUPT_COMPLETION = false
14 ) {
15 }
16 } catch (err) {
17 ITERATOR_HAD_ERROR_KEY = true;
18 ITERATOR_ERROR_KEY = err;
19 } finally {
20 try {
21 if (ITERATOR_ABRUPT_COMPLETION && ITERATOR_KEY.return != null) {
22 await ITERATOR_KEY.return();
23 }
24 } finally {
25 if (ITERATOR_HAD_ERROR_KEY) {
26 throw ITERATOR_ERROR_KEY;
27 }
28 }
29 }
30 }
31 `);
32
33 export default function (
34 path: NodePath<t.ForOfStatement>,
35 { getAsyncIterator }: { getAsyncIterator: t.Identifier },
36 ) {
37 const { node, scope, parent } = path;
38
39 const stepKey = scope.generateUidIdentifier("step");
40 const stepValue = t.memberExpression(stepKey, t.identifier("value"));
41 const left = node.left;
42 let declar;
43
44 if (t.isIdentifier(left) || t.isPattern(left) || t.isMemberExpression(left)) {
45 // for await (i of test), for await ({ i } of test)
46 declar = t.expressionStatement(
47 t.assignmentExpression("=", left, stepValue),
48 );
49 } else if (t.isVariableDeclaration(left)) {
50 // for await (let i of test)
51 declar = t.variableDeclaration(left.kind, [
52 t.variableDeclarator(left.declarations[0].id, stepValue),
53 ]);
54 }
55 let template = buildForAwait({
56 ITERATOR_HAD_ERROR_KEY: scope.generateUidIdentifier("didIteratorError"),
57 ITERATOR_ABRUPT_COMPLETION: scope.generateUidIdentifier(
58 "iteratorAbruptCompletion",
59 ),
60 ITERATOR_ERROR_KEY: scope.generateUidIdentifier("iteratorError"),
61 ITERATOR_KEY: scope.generateUidIdentifier("iterator"),
62 GET_ITERATOR: getAsyncIterator,
63 OBJECT: node.right,
64 STEP_KEY: t.cloneNode(stepKey),
65 });
66
67 // remove async function wrapper
68 // @ts-expect-error todo(flow->ts) improve type annotation for buildForAwait
69 template = template.body.body as t.Statement[];
70
71 const isLabeledParent = t.isLabeledStatement(parent);
72 const tryBody = (template[3] as t.TryStatement).block.body;
73 const loop = tryBody[0] as t.ForStatement;
74
75 if (isLabeledParent) {
76 tryBody[0] = t.labeledStatement(parent.label, loop);
77 }
78
79 return {
80 replaceParent: isLabeledParent,
81 node: template,
82 declar,
83 loop,
84 };
85 }