Skip to content

Commit

Permalink
fix: avoid name conflicts with current class elements
Browse files Browse the repository at this point in the history
  • Loading branch information
JLHwung committed Oct 6, 2020
1 parent ffa4a78 commit 474cc03
Show file tree
Hide file tree
Showing 5 changed files with 67 additions and 6 deletions.
44 changes: 40 additions & 4 deletions packages/babel-plugin-proposal-class-static-block/src/index.js
@@ -1,6 +1,40 @@
import { declare } from "@babel/helper-plugin-utils";
import syntaxClassStaticBlock from "@babel/plugin-syntax-class-static-block";

/**
* Generate a uid that is not in `denyList`
*
* @param {*} scope
* @param {Set<string>} privateNames
* @returns
*/
function generateUid(scope, denyList: Set<string>) {
const name = "";
let uid;
let i = 0;
do {
uid = scope._generateUid(name, i);
i++;
} while (denyList.has(uid));
return uid;
}

/**
* Get private names defined in current class body
*
* @param {NodePath<ClassBody>} classBody
* @returns {Set<string>} A set of defined private names
*/
function getPrivateNames(classBody: NodePath<ClassBody>): Set<string> {
const privateNames = new Set();
for (const path of classBody.get("body")) {
if (path.isPrivate()) {
privateNames.add(path.get("key.id").node.name);
}
}
return privateNames;
}

export default declare(({ types: t, template, assertVersion }) => {
// todo remove this check after Babel 7.12.0 is published
if (process.env.NODE_ENV !== "test") {
Expand All @@ -11,13 +45,15 @@ export default declare(({ types: t, template, assertVersion }) => {
name: "proposal-class-static-block",
inherits: syntaxClassStaticBlock,
visitor: {
StaticBlock(path) {
const staticBlockRef = path.scope.generateUidIdentifier("");
const classBody = path.parentPath;
StaticBlock(path: NodePath<StaticBlock>) {
const { parentPath: classBody, scope } = path;
const staticBlockRef = t.privateName(
t.identifier(generateUid(scope, getPrivateNames(classBody))),
);
classBody.pushContainer(
"body",
t.classPrivateProperty(
t.privateName(staticBlockRef),
staticBlockRef,
template.expression.ast`(() => { ${path.node.body} })()`,
[],
/* static */ true,
Expand Down
@@ -1,9 +1,9 @@
class Foo extends class extends class Base {
static #_3 = (() => {
static #_ = (() => {
this.qux = 21;
})();
} {
static #_2 = (() => {
static #_ = (() => {
this.bar = 21;
})();
} {
Expand Down
@@ -0,0 +1,8 @@
class Foo {
static #_ = 42;
// static block can not be tranformed as `#_` here
static {
this.foo = this.#_;
}
}
expect(Foo.foo).toBe(42);
@@ -0,0 +1,8 @@
class Foo {
static #_ = 42;
// static block can not be tranformed as `#_` here
static {
this.foo = this.#_;
}
}
expect(Foo.foo).toBe(42);
@@ -0,0 +1,9 @@
class Foo {
static #_ = 42; // static block can not be tranformed as `#_` here

static #_2 = (() => {
this.foo = this.#_;
})();
}

expect(Foo.foo).toBe(42);

0 comments on commit 474cc03

Please sign in to comment.