fix(es/decorator): Insert initializer to constructor with body (#4028)

This commit is contained in:
Austaras 2022-03-15 20:21:17 +08:00 committed by GitHub
parent 6d5541ccbe
commit 0c76696ed2
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 52 additions and 33 deletions

View File

@ -6061,6 +6061,43 @@ test!(
}), _class);"
);
test!(
ts(),
|_| decorators(Config {
legacy: true,
emit_metadata: false,
}),
issue_3979,
"
class A {
@foo x = 1;
constructor()
constructor() {
console.log(123)
}
}
",
r#"
var _class, _descriptor;
let A = ((_class = class A {
constructor();
constructor(){
_initializerDefineProperty(this, "x", _descriptor, this);
console.log(123);
}
}) || _class, _descriptor = _applyDecoratedDescriptor(_class.prototype, "x", [
foo
], {
configurable: true,
enumerable: true,
writable: true,
initializer: function() {
return 1;
}
}), _class);
"#
);
#[testing::fixture("tests/fixture/decorator/**/exec.ts")]
fn fixture(input: PathBuf) {
let code = fs::read_to_string(&input).expect("failed to read file");

View File

@ -702,41 +702,23 @@ impl Legacy {
});
if !constructor_stmts.is_empty() {
{
// Create constructors as required
let has = c
.class
let constructor = if let Some(c) = c.class.body.iter_mut().find_map(|m| match m {
ClassMember::Constructor(c @ Constructor { body: Some(..), .. }) => Some(c),
_ => None,
}) {
c
} else {
c.class
.body
.iter()
.any(|m| matches!(m, ClassMember::Constructor(..)));
if !has {
c.class
.body
.push(ClassMember::Constructor(default_constructor(
c.class.super_class.is_some(),
)))
.push(ClassMember::Constructor(default_constructor(
c.class.super_class.is_some(),
)));
if let ClassMember::Constructor(c) = c.class.body.last_mut().unwrap() {
c
} else {
unreachable!()
}
}
let constructor = c
.class
.body
.iter_mut()
.filter_map(|m| match m {
ClassMember::Constructor(c) => Some(c),
_ => None,
})
.next()
.unwrap();
if constructor.body.is_none() {
constructor.body = Some(BlockStmt {
span: DUMMY_SP,
stmts: vec![],
});
}
};
let decorate_stmts_insert_position = constructor
.body