Skip to content

Commit e8f638e

Browse files
committed
Implement the transformation as a PathVisitor.
1 parent 027ce57 commit e8f638e

File tree

1 file changed

+61
-0
lines changed

1 file changed

+61
-0
lines changed

visitor.js

+61
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
var recast = require("recast");
2+
var types = recast.types;
3+
var b = types.builders;
4+
5+
exports.visitFunction = function(path) {
6+
// Calling this.traverse(path) first makes for a post-order traversal.
7+
this.traverse(path);
8+
9+
var node = path.value;
10+
if (node.async) {
11+
node.async = false;
12+
} else {
13+
return;
14+
}
15+
16+
awaitVisitor.visit(path.get("body"));
17+
18+
var resultExpr = b.callExpression(
19+
b.memberExpression(
20+
this.getRuntime(),
21+
b.identifier("async"),
22+
false
23+
),
24+
[b.callExpression(
25+
b.functionExpression(
26+
null, // Anonymous.
27+
[], // No parameters.
28+
node.body, // Body without await.
29+
true, // Generator.
30+
node.expression
31+
),
32+
[] // Immediately invoked.
33+
)]
34+
);
35+
36+
if (node.expression) {
37+
node.body = resultExpr;
38+
} else {
39+
node.body = b.blockStatement([
40+
b.returnStatement(resultExpr)
41+
]);
42+
}
43+
};
44+
45+
exports.getRuntime = function() {
46+
return b.callExpression(
47+
b.identifier("require"),
48+
[b.literal("es7-async-await/runtime")]
49+
);
50+
};
51+
52+
var awaitVisitor = types.PathVisitor.fromMethodsObject({
53+
visitFunction: function(path) {
54+
return false; // Don't descend into nested function scopes.
55+
},
56+
57+
visitAwaitExpression: function(path) {
58+
// Convert await expressions to yield expressions.
59+
return b.yieldExpression(path.value.argument, false);
60+
}
61+
});

0 commit comments

Comments
 (0)