Skip to content
Closed
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
57 changes: 25 additions & 32 deletions src/js_parser/visit/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -227,11 +227,30 @@ impl<'a, const TYPESCRIPT: bool, const SCAN_ONLY: bool> P<'a, TYPESCRIPT, SCAN_O
let dup: Option<&mut StringVoidMap> = duplicate_args_check.as_deref_mut();
self.visit_binding(arg.binding, dup);
if let Some(default) = arg.default.as_mut() {
self.visit_expr(default);
self.visit_binding_initializer(arg.binding, default);
}
}
}

/// Decorator lowering turns the initializer into `_class = class {}`, so an anonymous
/// class gets the binding's name through `decorator_class_name` (see `e_class`).
Comment thread
robobun marked this conversation as resolved.
Resolved
pub(crate) fn visit_binding_initializer(
&mut self,
binding: BindingNodeIndex,
initializer: &mut Expr,
) {
let prev_decorator_class_name = self.decorator_class_name;
if initializer.is_anonymous_named()
&& let ExprData::EClass(e_class) = &initializer.data
&& e_class.should_lower_standard_decorators
&& let BData::BIdentifier(id) = binding.data
{
self.decorator_class_name = Some(self.load_name_from_ref(id.r#ref));
}
self.visit_expr(initializer);
self.decorator_class_name = prev_decorator_class_name;
}

// `Vec<Expr>` is not `Copy`; mutate in place.
pub(crate) fn visit_ts_decorators(&mut self, decs: &mut ExprNodeList) {
for dec in decs.slice_mut() {
Expand Down Expand Up @@ -576,7 +595,7 @@ impl<'a, const TYPESCRIPT: bool, const SCAN_ONLY: bool> P<'a, TYPESCRIPT, SCAN_O
for dec in st.decls.slice_mut() {
self.visit_binding(dec.binding, None);
if let Some(val) = dec.value.as_mut() {
self.visit_expr(val);
self.visit_binding_initializer(dec.binding, val);
}
}
st.kind = self.select_local_kind(st.kind);
Expand Down Expand Up @@ -632,22 +651,9 @@ impl<'a, const TYPESCRIPT: bool, const SCAN_ONLY: bool> P<'a, TYPESCRIPT, SCAN_O
// Arena-owned B::Array valid for 'a; exclusive during visit pass.
for item in bind.items_mut() {
self.visit_binding(item.binding, duplicate_arg_check.as_deref_mut());
if let Some(default_value) = item.default_value {
if let Some(default_value) = item.default_value.as_mut() {
let was_anonymous_named_expr = default_value.is_anonymous_named();
let prev_decorator_class_name2 = self.decorator_class_name;
if was_anonymous_named_expr {
if let ExprData::EClass(e_class) = &default_value.data {
if e_class.should_lower_standard_decorators {
if let BData::BIdentifier(id) = item.binding.data {
let id = id.get();
self.decorator_class_name =
Some(self.load_name_from_ref(id.r#ref));
}
}
}
}
self.visit_expr(item.default_value.as_mut().unwrap());
self.decorator_class_name = prev_decorator_class_name2;
self.visit_binding_initializer(item.binding, default_value);

if let BData::BIdentifier(bind_) = item.binding.data {
let bind_ = bind_.get();
Expand All @@ -671,22 +677,9 @@ impl<'a, const TYPESCRIPT: bool, const SCAN_ONLY: bool> P<'a, TYPESCRIPT, SCAN_O
}

self.visit_binding(property.value, duplicate_arg_check.as_deref_mut());
if let Some(default_value) = property.default_value {
if let Some(default_value) = property.default_value.as_mut() {
let was_anonymous_named_expr = default_value.is_anonymous_named();
let prev_decorator_class_name3 = self.decorator_class_name;
if was_anonymous_named_expr {
if let ExprData::EClass(e_class) = &default_value.data {
if e_class.should_lower_standard_decorators {
if let BData::BIdentifier(id) = property.value.data {
let id = id.get();
self.decorator_class_name =
Some(self.load_name_from_ref(id.r#ref));
}
}
}
}
self.visit_expr(property.default_value.as_mut().unwrap());
self.decorator_class_name = prev_decorator_class_name3;
self.visit_binding_initializer(property.value, default_value);

if let BData::BIdentifier(bind_) = property.value.data {
let bind_ = bind_.get();
Expand Down
131 changes: 131 additions & 0 deletions test/bundler/transpiler/es-decorators.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -982,6 +982,137 @@ describe("ES Decorators", () => {
});
});

describe("anonymous decorated class as a binding initializer", () => {
// The lowering rewrites the class to `_class = class {}`, so the name the
// binding would have given it has to be carried over explicitly, the same
// way it already is for `const K = class {}`. Expected values match node
// running the same code with the decorators removed.
test.concurrent("takes the parameter name in every kind of parameter list", async () => {
const { stdout, stderr, exitCode } = await runDecorator(`
function dec() {}
function declaration(K = class { @dec m() {} }) { return K.name; }
const expression = function (K = class { @dec m() {} }) { return K.name; };
const arrow = (K = class { @dec m() {} }) => K.name;
function secondParameter(first, K = class { @dec m() {} }) { return K.name; }
class C {
constructor(K = class { @dec m() {} }) { this.fromConstructor = K.name; }
method(K = class { @dec m() {} }) { return K.name; }
static staticMethod(K = class { @dec m() {} }) { return K.name; }
}
const obj = {
method(K = class { @dec m() {} }) { return K.name; },
set setter(K = class { @dec m() {} }) { this.fromSetter = K.name; },
};
obj.setter = undefined;
function objectPattern({ K = class { @dec m() {} } } = {}) { return K.name; }
function arrayPattern([K = class { @dec m() {} }] = []) { return K.name; }
console.log(JSON.stringify({
declaration: declaration(),
expression: expression(),
arrow: arrow(),
secondParameter: secondParameter(1),
constructorParameter: new C().fromConstructor,
method: new C().method(),
staticMethod: C.staticMethod(),
objectMethod: obj.method(),
setter: obj.fromSetter,
objectPattern: objectPattern(),
arrayPattern: arrayPattern(),
}));
`);
expect(stderr).toBe("");
expect(JSON.parse(stdout)).toEqual({
declaration: "K",
expression: "K",
arrow: "K",
secondParameter: "K",
constructorParameter: "K",
method: "K",
staticMethod: "K",
objectMethod: "K",
setter: "K",
objectPattern: "K",
arrayPattern: "K",
});
expect(exitCode).toBe(0);
});

test.concurrent("takes the variable name in a for loop declaration", async () => {
const { stdout, stderr, exitCode } = await runDecorator(`
function dec() {}
const names = [];
for (const K = class { @dec m() {} }; names.length < 1; ) names.push(K.name);
for (let K = class { @dec m() {} }, L = class { accessor x; }; names.length < 3; ) names.push(K.name, L.name);
for (var V = class { @dec m() {} }; names.length < 4; ) names.push(V.name);
for (const [D = class { @dec m() {} }] = []; names.length < 5; ) names.push(D.name);
console.log(JSON.stringify(names));
`);
expect(stderr).toBe("");
expect(JSON.parse(stdout)).toEqual(["K", "K", "L", "V", "D"]);
expect(exitCode).toBe(0);
});

test.concurrent("class decorator sees the parameter name as context.name", async () => {
const { stdout, stderr, exitCode } = await runDecorator(`
function dec(cls, ctx) { console.log("ctx.name:", JSON.stringify(ctx.name)); }
function f(K = @dec class {}) { return K.name; }
console.log(JSON.stringify(f()));
`);
expect(stderr).toBe("");
expect(stdout).toBe('ctx.name: "K"\n"K"\n');
expect(exitCode).toBe(0);
});

test.concurrent("class with an accessor and no decorators is lowered too", async () => {
const { stdout, stderr, exitCode } = await runDecorator(`
function f(K = class { accessor x = 1; }) { return [K.name, new K().x]; }
console.log(JSON.stringify(f()));
`);
expect(stderr).toBe("");
expect(stdout).toBe('["K",1]\n');
expect(exitCode).toBe(0);
});

test.concurrent("parameter name does not override an explicit class name or reach a nested class", async () => {
const { stdout, stderr, exitCode } = await runDecorator(`
function dec() {}
function named(K = class Named { @dec m() {} }) { return K.name; }
function nested(K = [class { @dec m() {} }][0]) { return K.name; }
function passed(K = class { @dec m() {} }) { return K.name; }
console.log(JSON.stringify([named(), nested(), passed(class Passed {})]));
`);
expect(stderr).toBe("");
const [named, nested, passed] = JSON.parse(stdout);
expect(named).toBe("Named");
expect(nested).not.toBe("K");
expect(passed).toBe("Passed");
expect(exitCode).toBe(0);
});

test.concurrent("TypeScript constructor parameter property", async () => {
using dir = tempDir("es-dec-param-property", {
"tsconfig.json": JSON.stringify({ compilerOptions: {} }),
"test.ts": `
function dec(value: unknown, ctx: ClassMethodDecoratorContext) {}
class Holder {
constructor(public K = class { @dec m() {} }) {}
}
console.log(new Holder().K.name);
`,
});
await using proc = Bun.spawn({
cmd: [bunExe(), "test.ts"],
env: bunEnv,
cwd: String(dir),
stderr: "pipe",
});
const [stdout, rawStderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]);
expect(filterStderr(rawStderr)).toBe("");
expect(stdout).toBe("K\n");
expect(exitCode).toBe(0);
});
});

describe("private member calls in lowered classes", () => {
// When a class is lowered for standard decorators, `recv.#m(...)` becomes
// `__privateGet(recv, _m).call(recv, ...)`. The receiver must be evaluated
Expand Down
Loading