feat(es/compat): Verify private property access (#4465)

This commit is contained in:
Satish Srinivasan 2022-04-30 05:32:52 -07:00 committed by GitHub
parent 951e7b3fb9
commit de53a6fa9d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
5 changed files with 95 additions and 0 deletions

View File

@ -0,0 +1,11 @@
x Illegal access to private class property.
,----
18 | foo.#bar;
: ^^^^^^^^
`----
x Illegal access to private class property.
,----
19 | foo.#privateMethod();
: ^^^^^^^^^^^^^^^^^^
`----

View File

@ -0,0 +1,21 @@
class Foo {
#bar = 'i\'m a private field!';
#privateMethod() {
return 'i\'m a private method!';
}
foo() {
return this.#bar;
}
bar() {
return this.#privateMethod();
}
}
var f = new Foo();
console.log(f.foo());
console.log(f.bar());
foo.#bar;
foo.#privateMethod();

View File

@ -0,0 +1,19 @@
class Foo {
#bar = 'i\'m a private field!';
#privateMethod() {
return 'i\'m a private method!';
}
foo() {
return this.#bar;
}
bar() {
return this.#privateMethod();
}
}
var f = new Foo();
console.log(f.foo());
console.log(f.bar());

View File

@ -0,0 +1,34 @@
import * as swcHelpers from "@swc/helpers";
var _bar = /*#__PURE__*/ new WeakMap(), _privateMethod = /*#__PURE__*/ new WeakSet();
var Foo = /*#__PURE__*/ function() {
"use strict";
function Foo() {
swcHelpers.classCallCheck(this, Foo);
swcHelpers.classPrivateMethodInit(this, _privateMethod);
swcHelpers.classPrivateFieldInit(this, _bar, {
writable: true,
value: "i'm a private field!"
});
}
swcHelpers.createClass(Foo, [
{
key: "foo",
value: function foo() {
return swcHelpers.classPrivateFieldGet(this, _bar);
}
},
{
key: "bar",
value: function bar() {
return swcHelpers.classPrivateMethodGet(this, _privateMethod, privateMethod).call(this);
}
}
]);
return Foo;
}();
function privateMethod() {
return "i'm a private method!";
}
var f = new Foo();
console.log(f.foo());
console.log(f.bar());

View File

@ -11,6 +11,7 @@ use swc_ecma_ast::*;
use swc_ecma_transforms_base::pass::JsPass; use swc_ecma_transforms_base::pass::JsPass;
use swc_ecma_utils::{ use swc_ecma_utils::{
default_constructor, ident::IdentLike, prepend, private_ident, quote_ident, ExprFactory, Id, default_constructor, ident::IdentLike, prepend, private_ident, quote_ident, ExprFactory, Id,
HANDLER,
}; };
use swc_ecma_visit::{ use swc_ecma_visit::{
as_folder, noop_visit_mut_type, noop_visit_type, Visit, VisitMut, VisitMutWith, VisitWith, as_folder, noop_visit_mut_type, noop_visit_type, Visit, VisitMut, VisitMutWith, VisitWith,
@ -367,6 +368,15 @@ impl VisitMut for PrivateInObject {
}); });
} }
Expr::Member(MemberExpr {
span,
obj: _,
prop: MemberProp::PrivateName(PrivateName { .. }),
}) => {
let error = "Illegal access to private class property.";
HANDLER.with(|h| h.struct_span_err(*span, error).emit());
}
_ => {} _ => {}
} }
} }