Skip to content

Commit

Permalink
fix: conflict detection of unreferenced binding and assignments
Browse files Browse the repository at this point in the history
  • Loading branch information
j4k0xb committed Feb 17, 2024
1 parent 270d05a commit 16f575f
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 11 deletions.
9 changes: 6 additions & 3 deletions packages/webcrack/src/ast-utils/rename.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ import * as m from '@codemod/matchers';
import { codePreview } from './generator';

export function renameFast(binding: Binding, newName: string): void {
if (binding.scope.hasBinding(newName)) binding.scope.rename(newName);

binding.referencePaths.forEach((ref) => {
if (!ref.isIdentifier()) {
throw new Error(
Expand Down Expand Up @@ -62,9 +64,10 @@ export function renameFast(binding: Binding, newName: string): void {
*/
export function renameCarefully(binding: Binding, newName: string): void {
const hasConflicts = () =>
binding.referencePaths.some((referencePath) =>
referencePath.scope.hasBinding(newName),
);
binding.scope.hasBinding(newName) ||
binding.referencePaths.some((ref) => ref.scope.hasBinding(newName)) ||
binding.constantViolations.some((ref) => ref.scope.hasBinding(newName));

if (!t.isValidIdentifier(newName) || hasConflicts()) {
newName = binding.scope.generateUid(newName);
}
Expand Down
14 changes: 14 additions & 0 deletions packages/webcrack/src/ast-utils/test/rename.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,20 @@ describe('rename variable', () => {
`);
});

test('conflict with existing binding 2', () => {
const ast = parse('let a = 1; let b = 2;');
traverse(ast, {
Program(path) {
const binding = path.scope.getBinding('a')!;
renameFast(binding, 'b');
},
});
expect(ast).toMatchInlineSnapshot(`
let b = 1;
let _b = 2;
`);
});

test('duplicate function binding', () => {
const ast = parse('var a; function a() {}');
traverse(ast, {
Expand Down
18 changes: 10 additions & 8 deletions packages/webcrack/src/unminify/test/rename-destructuring.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,30 +24,32 @@ test('rename object destructuring', () =>
test('rename object destructuring with conflict', () =>
expectJS(`
const gql = 1;
const {
gql: t,
dispatchers: o,
listener: i
} = n;
function foo({
gql: t,
dispatchers: o,
listener: i
}, {
gql: a,
dispatchers: b,
listener: c
}) {
o.delete(t, i, a, b, c);
o.delete(t, i);
}
`).toMatchInlineSnapshot(`
const gql = 1;
function foo({
const {
gql: _gql,
dispatchers,
listener
}, {
} = n;
function foo({
gql: _gql2,
dispatchers: _dispatchers,
listener: _listener
}) {
dispatchers.delete(_gql, listener, _gql2, _dispatchers, _listener);
_dispatchers.delete(_gql2, _listener);
}
`));

Expand Down

0 comments on commit 16f575f

Please sign in to comment.