Skip to content

Commit

Permalink
fix(smart-inline): fix missing renaming in property descturing
Browse files Browse the repository at this point in the history
closes #117
  • Loading branch information
pionxzh committed Feb 16, 2024
1 parent 86469e7 commit 55e2938
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -250,6 +250,25 @@ function foo() {
`,
)

inlineTest('property destructuring - consecutive assignments',
`
const t = s.target;
const p = t.parentElement;
const v = p.value;
`,
`
const {
target
} = s;
const {
parentElement
} = target;
const {
value
} = parentElement;
`,
)

inlineTest('array destructuring',
`
const t = e[0];
Expand Down
11 changes: 9 additions & 2 deletions packages/unminify/src/transformations/smart-inline.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { mergeComments } from '@wakaru/ast-utils/comments'
import { generateName } from '@wakaru/ast-utils/identifier'
import { createObjectProperty } from '@wakaru/ast-utils/object'
import { findReferences } from '@wakaru/ast-utils/reference'
import { findReferences, renameIdentifier } from '@wakaru/ast-utils/reference'
import { MultiMap } from '@wakaru/ds'
import { nonNullable } from '@wakaru/shared/array'
import { createJSCodeshiftTransformationRule } from '@wakaru/shared/rule'
Expand Down Expand Up @@ -218,7 +218,12 @@ function handleDestructuring(j: JSCodeshift, body: StatementKind[], scope: Scope
body.splice(insertIndex, 0, destructuring)
})

const renameMap = new Map<string, string>()
objectAccessDeclarationMap.forEach((declarations, objectName) => {
if (renameMap.has(objectName)) {
objectName = renameMap.get(objectName)!
}

// Rename all variables to their property names
let insertIndex = body.length
const destructuringPropertyMap = new Map<string, string>()
Expand Down Expand Up @@ -252,7 +257,8 @@ function handleDestructuring(j: JSCodeshift, body: StatementKind[], scope: Scope

const newPropertyName = destructuringPropertyMap.get(propertyName)
|| generateName(propertyName, scope, declaredNames)
scope.rename(variableName, newPropertyName)
renameIdentifier(j, scope, variableName, newPropertyName)
renameMap.set(variableName, newPropertyName)
// TODO: should we move this into `scope.rename`?
scope.markAsStale()
destructuringPropertyMap.set(propertyName, newPropertyName)
Expand All @@ -270,6 +276,7 @@ function handleDestructuring(j: JSCodeshift, body: StatementKind[], scope: Scope
const kinds = [...destructuringPropertyMap.keys()].map(n => variableKindMap.get(n)).filter(nonNullable)
const kind = getMostRestrictiveKind(kinds)
if (!kind) return

const properties = [...destructuringPropertyMap.entries()]
.map(([propertyName, newPropertyName]) => {
const property = createObjectProperty(j, propertyName, j.identifier(newPropertyName))
Expand Down

0 comments on commit 55e2938

Please sign in to comment.