Skip to content

Commit

Permalink
Merge pull request #133 from j4k0xb/fix/invalid-identifiers
Browse files Browse the repository at this point in the history
fix: invalid identifiers
  • Loading branch information
jehna authored Oct 6, 2024
2 parents 87065c9 + a317fd3 commit 7f9e0b4
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 2 deletions.
33 changes: 33 additions & 0 deletions src/plugins/local-llm-rename/visit-all-identifiers.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -207,3 +207,36 @@ e.b;
})
);
});

test("should handle invalid identifiers", async () => {
const code = `const a = 1`;
const result = await visitAllIdentifiers(code, async () => "this.kLength");
assert.equal(result, "const thisKLength = 1;");
});

test("should handle space in identifier name (happens for some reason though it shouldn't)", async () => {
const code = `const a = 1`;
const result = await visitAllIdentifiers(code, async () => "foo bar");
assert.equal(result, "const fooBar = 1;");
});

test("should handle reserved identifiers", async () => {
const code = `const a = 1`;
const result = await visitAllIdentifiers(code, async () => "static");
assert.equal(result, "const _static = 1;");
});

test("should handle multiple identifiers named the same", async () => {
const code = `
const a = 1;
const b = 1;
`.trim();
const result = await visitAllIdentifiers(code, async () => "foo");
assert.equal(
result,
`
const foo = 1;
const _foo = 1;
`.trim()
);
});
4 changes: 2 additions & 2 deletions src/plugins/local-llm-rename/visit-all-identifiers.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { parseAsync, transformFromAstAsync, NodePath } from "@babel/core";
import * as babelTraverse from "@babel/traverse";
import { Identifier, isValidIdentifier, Node } from "@babel/types";
import { Identifier, toIdentifier, Node } from "@babel/types";

const traverse: typeof babelTraverse.default.default = (
typeof babelTraverse.default === "function"
Expand Down Expand Up @@ -39,7 +39,7 @@ export async function visitAllIdentifiers(
const surroundingCode = await scopeToString(smallestScope);
const renamed = await visitor(smallestScopeNode.name, surroundingCode);

let safeRenamed = isValidIdentifier(renamed) ? renamed : `_${renamed}`;
let safeRenamed = toIdentifier(renamed);
while (renames.has(safeRenamed)) {
safeRenamed = `_${safeRenamed}`;
}
Expand Down

0 comments on commit 7f9e0b4

Please sign in to comment.