Debian Codegraph @

packages/babel-helper-remap-async-to-generator/src/index.ts

raw symbols SCIP
1 /* @noflow */
2
3 import type { NodePath } from "@babel/traverse";
4 import wrapFunction from "@babel/helper-wrap-function";
5 import annotateAsPure from "@babel/helper-annotate-as-pure";
6 import environmentVisitor from "@babel/helper-environment-visitor";
7 import { traverse } from "@babel/core";
8 import {
9 callExpression,
10 cloneNode,
11 isIdentifier,
12 isThisExpression,
13 yieldExpression,
14 } from "@babel/types";
15 import type * as t from "@babel/types";
16
17 const awaitVisitor = traverse.visitors.merge<{ wrapAwait: t.Expression }>([
18 {
19 ArrowFunctionExpression(path) {
20 path.skip();
21 },
22
23 AwaitExpression(path, { wrapAwait }) {
24 const argument = path.get("argument");
25
26 path.replaceWith(
27 yieldExpression(
28 wrapAwait
29 ? callExpression(cloneNode(wrapAwait), [argument.node])
30 : argument.node,
31 ),
32 );
33 },
34 },
35 environmentVisitor,
36 ]);
37
38 export default function (
39 path: NodePath<t.Function>,
40 helpers: {
41 wrapAsync: t.Expression;
42 wrapAwait?: t.Expression;
43 },
44 noNewArrows?: boolean,
45 ignoreFunctionLength?: boolean,
46 ) {
47 path.traverse(awaitVisitor, {
48 wrapAwait: helpers.wrapAwait,
49 });
50
51 const isIIFE = checkIsIIFE(path);
52
53 path.node.async = false;
54 path.node.generator = true;
55
56 wrapFunction(
57 path,
58 cloneNode(helpers.wrapAsync),
59 noNewArrows,
60 ignoreFunctionLength,
61 );
62
63 const isProperty =
64 path.isObjectMethod() ||
65 path.isClassMethod() ||
66 path.parentPath.isObjectProperty() ||
67 path.parentPath.isClassProperty();
68
69 if (!isProperty && !isIIFE && path.isExpression()) {
70 annotateAsPure(path);
71 }
72
73 function checkIsIIFE(path: NodePath) {
74 if (path.parentPath.isCallExpression({ callee: path.node })) {
75 return true;
76 }
77
78 // try to catch calls to Function#bind, as emitted by arrowFunctionToExpression in spec mode
79 // this may also catch .bind(this) written by users, but does it matter? 🤔
80 const { parentPath } = path;
81 if (
82 parentPath.isMemberExpression() &&
83 isIdentifier(parentPath.node.property, { name: "bind" })
84 ) {
85 const { parentPath: bindCall } = parentPath;
86
87 // (function () { ... }).bind(this)()
88
89 return (
90 // first, check if the .bind is actually being called
91 bindCall.isCallExpression() &&
92 // and whether its sole argument is 'this'
93 bindCall.node.arguments.length === 1 &&
94 isThisExpression(bindCall.node.arguments[0]) &&
95 // and whether the result of the .bind(this) is being called
96 bindCall.parentPath.isCallExpression({ callee: bindCall.node })
97 );
98 }
99
100 return false;
101 }
102 }