Skip to content

Commit

Permalink
Fix compilation of parameters in async generators
Browse files Browse the repository at this point in the history
  • Loading branch information
nicolo-ribaudo committed Nov 5, 2022
1 parent ce09a26 commit 4a751b8
Show file tree
Hide file tree
Showing 4 changed files with 53 additions and 19 deletions.
24 changes: 17 additions & 7 deletions packages/babel-plugin-transform-parameters/src/params.ts
Expand Up @@ -154,7 +154,8 @@ export default function convertFunctionParams(
// ensure it's a block, useful for arrow functions
path.ensureBlock();

if (state.needsOuterBinding || shadowedParams.size > 0 || node.generator) {
const { async, generator } = node;
if (generator || state.needsOuterBinding || shadowedParams.size > 0) {
body.push(buildScopeIIFE(shadowedParams, path.node.body));

path.set("body", t.blockStatement(body as t.Statement[]));
Expand All @@ -169,12 +170,21 @@ export default function convertFunctionParams(
// This is an IIFE, so we don't need to worry about the noNewArrows assumption
arrowPath.arrowFunctionToExpression();

arrowPath.node.generator = path.node.generator;
arrowPath.node.async = path.node.async;

// We don't reset "async" because if the default value of a parameter
// throws, it must reject asynchronously.
path.node.generator = false;
arrowPath.node.generator = generator;
arrowPath.node.async = async;

node.generator = false;
node.async = false;
// If the default value of a parameter throws, it must reject asynchronously.
if (async) {
path.node.body = template.statement.ast`{
try {
${path.node.body.body}
} catch (e) {
return Promise.reject(e);
}
}` as t.BlockStatement;
}
} else {
path.get("body").unshiftContainer("body", body);
}
Expand Down
@@ -0,0 +1,10 @@
async function * foo (p = 1) {
yield "hello";
yield p;
}

return (async () => {
const res = [];
for await (const x of foo()) res.push(x);
expect(res).toEqual(["hello", 1]);
})();
@@ -0,0 +1,6 @@
{
"plugins": ["transform-parameters"],
"parserOpts": {
"allowReturnOutsideFunction": true
}
}
Expand Up @@ -5,17 +5,25 @@ function f() {
return a;
}(a);
}
async function g() {
let a = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 1;
return async function (a) {
var a = await a;
return a;
}(a);
function g() {
try {
let a = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 1;
return async function (a) {
var a = await a;
return a;
}(a);
} catch (e) {
return Promise.reject(e);
}
}
async function h() {
let a = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 1;
return async function* (a) {
var a = await (yield a);
return a;
}(a);
function h() {
try {
let a = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 1;
return async function* (a) {
var a = await (yield a);
return a;
}(a);
} catch (e) {
return Promise.reject(e);
}
}

0 comments on commit 4a751b8

Please sign in to comment.