Skip to content

fix(visitors): asynchronize callback having no param other than error #249

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

Merged
merged 1 commit into from
Jul 3, 2020
Merged
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
3 changes: 3 additions & 0 deletions src/functionTypes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,9 @@ export function getNames<T>(path: u.NodePath<T>): string[] {
Identifier(path) {
names.push(path.node.name);
},
Statement(path) {
path.skip();
},
});
return uniq(names);
}
Expand Down
1 change: 0 additions & 1 deletion src/visitors/asynchronize/asynchronous.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,5 @@ export function fetchAsynchronous(

path.replaceWith(u.awaitExpression(node));

path.skip();
return true;
}
130 changes: 73 additions & 57 deletions src/visitors/asynchronize/errorFirstCallback.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,65 +4,80 @@ import { BaseState } from '../../state';
import { isErrorFirstCallback } from '../../types';
import * as u from '../../util';

type FunctionParameter = u.Identifier | u.RestElement | u.TSParameterProperty;

function isFunctionParameter(node: u.Node): node is FunctionParameter {
return (
u.isIdentifier(node) ||
u.isRestElement(node) ||
u.isTSParameterProperty(node)
);
}

export function fetchErrorFirstCallback(
path: u.NodePath<u.VariableDeclaration>,
path: u.NodePath<u.CallExpression>,
asynchronized: u.Node[],
state: BaseState,
): boolean {
const { node } = path;
const { declarations } = node;
if (declarations.length !== 1) {
const { node: original } = path;
const names = getNames(path.get('callee'));
const entry = state.escapin.types.get(...names);
if (!isErrorFirstCallback(entry)) {
return false;
}

const { id, init } = declarations[0];
asynchronized.push(original);

if (u.isIdentifier(id) && u.isIdentifier(init)) {
const entry = state.escapin.types.get(init.name);
const args: FunctionParameter[] = [u.identifier('err')];

if (entry && state.escapin.types.get(id.name) === undefined) {
state.escapin.types.put({ names: [id.name], type: entry.type });
}
return false;
}

if (
!u.isCallExpression(init) ||
u.test(path, path => u.isIdentifier(path.node, { name: 'Promise' }))
) {
return false;
}
const declPath = path.findParent(path =>
u.isVariableDeclaration(path.node),
) as u.NodePath<u.VariableDeclaration>;

const names = getNames(path.get('declarations.0.init.callee') as u.NodePath);
const entry = state.escapin.types.get(...names);
if (!isErrorFirstCallback(entry)) {
return false;
if (declPath === null) {
original.arguments.push(
u.parseExpression(
'err => { if (err) { reject(err); } else { resolve(); } }',
),
);
path.replaceWith(
u.awaitExpression(
u.expression('new Promise((resolve, reject) => {$ORIGINAL})', {
$ORIGINAL: u.expressionStatement(original),
}),
),
);
return true;
}

asynchronized.push(node);

const data = path.scope.generateUidIdentifier('data');
const args = [u.identifier('err')];
const { node } = declPath;
const { declarations } = node;
const { id } = declarations[0];

let newId!: u.Node;
if (u.isObjectPattern(id)) {
for (const property of id.properties) {
if (u.isRestElement(property)) {
continue;
let param!: FunctionParameter;
if (u.isObjectProperty(property)) {
const { key } = property;
if (!isFunctionParameter(key)) {
throw new EscapinSyntaxError('Unsupported type', id, state);
}
param = key;
u.replace(
declPath.parentPath,
param,
u.memberExpression(data, param),
path =>
path.isObjectProperty() ||
path.isMemberExpression() ||
path.isFunction(node),
);
} else if (u.isRestElement(property)) {
param = property;
}
const { key } = property;
if (!u.isIdentifier(key)) {
continue;
}
args.push(key);
u.replace(
path.parentPath,
key,
u.memberExpression(data, key),
path =>
path.isObjectProperty() ||
path.isMemberExpression() ||
path.isFunction(node),
);
args.push(param);
}
newId = u.objectExpression(
id.properties.map(prop =>
Expand All @@ -73,35 +88,36 @@ export function fetchErrorFirstCallback(
);
} else if (u.isIdentifier(id)) {
args.push(id);
u.replace(path.parentPath, id, data);
u.replace(declPath.parentPath, id, data);
} else {
throw new EscapinSyntaxError('Unsupported type', id, state);
}
declarations[0].id = data;
const callback = u.arrowFunctionExpression(
args,
u.blockStatement(
u.statements('if (err) { reject(err); } else { resolve($DATA); }', {
$DATA: newId || id,
}),

original.arguments.push(
u.arrowFunctionExpression(
args,
u.blockStatement(
u.statements('if (err) { reject(err); } else { resolve($DATA); }', {
$DATA: newId || id,
}),
),
),
);
init.arguments.push(callback);

declarations[0].init = u.awaitExpression(
u.expression('new Promise((resolve, reject) => {$INIT})', {
$INIT: u.expressionStatement(init),
const modified = u.awaitExpression(
u.expression('new Promise((resolve, reject) => {$ORIGINAL})', {
$ORIGINAL: u.expressionStatement(original),
}),
);

path.replaceWith(modified);
if (
!u.test(
path.parentPath,
declPath.parentPath,
path => u.equals(path.node, data),
path => path.node === node,
)
) {
path.replaceWith(u.expressionStatement(declarations[0].init));
declPath.replaceWith(u.expressionStatement(modified));
}
return true;
}
2 changes: 0 additions & 2 deletions src/visitors/asynchronize/generalCallback.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,6 @@ export function fetchGeneralCallback(
});

if (!asyncRequired) {
path.skip();
return true;
}

Expand Down Expand Up @@ -83,6 +82,5 @@ export function fetchGeneralCallback(
state.addDependency('deasync');
break;
}
path.skip();
return true;
}
50 changes: 18 additions & 32 deletions src/visitors/asynchronize/index.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
import { Visitor } from '@babel/traverse';
import { getNames } from '../../functionTypes';
import { BaseState } from '../../state';
import { asynchronous } from '../../types';
import * as u from '../../util';
import { fetchAsynchronous } from './asynchronous';
import { fetchErrorFirstCallback } from './errorFirstCallback';
import { fetchGeneralCallback } from './generalCallback';
import { EscapinSyntaxError } from '../../error';

function newVisitor(): Visitor<BaseState> {
const asynchronized: u.Node[] = [];
Expand All @@ -15,35 +18,30 @@ function newVisitor(): Visitor<BaseState> {
},
exit(path, state): void {
if (changed) {
path.traverse(visitor, state);
u.traverse(visitor, state);
}
},
},
Function(path): void {
Function(path, state): void {
const { node } = path;
if (asynchronized.includes(node)) {
path.skip();
return;
}

if (
!(
u.test<u.Function>(path, path => path.isAwaitExpression()) &&
!node.async
)
!u.test<u.Function>(path, path => path.isAwaitExpression()) ||
node.async
) {
return;
}

const parent = path.parentPath.node;

if (u.isCallExpression(parent) && parent.callee !== node) {
return;
}
node.async = true;
const stmtPath = (path.isFunctionDeclaration()
? path
: path.findParent(path => u.isStatement(path.node))) as u.NodePath;
const names = getNames(stmtPath);
const entry = asynchronous(...names);
console.log(entry);
state.escapin.types.put(entry);

asynchronized.push(node);

node.async = true;
changed = true;
},
CallExpression(path, state): void {
Expand All @@ -53,6 +51,7 @@ function newVisitor(): Visitor<BaseState> {
}

const done =
fetchErrorFirstCallback(path, asynchronized, state) ||
fetchGeneralCallback(path, asynchronized, state) ||
fetchAsynchronous(path, asynchronized, state);

Expand All @@ -61,7 +60,7 @@ function newVisitor(): Visitor<BaseState> {
path.skip();
}
},
For(path): void {
For(path, state): void {
if (asynchronized.includes(path.node)) {
path.skip();
return;
Expand All @@ -79,7 +78,7 @@ function newVisitor(): Visitor<BaseState> {
for (const declarator of decl.node.declarations) {
const { id } = declarator;
if (!u.isIdentifier(id)) {
continue;
throw new EscapinSyntaxError('Unsupported type', id, state);
}
declarator.id = path.scope.generateUidIdentifier(id.name);
u.replace<u.For>(path, id, declarator.id);
Expand Down Expand Up @@ -116,19 +115,6 @@ function newVisitor(): Visitor<BaseState> {
changed = true;
path.skip();
},
VariableDeclaration(path, state): void {
if (asynchronized.includes(path.node)) {
path.skip();
return;
}

const done = fetchErrorFirstCallback(path, asynchronized, state);

if (done) {
changed = true;
path.skip();
}
},
};

return visitor;
Expand Down
38 changes: 26 additions & 12 deletions src/visitors/uncallbackify.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,18 +54,32 @@ const visitor: Visitor<BaseState> = {

callbackPath.remove();

stmtPath.replaceWith(
u.statement(
'try { const $OBJ = $FUNC; $CONSEQUENT; } catch ($ERROR) { $ALTERNATE; }',
{
$ALTERNATE: alternate,
$CONSEQUENT: consequent,
$ERROR: errorParam.node,
$FUNC: path.node,
$OBJ: getObjectPattern(params, state),
},
),
);
if (params.length > 0) {
stmtPath.replaceWith(
u.statement(
'try { const $OBJ = $FUNC; $CONSEQUENT; } catch ($ERROR) { $ALTERNATE; }',
{
$ALTERNATE: alternate,
$CONSEQUENT: consequent,
$ERROR: errorParam.node,
$FUNC: path.node,
$OBJ: getObjectPattern(params, state),
},
),
);
} else {
stmtPath.replaceWith(
u.statement(
'try { $FUNC; $CONSEQUENT; } catch ($ERROR) { $ALTERNATE; }',
{
$ALTERNATE: alternate,
$CONSEQUENT: consequent,
$ERROR: errorParam.node,
$FUNC: path.node,
},
),
);
}
},
};

Expand Down
Loading