Support typescript constructor parameter property

This commit is contained in:
강동윤 2019-02-08 18:13:32 +09:00
parent e1b83e594f
commit 7482836d5e

View File

@ -1,6 +1,9 @@
use crate::pass::Pass;
use crate::{
pass::Pass,
util::{prepend_stmts, ExprFactory},
};
use ast::*;
use swc_common::{util::move_map::MoveMap, Fold, FoldWith, Spanned};
use swc_common::{util::move_map::MoveMap, Fold, FoldWith, Spanned, DUMMY_SP};
/// Strips type annotations out.
pub fn strip() -> impl Pass + Clone + Copy {
@ -10,6 +13,58 @@ pub fn strip() -> impl Pass + Clone + Copy {
#[derive(Clone, Copy)]
struct Strip;
impl Fold<Constructor> for Strip {
fn fold(&mut self, c: Constructor) -> Constructor {
let c = c.fold_children(self);
eprintln!("HERE");
let mut stmts = vec![];
let params = c.params.move_map(|param| match param {
PatOrTsParamProp::Pat(..) => param,
PatOrTsParamProp::TsParamProp(param) => {
let (ident, param) = match param.param {
TsParamPropParam::Ident(i) => (i.clone(), Pat::Ident(i)),
TsParamPropParam::Assign(AssignPat {
span,
left: box Pat::Ident(i),
right,
type_ann: _,
}) => (
i.clone(),
Pat::Assign(AssignPat {
span,
left: box Pat::Ident(i),
right,
type_ann: None,
}),
),
_ => unreachable!("destructuring pattern inside TsParameterProperty"),
};
stmts.push(Stmt::Expr(box Expr::Assign(AssignExpr {
span: DUMMY_SP,
left: PatOrExpr::Expr(box ThisExpr { span: DUMMY_SP }.member(ident.clone())),
op: op!("="),
right: box Expr::Ident(ident),
})));
PatOrTsParamProp::Pat(param)
}
});
let body = match c.body {
Some(mut body) => {
prepend_stmts(&mut body.stmts, stmts.into_iter());
Some(body)
}
None => None,
};
Constructor { params, body, ..c }
}
}
impl Fold<Vec<ModuleItem>> for Strip {
fn fold(&mut self, items: Vec<ModuleItem>) -> Vec<ModuleItem> {
items.move_flat_map(|item| match item {
@ -29,7 +84,7 @@ impl Fold<Vec<ModuleItem>> for Strip {
| ModuleItem::ModuleDecl(ModuleDecl::TsImportEqualsDecl(..))
| ModuleItem::ModuleDecl(ModuleDecl::TsNamespaceExportDecl(..)) => None,
_ => Some(item),
_ => Some(item.fold_with(self)),
})
}
}
@ -78,3 +133,61 @@ to_none!(
TsTypeParamDecl,
TsTypeParamInstantiation
);
impl Fold<Expr> for Strip {
fn fold(&mut self, expr: Expr) -> Expr {
let expr = expr.fold_children(self);
match expr {
Expr::TsAs(TsAsExpr { expr, .. }) => *expr,
Expr::TsNonNull(TsNonNullExpr { expr, .. }) => *expr,
Expr::TsTypeAssertion(TsTypeAssertion { expr, .. }) => *expr,
Expr::TsTypeCast(TsTypeCastExpr { expr, .. }) => *expr,
_ => expr,
}
}
}
#[cfg(test)]
mod tests {
use super::strip;
macro_rules! to {
($name:ident, $from:expr, $to:expr) => {
test!(
::swc_ecma_parser::Syntax::Typescript(Default::default()),
|_| strip(),
$name,
$from,
$to
);
};
}
to!(
constructor_01,
"class Foo {
constructor(public readonly foo) {}
}",
"class Foo {
constructor(foo) {
this.foo = foo;
}
}"
);
to!(
constructor_02,
"class Foo {
constructor(readonly foo) {
this.bar = 1;
}
}",
"class Foo {
constructor(foo) {
this.foo = foo;
this.bar = 1;
}
}"
);
}