Skip to content

Commit

Permalink
fix(placeholders): improve argument hoist logic
Browse files Browse the repository at this point in the history
Previous hoist logic would hoist too far and could drop the lifted paths before the declarations they use, causing `ReferenceError`s.
  • Loading branch information
citycide committed Dec 4, 2017
1 parent 23e1dab commit dfffd97
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 11 deletions.
24 changes: 18 additions & 6 deletions dist/util.js
Original file line number Diff line number Diff line change
Expand Up @@ -60,14 +60,26 @@ function findWrapper(path, noCallee) {
}

function hoistArguments(t, caller) {
const args = caller.get('body.body.0.argument.arguments');
var _args;

let args, upper;

if (caller.isArrowFunctionExpression()) {
args = caller.get('body.body.0.argument.arguments');
upper = caller.getStatementParent();
} else if (caller.isCallExpression()) {
args = caller.get('arguments');
upper = caller.findParent(_it2 => {
return _it2.isArrowFunctionExpression();
}).getStatementParent();
}

if (!((_args = args) === null || _args === void 0 ? void 0 : _args.length)) return;
args.forEach(arg => {
if (!shouldHoist(arg)) return;
const id = arg.scope.generateUidIdentifier('ref');
caller.scope.parent.push({
id,
init: arg.node
});
const id = upper.scope.generateUidIdentifier('ref');
const ref = t.variableDeclaration('const', [t.variableDeclarator(id, arg.node)]);
upper.insertBefore(ref);
arg.replaceWith(id);
});
}
Expand Down
20 changes: 17 additions & 3 deletions src/util.js
Original file line number Diff line number Diff line change
Expand Up @@ -51,13 +51,27 @@ export function findWrapper (path, noCallee) {
}

export function hoistArguments (t, caller) {
const args = caller.get('body.body.0.argument.arguments')
let args, upper
if (caller.isArrowFunctionExpression()) {
args = caller.get('body.body.0.argument.arguments')
upper = caller.getStatementParent()
} else if (caller.isCallExpression()) {
args = caller.get('arguments')
upper = caller
.findParent(it.isArrowFunctionExpression())
.getStatementParent()
}

if (!args?.length) return

args.forEach(arg => {
if (!shouldHoist(arg)) return

const id = arg.scope.generateUidIdentifier('ref')
caller.scope.parent.push({ id, init: arg.node })
const id = upper.scope.generateUidIdentifier('ref')
const ref = t.variableDeclaration('const', [
t.variableDeclarator(id, arg.node)
])
upper.insertBefore(ref)
arg.replaceWith(id)
})
}
Expand Down
5 changes: 3 additions & 2 deletions test.js
Original file line number Diff line number Diff line change
Expand Up @@ -199,8 +199,9 @@ test(
const log = console.log(_, {}, foo(), new Person(), 2, _.bar())
`,
$`
var _ref = foo(),
_ref2 = new Person();
const _ref = foo();
const _ref2 = new Person();
const log = (_arg, _arg2) => {
return console.log(_arg, {}, _ref, _ref2, 2, _arg2.bar());
Expand Down

0 comments on commit dfffd97

Please sign in to comment.