Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support Async/Await based on #12 #125

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 47 additions & 0 deletions src/program/BlockStatement.js
Original file line number Diff line number Diff line change
Expand Up @@ -176,6 +176,53 @@ export default class BlockStatement extends Node {

super.transpile(code, transforms);

if (transforms.asyncAwait && this.isFunctionBlock && this.parent.async && this.body.length) {
const first = this.body[0];
const last = this.body[this.body.length - 1];
const hasOnlyOneLine = this.body.length === 1;

// TODO refactor :)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Refactor how? Who wrote this comment?

Better refactor now before merging, as later it will most likely not ever be refactored.

if (this.parent.type === 'FunctionDeclaration') {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This does not handle FunctionExpressions.

if (hasOnlyOneLine) {
if (first.type === 'ReturnStatement') {
code.insertLeft(first.argument.start, 'Promise.resolve().then(function() { ');
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

insertLeft has been replaced by appendLeft.

code.insertLeft(first.end, ' })');
} else {
code.insertLeft(first.start, 'return Promise.resolve().then(function() { ');
code.insertRight(last.end, ' }).then(function() {})');
}
} else {
code.insertLeft(first.start, 'return Promise.resolve()');
code.insertRight(last.end, '.then(function() {})');

for (let i = 0; i < this.body.length; i++) {
const prev = this.body[i - 1];
const cur = this.body[i];
const next = this.body[i + 1];

if (cur.expression.type === 'AwaitExpression') {
code.insertLeft(cur.start, '.then(function() { ');
code.insertRight(cur.end, ' })');
} else {
if (!prev || prev.expression.type === 'AwaitExpression') {
code.insertLeft(cur.start, '.then(function() { ');
}

if (!next || next.expression.type === 'AwaitExpression') {
code.insertRight(cur.end, ' })');
}
}
}
}

} else if (this.parent.type === 'ArrowFunctionExpression') {
// TODO merge with ^
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

TODOs should be new issues IMO, and not included in the code.

// wrap the function's body in a promise
code.insertLeft(first.start + 1, 'Promise.resolve().then(function() { return ');
code.insertLeft(last.end, ' })');
}
}

if (this.createdDeclarations.length) {
introStatementGenerators.push((start, prefix, suffix) => {
const assignment = `${prefix}var ${this.createdDeclarations.join(', ')}${suffix}`;
Expand Down
3 changes: 3 additions & 0 deletions src/program/types/ArrowFunctionExpression.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import Node from '../Node.js';
import CompileError from '../../utils/CompileError.js';
import removeTrailingComma from '../../utils/removeTrailingComma.js';
import AwaitExpression from './AwaitExpression';

export default class ArrowFunctionExpression extends Node {
initialise(transforms) {
Expand All @@ -22,6 +23,7 @@ export default class ArrowFunctionExpression extends Node {
}
code.remove(charIndex, this.body.start);

AwaitExpression.removeAsync(code, transforms, this.async, this.start);
super.transpile(code, transforms);

// wrap naked parameter
Expand All @@ -38,6 +40,7 @@ export default class ArrowFunctionExpression extends Node {
code.prependRight(this.start, 'function ');
}
} else {
AwaitExpression.removeAsync(code, transforms, this.async, this.start);
super.transpile(code, transforms);
}

Expand Down
19 changes: 14 additions & 5 deletions src/program/types/AwaitExpression.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,20 @@
import Node from '../Node.js';
import CompileError from '../../utils/CompileError.js';

const noop = () => {};

export default class AwaitExpression extends Node {
initialise(transforms) {
if (transforms.asyncAwait) {
CompileError.missingTransform("await", "asyncAwait", this);
static removeAsync(code, transforms, async, start, callback = noop) {
if (transforms.asyncAwait && async) {
code.remove(start, start + 6);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Magic number 6 is mysterious here. Better as named variable, or with a comment?

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

could this be "async ".length?

callback();
}
super.initialise(transforms);
}

transpile (code, transforms) {
AwaitExpression.removeAsync(code, transforms, true, this.start, () => {
code.insertLeft(this.argument.start, 'return ');
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This handles the expression as though it was a statement. See for example async () => await 1 + await 2.

});

super.transpile(code, transforms);
}
}
2 changes: 2 additions & 0 deletions src/program/types/FunctionDeclaration.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import Node from '../Node.js';
import CompileError from '../../utils/CompileError.js';
import removeTrailingComma from '../../utils/removeTrailingComma.js';
import AwaitExpression from './AwaitExpression';

export default class FunctionDeclaration extends Node {
initialise(transforms) {
Expand All @@ -20,6 +21,7 @@ export default class FunctionDeclaration extends Node {
}

transpile(code, transforms) {
AwaitExpression.removeAsync(code, transforms, this.async, this.start);
super.transpile(code, transforms);
if (transforms.trailingFunctionCommas && this.params.length) {
removeTrailingComma(code, this.params[this.params.length - 1].end);
Expand Down
25 changes: 25 additions & 0 deletions test/samples/async-await.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
module.exports = [
{
description: 'transpiles await arrow function call',
input: `async () => await a()`,
output: `!function() { return Promise.resolve().then(function() { return a() }); }`
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What's the point of !function? Just to draw attention that it's not being used?

Copy link

@maxmilton maxmilton Aug 31, 2018

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It turns it from a function declaration into an expression, see: https://stackoverflow.com/questions/3755606/what-does-the-exclamation-mark-do-before-the-function

As for why I'm not entirely sure.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The input is a function expression, too.

},

{
description: 'transpiles await function call',
input: `async function f() { await a(); }`,
output: `function f() { return Promise.resolve().then(function() { return a(); }).then(function() {}) }`
},

{
description: 'transpiles await function call with return statement',
input: `async function f() { return await a(); }`,
output: `function f() { return Promise.resolve().then(function() { return a(); }) }`
},

{
description: 'transpiles await function call with more than one line of code',
input: `async function f() { await a(); thing(); await a2(); stuff(); await a3(); await a4(); }`,
output: `function f() { return Promise.resolve().then(function() { return a(); }) .then(function() { thing(); }) .then(function() { return a2(); }) .then(function() { stuff(); }) .then(function() { return a3(); }) .then(function() { return a4(); }).then(function() {}) }`
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

there is not test that verifies return values and closures

	{
		description: 'transpiles await function call with normal return statement',
		input: `async function f() { var x = 1; await a(); return x; }`,
        output: `...`
	},

];