Skip to content

Commit

Permalink
fix: only hoist counter for a smaller subset of function declarations
Browse files Browse the repository at this point in the history
  • Loading branch information
Benjamin Coe committed Jan 4, 2017
1 parent 4fe4dca commit 9f8931e
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 2 deletions.
8 changes: 6 additions & 2 deletions src/visitor.js
Original file line number Diff line number Diff line change
Expand Up @@ -145,11 +145,15 @@ class VisitState {
} else if (path.isStatement()) {
path.insertBefore(T.expressionStatement(increment));
} else if ((path.isFunctionExpression() || path.isArrowFunctionExpression()) && T.isVariableDeclarator(path.parentPath)) {
const parent = path.findParent((path) => path.parentPath.isProgram());
if (parent) {
// make an attempt to hoist the statement counter, so that
// function names are maintained.
const parent = path.parentPath.parentPath;
if (parent && (T.isProgram(parent.parentPath) || T.isBlockStatement(parent.parentPath))) {
parent.insertBefore(T.expressionStatement(
increment
));
} else {
path.replaceWith(T.sequenceExpression([increment, path.node]));
}
} else /* istanbul ignore else: not expected */ if (path.isExpression()) {
path.replaceWith(T.sequenceExpression([increment, path.node]));
Expand Down
36 changes: 36 additions & 0 deletions test/specs/functions.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -110,3 +110,39 @@ tests:
functions: {'0': 0, '1': 0}
statements: {'0': 1, '1': 1, '2': 1}
guard: isInferredFunctionNameAvailable


---
name: function declaration assignment name (top-level)
guard: isInferredFunctionNameAvailable
code: |
const foo = function() {}
var bar = function() {}
output = foo.name + ' ' + bar.name;
tests:
- name: properly sets function name
out: 'foo bar'
lines: {'1': 1, '2': 1, '3': 1}
functions: {'0': 0, '1': 0}
statements: {'0': 1, '1': 1, '2': 1}
guard: isInferredFunctionNameAvailable

---
name: function declaration assignment name (in function)
guard: isInferredFunctionNameAvailable
code: |
function a () {
const foo = function () {}
}
function b () {
const bar = function () {}
return bar.name
}
output = b()
tests:
- name: properly sets function name
out: 'bar'
lines: {'2': 0, '5': 1, '6': 1, '8': 1}
functions: {'0': 0, '1': 0, '2': 1, '3': 0}
statements: {'0': 0, '1': 1, '2': 1, '3': 1}
guard: isInferredFunctionNameAvailable

0 comments on commit 9f8931e

Please sign in to comment.