Rietveld Code Review Tool
Help | Bug tracker | Discussion group | Source code

Unified Diff: scripts/abprewrite.js

Issue 5417063522762752: Issue 427 - Desugar arrow functions to normal or bound functions (Closed)
Patch Set: I just decided to ignore eval and Function for now, I can open a new bug if we really want to ban t… Created May 18, 2014, 10:55 a.m.
Use n/p to move between diff chunks; N/P to move between comments.
Jump to:
View side-by-side diff with in-line comments
Download patch
« no previous file with comments | « autotest/test_abprewrite_module.js.expected ('k') | scripts/astDecompile.js » ('j') | no next file with comments »
Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
Index: scripts/abprewrite.js
===================================================================
--- a/scripts/abprewrite.js
+++ b/scripts/abprewrite.js
@@ -391,34 +391,18 @@ function modifyLetStatement(ast)
return ast;
}
function modifyFunctionExpression(ast)
{
if (ast.expression)
{
- // Convert expression closures:
- // function() foo;
- //
- // Change into:
- // function()
- // {
- // return foo;
- // }
- ast.expression = false;
- ast.body = {
- type: "BlockStatement",
- body: [
- {
- type: "ReturnStatement",
- argument: ast.body
- }
- ]
- };
+ print("Use arrow functions instead of function expressions!\n");
+ throw new Error("Use arrow functions instead of function expressions!");
}
if (ast.generator)
{
// Convert generators:
// function()
// {
// ...
@@ -454,16 +438,57 @@ function modifyFunctionExpression(ast)
return ast;
}
function modifyFunctionDeclaration(ast)
{
return modifyFunctionExpression(ast);
}
+function modifyArrowExpression(ast)
+{
+ if (ast.body.type != "BlockStatement") {
+ // Convert expressions to block statements.
+ // (a) => a + 1
+ //
+ // Change into:
+ // (a) => { return a + 1; }
+ ast.body = {
+ type: "BlockStatement",
+ body: [
+ {
+ type: "ReturnStatement",
+ argument: ast.body
+ }
+ ]
+ };
+ }
+
+ // Now convert the arrow expression into a normal
+ // function expression.
+ ast.type = "FunctionExpression";
+ ast.expression = false;
+
+ // We want to avoid the .bind call if |this| isn't actually used.
+ // This is not necessarily always correct, but should be good enough.
+ var body = decompileAST(ast.body);
+ if (/((\bthis\b)|=>)/.test(body)) {
+ return {
+ type: "CallExpression",
+ callee: Member(ast, "bind"),
+ arguments: [
+ {
+ type: "ThisExpression"
+ }
+ ]
+ };
+ }
+ return ast;
+}
+
function modifyYieldExpression(ast)
{
// Convert generators into functions returning arrays:
// yield "foo";
//
// Change into:
// _generatorResult44.push("foo");
« no previous file with comments | « autotest/test_abprewrite_module.js.expected ('k') | scripts/astDecompile.js » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld