Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[setPublicClassFields] Use define for static name/length #14351

Merged
merged 2 commits into from Mar 22, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
27 changes: 24 additions & 3 deletions packages/babel-helper-create-class-features-plugin/src/fields.ts
Expand Up @@ -936,6 +936,18 @@ export type PropNode =
| t.StaticBlock;
export type PropPath = NodePath<PropNode>;

function isNameOrLength(node: t.ClassProperty) {
if (node.key.type === "Identifier") {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: can we memoise node.key?

return (
!node.computed && (node.key.name === "name" || node.key.name === "length")
);
}
if (node.key.type === "StringLiteral") {
return node.key.value === "name" || node.key.value === "length";
}
return false;
}

export function buildFieldsInitNodes(
ref: t.Identifier,
superRef: t.Expression | undefined,
Expand Down Expand Up @@ -1019,10 +1031,19 @@ export function buildFieldsInitNodes(
);
break;
case isStatic && isPublic && isField && setPublicClassFields:
needsClassRef = true;
// Functions always have non-writable .name and .length properties,
// so we must always use [[Define]] for them.
// It might still be possible to a computed static fields whose resulting
// key is "name" or "length", but the assumption is telling us that it's
// not going to happen.
// @ts-expect-error checked in switch
staticNodes.push(buildPublicFieldInitLoose(t.cloneNode(ref), prop));
break;
if (!isNameOrLength(prop.node)) {
needsClassRef = true;
// @ts-expect-error checked in switch
staticNodes.push(buildPublicFieldInitLoose(t.cloneNode(ref), prop));
break;
}
// falls through
case isStatic && isPublic && isField && !setPublicClassFields:
needsClassRef = true;
staticNodes.push(
Expand Down
@@ -0,0 +1,12 @@
class A {
static name = 1;
static length = 2;
static foo = 3;
static [bar] = 4;
static ["name"] = 5;
static [name] = 6;
static "name" = 7;

name = 8;
length = 9;
}
@@ -0,0 +1,20 @@
let _bar, _name;

_bar = bar;
_name = name;

class A {
constructor() {
this.name = 8;
this.length = 9;
}

}

babelHelpers.defineProperty(A, "name", 1);
babelHelpers.defineProperty(A, "length", 2);
A.foo = 3;
A[_bar] = 4;
babelHelpers.defineProperty(A, "name", 5);
A[_name] = 6;
babelHelpers.defineProperty(A, "name", 7);