Skip to content

Commit

Permalink
Prevent multiple return statements in a loop when replacing expressions
Browse files Browse the repository at this point in the history
  • Loading branch information
existentialism committed Feb 4, 2017
1 parent 8c3392f commit 9c46fd6
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 4 deletions.
@@ -0,0 +1,10 @@
let p
let a = do {
while (p = p.parentPath) {
if (a) {
'a'
} else {
'b'
}
}
};
@@ -0,0 +1,13 @@
let p;
let a = function () {
var _ret;

while (p = p.parentPath) {
if (a) {
_ret = 'a';
} else {
_ret = 'b';
}
}
return _ret;
}();
14 changes: 10 additions & 4 deletions packages/babel-traverse/src/path/replacement.js
Expand Up @@ -219,10 +219,16 @@ export function replaceExpressionWithStatements(nodes: Array<Object>) {

const loop = path.findParent((path) => path.isLoop());
if (loop) {
const callee = this.get("callee");

const uid = callee.scope.generateDeclaredUidIdentifier("ret");
callee.get("body").pushContainer("body", t.returnStatement(uid));
let uid = loop.getData("expressionReplacementReturnUid");

if (!uid) {
const callee = this.get("callee");
uid = callee.scope.generateDeclaredUidIdentifier("ret");
callee.get("body").pushContainer("body", t.returnStatement(uid));
loop.setData("expressionReplacementReturnUid", uid);
} else {
uid = t.identifier(uid.name);
}

path.get("expression").replaceWith(
t.assignmentExpression("=", uid, path.node.expression)
Expand Down

0 comments on commit 9c46fd6

Please sign in to comment.