| 1 |
import { declare } from "@babel/helper-plugin-utils"; |
| 2 |
import syntaxAsyncDoExpressions from "@babel/plugin-syntax-async-do-expressions"; |
| 3 |
import hoistVariables from "@babel/helper-hoist-variables"; |
| 4 |
import type * as t from "@babel/types"; |
| 5 |
|
| 6 |
export default declare(({ types: t, assertVersion }) => { |
| 7 |
assertVersion("^7.13.0"); |
| 8 |
|
| 9 |
return { |
| 10 |
name: "proposal-async-do-expressions", |
| 11 |
inherits: syntaxAsyncDoExpressions, |
| 12 |
visitor: { |
| 13 |
DoExpression: { |
| 14 |
exit(path) { |
| 15 |
if (!path.is("async")) { |
| 16 |
// non-async do expressions are handled by proposal-do-expressions |
| 17 |
return; |
| 18 |
} |
| 19 |
const { scope } = path; |
| 20 |
// Hoist variable declaration to containing function scope |
| 21 |
// `async do { var x = 1; x }` -> `var x; (async() => { x = 1; return x })()` |
| 22 |
hoistVariables( |
| 23 |
path, |
| 24 |
(id: t.Identifier) => { |
| 25 |
scope.push({ id: t.cloneNode(id) }); |
| 26 |
}, |
| 27 |
"var", |
| 28 |
); |
| 29 |
const bodyPath = path.get("body"); |
| 30 |
|
| 31 |
// add implicit returns to all ending expression statements |
| 32 |
const completionRecords = bodyPath.getCompletionRecords(); |
| 33 |
|
| 34 |
for (const p of completionRecords) { |
| 35 |
if (p.isExpressionStatement()) { |
| 36 |
p.replaceWith(t.returnStatement(p.node.expression)); |
| 37 |
} |
| 38 |
} |
| 39 |
|
| 40 |
path.replaceWith( |
| 41 |
t.callExpression( |
| 42 |
t.arrowFunctionExpression([], bodyPath.node, /* async */ true), |
| 43 |
[], |
| 44 |
), |
| 45 |
); |
| 46 |
}, |
| 47 |
}, |
| 48 |
}, |
| 49 |
}; |
| 50 |
}); |