diff options
author | Florian Dold <florian.dold@gmail.com> | 2016-10-04 11:50:26 +0200 |
---|---|---|
committer | Florian Dold <florian.dold@gmail.com> | 2016-10-04 11:50:26 +0200 |
commit | 30b577138dda685f65a8529be1866afa6e321845 (patch) | |
tree | bfa92ee3ab485a6b11f86731777ecf5c5d166bab /config/codemod-strip-tdz.js |
Squashed 'thirdparty/preact/' content from commit b2d90cc
git-subtree-dir: thirdparty/preact
git-subtree-split: b2d90cc116f1d1998f7a7c98dc6986bf4c1841f4
Diffstat (limited to 'config/codemod-strip-tdz.js')
-rw-r--r-- | config/codemod-strip-tdz.js | 56 |
1 files changed, 56 insertions, 0 deletions
diff --git a/config/codemod-strip-tdz.js b/config/codemod-strip-tdz.js new file mode 100644 index 000000000..a1f07fafe --- /dev/null +++ b/config/codemod-strip-tdz.js @@ -0,0 +1,56 @@ +/* eslint no-console:0 */ + + +// parent node types that we don't want to remove pointless initializations from (because it breaks hoisting) +const BLOCKED = ['ForStatement', 'WhileStatement']; // 'IfStatement', 'SwitchStatement' + +/** Removes var initialization to `void 0`, which Babel adds for TDZ strictness. */ +export default (file, api) => { + let { jscodeshift } = api, + found = 0; + + let code = jscodeshift(file.source) + .find(jscodeshift.VariableDeclaration) + .forEach(handleDeclaration); + + function handleDeclaration(decl) { + let p = decl, + remove = true; + + while ((p = p.parentPath)) { + if (~BLOCKED.indexOf(p.value.type)) { + remove = false; + break; + } + } + + decl.value.declarations.filter(isPointless).forEach( node => { + if (remove===false) { + console.log(`> Skipping removal of undefined init for "${node.id.name}": within ${p.value.type}`); + } + else { + removeNodeInitialization(node); + } + }); + } + + function removeNodeInitialization(node) { + node.init = null; + found++; + } + + function isPointless(node) { + let { init } = node; + if (init) { + if (init.type==='UnaryExpression' && init.operator==='void' && init.argument.value==0) { + return true; + } + if (init.type==='Identifier' && init.name==='undefined') { + return true; + } + } + return false; + } + + return found ? code.toSource({ quote: 'single' }) : null; +}; |