Skip to content

Commit

Permalink
fix: Ensure correct scope references after traversal (#192)
Browse files Browse the repository at this point in the history
* test: Add tests illustrating scope issue
* fix: Re-crawl scope after traversal to fix references
  • Loading branch information
leebyron authored and coreyfarrell committed Feb 18, 2019
1 parent 8e827c6 commit 201a933
Show file tree
Hide file tree
Showing 5 changed files with 76 additions and 0 deletions.
2 changes: 2 additions & 0 deletions fixtures/with-changed-scope.js
@@ -0,0 +1,2 @@
import { noop } from 'lodash'
noop(noop() ? noop : noop)
19 changes: 19 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Expand Up @@ -18,6 +18,7 @@
"@babel/core": "^7.2.2",
"@babel/preset-env": "^7.2.3",
"@babel/register": "^7.0.0",
"babel-plugin-lodash": "^3.3.4",
"chai": "^4.2.0",
"coveralls": "^3.0.2",
"cross-env": "^5.2.0",
Expand Down
3 changes: 3 additions & 0 deletions src/index.js
Expand Up @@ -70,6 +70,9 @@ function makeVisitor ({ types: t }) {
inputSourceMap
})
this.__dv__.enter(path)
// Istanbul visitor may replace Identifiers and require re-crawling
// scope before continuing with other babel plugins.
path.scope.crawl()
},
exit (path) {
if (!this.__dv__) {
Expand Down
51 changes: 51 additions & 0 deletions test/babel-plugin-istanbul.js
Expand Up @@ -171,4 +171,55 @@ describe('babel-plugin-istanbul', function () {
resultAfter.code.should.match(/statementMap/)
})
})

describe('should leave scope with correct references', function () {
it('leaves scope references as Identifiers', function () {
// This is a unit test which inspects the root cause of the problem:
// scope references that are replaced to no longer be Identifiers
babel.transformFileSync('./fixtures/with-changed-scope.js', {
babelrc: false,
configFile: false,
plugins: [
[makeVisitor({ types: babel.types }), {
include: ['fixtures/with-changed-scope.js']
}],
function testScope (t) {
return {
visitor: {
ImportSpecifier (path) {
const fileScope = path.hub.file.scope
const localBinding = fileScope.getBinding(path.node.local.name)
for (const localReference of localBinding.referencePaths) {
localReference.type.should.equal('Identifier')
}
}
}
}
}
]
})
})

it('creates valid syntax with other transforming plugins', function () {
// This is a minimal end-to-end test which illustrates how scope
// reference alteration impacts the assumptions of other plugins
const result = babel.transformFileSync(
'./fixtures/with-changed-scope.js', {
babelrc: false,
configFile: false,
plugins: [
[makeVisitor({ types: babel.types }), {
include: ['fixtures/with-changed-scope.js']
}],
'babel-plugin-lodash'
]
})

function testSyntaxError () {
babel.parse(result.code)
}

testSyntaxError.should.not.throw()
})
})
})

0 comments on commit 201a933

Please sign in to comment.