Skip to content

Commit

Permalink
fix(un-variable-merging): should not split varaible declration in for…
Browse files Browse the repository at this point in the history
… init that was actually used
  • Loading branch information
pionxzh committed Jul 13, 2024
1 parent 22ad078 commit acd9379
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 8 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -59,12 +59,20 @@ inlineTest('variable declaration that is not used in for statement should not be
for (var i = 0, j = 0, k = 0; j < 10; k++) {
console.log(k);
}
for (var _len = arguments.length, _arguments = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
_arguments[_key - 2] = arguments[_key];
}
`,
`
var i = 0;
for (var j = 0, k = 0; j < 10; k++) {
console.log(k);
}
for (var _len = arguments.length, _arguments = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
_arguments[_key - 2] = arguments[_key];
}
`,
)

Expand Down
15 changes: 7 additions & 8 deletions packages/unminify/src/transformations/un-variable-merging.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { mergeComments } from '@wakaru/ast-utils/comments'
import { replaceWithMultipleStatements } from '@wakaru/ast-utils/insert'
import { findReferences } from '@wakaru/ast-utils/reference'
import { createJSCodeshiftTransformationRule } from '@wakaru/shared/rule'
import type { ASTTransformation } from '@wakaru/shared/rule'
import type { ForStatement } from 'jscodeshift'
Expand Down Expand Up @@ -32,23 +33,21 @@ export const transformAST: ASTTransformation = (context) => {
.find(j.VariableDeclaration)
.forEach((p) => {
if (j.ForStatement.check(p.parent.node)) {
const { init, test, update } = p.parent.node as ForStatement
const { init } = p.parent.node as ForStatement
if (init && j.VariableDeclaration.check(init) && init.kind === 'var') {
const initDeclarators = init.declarations
// filter out the declarations that are used in test or update
const usedDeclarators = initDeclarators.filter((d) => {
if (!j.VariableDeclarator.check(d)) return false
const usedDeclarators = initDeclarators.filter((declarator) => {
if (!j.VariableDeclarator.check(declarator)) return false

const { id } = d
const { id } = declarator
if (!j.Identifier.check(id)) return false

// check if the name is declared outside of the for statement
if (p.parent?.parent?.scope.lookup(id.name)) return true

const name = id.name
const isUsedInTest = test && j(test).find(j.Identifier, { name }).size() > 0
const isUsedInUpdate = update && j(update).find(j.Identifier, { name }).size() > 0
if (isUsedInTest || isUsedInUpdate) return true
const isUsed = findReferences(j, p.parent, id.name).size() > 1
if (isUsed) return true

return false
})
Expand Down

0 comments on commit acd9379

Please sign in to comment.