swc_ecma_compat_es2015/object_super.rs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593
use std::iter;
use swc_common::{util::take::Take, Span, DUMMY_SP};
use swc_ecma_ast::*;
use swc_ecma_transforms_base::helper;
use swc_ecma_utils::{
alias_ident_for, is_rest_arguments, prepend_stmt, private_ident, quote_ident, ExprFactory,
};
use swc_ecma_visit::{noop_visit_mut_type, visit_mut_pass, VisitMut, VisitMutWith};
use swc_trace_macro::swc_trace;
struct ObjectSuper {
extra_vars: Vec<Ident>,
}
pub fn object_super() -> impl Pass {
visit_mut_pass(ObjectSuper {
extra_vars: Vec::new(),
})
}
#[swc_trace]
impl VisitMut for ObjectSuper {
noop_visit_mut_type!(fail);
fn visit_mut_module_items(&mut self, n: &mut Vec<ModuleItem>) {
n.visit_mut_children_with(self);
if !self.extra_vars.is_empty() {
prepend_stmt(
n,
VarDecl {
span: DUMMY_SP,
kind: VarDeclKind::Var,
declare: false,
decls: self
.extra_vars
.take()
.into_iter()
.map(|v| VarDeclarator {
span: DUMMY_SP,
name: v.into(),
init: None,
definite: false,
})
.collect(),
..Default::default()
}
.into(),
);
}
}
fn visit_mut_stmts(&mut self, stmts: &mut Vec<Stmt>) {
stmts.visit_mut_children_with(self);
if !self.extra_vars.is_empty() {
prepend_stmt(
stmts,
VarDecl {
span: DUMMY_SP,
kind: VarDeclKind::Var,
decls: self
.extra_vars
.drain(..)
.map(|v| VarDeclarator {
span: DUMMY_SP,
name: v.into(),
init: None,
definite: false,
})
.collect(),
..Default::default()
}
.into(),
);
}
}
fn visit_mut_expr(&mut self, expr: &mut Expr) {
expr.visit_mut_children_with(self);
if let Expr::Object(ObjectLit { span: _, props }) = expr {
let mut replacer = SuperReplacer {
obj: None,
vars: Vec::new(),
};
for prop_or_spread in props.iter_mut() {
if let PropOrSpread::Prop(ref mut prop) = prop_or_spread {
if let Prop::Method(MethodProp { key: _, function }) = &mut **prop {
function.visit_mut_with(&mut replacer);
if !replacer.vars.is_empty() {
if let Some(BlockStmt { span: _, stmts, .. }) = &mut function.body {
prepend_stmt(
stmts,
VarDecl {
span: DUMMY_SP,
kind: VarDeclKind::Var,
declare: false,
decls: replacer
.vars
.drain(..)
.map(|v| VarDeclarator {
span: DUMMY_SP,
name: v.into(),
init: None,
definite: false,
})
.collect(),
..Default::default()
}
.into(),
);
}
}
}
}
}
if let Some(obj) = replacer.obj {
*expr = AssignExpr {
span: DUMMY_SP,
op: op!("="),
left: obj.clone().into(),
right: Box::new(expr.take()),
}
.into();
self.extra_vars.push(obj);
}
}
}
}
struct SuperReplacer {
obj: Option<Ident>,
vars: Vec<Ident>,
}
#[swc_trace]
impl VisitMut for SuperReplacer {
noop_visit_mut_type!(fail);
fn visit_mut_object_lit(&mut self, obj: &mut ObjectLit) {
for prop_or_spread in obj.props.iter_mut() {
if let PropOrSpread::Prop(prop) = prop_or_spread {
match &mut **prop {
Prop::Method(MethodProp { key, .. })
| Prop::Getter(GetterProp { key, .. })
| Prop::Setter(SetterProp { key, .. }) => key.visit_mut_with(self),
Prop::KeyValue(KeyValueProp { key, value }) => {
key.visit_mut_with(self);
if !(value.is_fn_expr() || value.is_class()) {
value.visit_mut_with(self)
}
}
Prop::Shorthand(_) | Prop::Assign(_) => (),
}
}
}
}
fn visit_mut_expr(&mut self, expr: &mut Expr) {
self.visit_mut_super_member_call(expr);
self.visit_mut_super_member_set(expr);
self.visit_mut_super_member_get(expr);
expr.visit_mut_children_with(self)
}
}
#[swc_trace]
impl SuperReplacer {
fn get_obj_ref(&mut self) -> Ident {
if let Some(obj) = &self.obj {
obj.clone()
} else {
let ident = private_ident!("_obj");
self.obj = Some(ident.clone());
ident
}
}
fn get_proto(&mut self) -> ExprOrSpread {
CallExpr {
span: DUMMY_SP,
callee: helper!(get_prototype_of),
args: vec![self.get_obj_ref().as_arg()],
..Default::default()
}
.as_arg()
}
// .a -> "a"
fn normalize_computed_expr(&mut self, prop: &mut SuperProp) -> Box<Expr> {
match prop.take() {
SuperProp::Ident(IdentName {
sym: value, span, ..
}) => Lit::Str(Str {
raw: None,
value,
span,
})
.into(),
SuperProp::Computed(ComputedPropName { expr, .. }) => expr,
}
}
/// # In
/// ```js
/// super.foo(a)
/// ```
/// # out
/// ```js
/// _get(_get_prototype_of(Clazz.prototype), 'foo', this).call(this, a)
/// ```
fn visit_mut_super_member_call(&mut self, n: &mut Expr) {
if let Expr::Call(CallExpr {
callee: Callee::Expr(callee_expr),
args,
..
}) = n
{
if let Expr::SuperProp(SuperPropExpr {
obj: Super { span: super_token },
prop,
..
}) = &mut **callee_expr
{
let prop = self.normalize_computed_expr(prop);
let callee =
SuperReplacer::super_to_get_call(self.get_proto(), *super_token, prop.as_arg());
let this = ThisExpr { span: DUMMY_SP }.as_arg();
if args.len() == 1 && is_rest_arguments(&args[0]) {
*n = CallExpr {
span: DUMMY_SP,
callee: MemberExpr {
span: DUMMY_SP,
obj: Box::new(callee),
prop: quote_ident!("apply").into(),
}
.as_callee(),
args: iter::once(this)
.chain(iter::once({
let mut arg = args.pop().unwrap();
arg.spread = None;
arg
}))
.collect(),
..Default::default()
}
.into();
return;
}
*n = CallExpr {
span: DUMMY_SP,
callee: MemberExpr {
span: DUMMY_SP,
obj: Box::new(callee),
prop: MemberProp::Ident(quote_ident!("call")),
}
.as_callee(),
args: iter::once(this).chain(args.take()).collect(),
..Default::default()
}
.into();
}
}
}
/// # In
/// ```js
/// super.foo = bar
/// # out
/// ```js
/// _set(_get_prototype_of(_obj), "foo", bar, this, true)
/// ```
fn visit_mut_super_member_set(&mut self, n: &mut Expr) {
match n {
Expr::Update(UpdateExpr {
arg, op, prefix, ..
}) => {
if let Expr::SuperProp(SuperPropExpr {
obj: Super { span: super_token },
prop,
..
}) = &mut **arg
{
let op = match op {
op!("++") => op!("+="),
op!("--") => op!("-="),
};
*n = self.super_to_set_call(*super_token, true, prop, op, 1.0.into(), *prefix);
}
}
Expr::Assign(AssignExpr {
span,
left,
op,
right,
}) => {
if let AssignTarget::Simple(SimpleAssignTarget::SuperProp(SuperPropExpr {
obj: Super { span: super_token },
prop,
..
})) = left
{
*n =
self.super_to_set_call(*super_token, false, prop, *op, right.take(), false);
return;
}
left.visit_mut_children_with(self);
*n = AssignExpr {
span: *span,
left: left.take(),
op: *op,
right: right.take(),
}
.into();
}
_ => {}
}
}
/// # In
/// ```js
/// super.foo
/// ```
/// # out
/// ```js
/// _get(_get_prototype_of(Clazz.prototype), 'foo', this)
/// ```
fn visit_mut_super_member_get(&mut self, n: &mut Expr) {
if let Expr::SuperProp(SuperPropExpr {
obj: Super {
span: super_token, ..
},
prop,
..
}) = n
{
let prop = self.normalize_computed_expr(prop);
*n = SuperReplacer::super_to_get_call(self.get_proto(), *super_token, prop.as_arg());
}
}
fn super_to_get_call(proto: ExprOrSpread, super_token: Span, prop: ExprOrSpread) -> Expr {
CallExpr {
span: super_token,
callee: helper!(get),
args: vec![proto, prop, ThisExpr { span: super_token }.as_arg()],
..Default::default()
}
.into()
}
fn to_bin_expr(left: Box<Expr>, op: AssignOp, rhs: Box<Expr>) -> BinExpr {
BinExpr {
span: DUMMY_SP,
left,
op: op.to_update().unwrap(),
right: rhs,
}
}
fn call_set_helper(
&mut self,
super_token: Span,
prop: ExprOrSpread,
rhs: ExprOrSpread,
) -> Expr {
CallExpr {
span: super_token,
callee: helper!(set),
args: vec![
self.get_proto(),
prop,
rhs,
ThisExpr { span: super_token }.as_arg(),
// strict
true.as_arg(),
],
..Default::default()
}
.into()
}
fn super_to_set_call(
&mut self,
super_token: Span,
is_update: bool,
prop: &mut SuperProp,
op: AssignOp,
rhs: Box<Expr>,
prefix: bool,
) -> Expr {
let computed = match prop {
SuperProp::Ident(_) => false,
SuperProp::Computed(_) => true,
};
let mut prop = self.normalize_computed_expr(prop);
match op {
op!("=") => self.call_set_helper(super_token, prop.as_arg(), rhs.as_arg()),
_ => {
let left = Box::new(SuperReplacer::super_to_get_call(
self.get_proto(),
super_token,
if computed {
let ref_ident = alias_ident_for(&rhs, "_ref").into_private();
self.vars.push(ref_ident.clone());
*prop = AssignExpr {
span: DUMMY_SP,
left: ref_ident.clone().into(),
op: op!("="),
right: prop.take(),
}
.into();
ref_ident.as_arg()
} else {
prop.clone().as_arg()
},
));
if is_update {
if prefix {
self.call_set_helper(
super_token,
prop.as_arg(),
SuperReplacer::to_bin_expr(
UnaryExpr {
span: DUMMY_SP,
op: op!(unary, "+"),
arg: left,
}
.into(),
op,
rhs,
)
.as_arg(),
)
} else {
let update_ident = alias_ident_for(&rhs, "_super").into_private();
self.vars.push(update_ident.clone());
SeqExpr {
span: DUMMY_SP,
exprs: vec![
Box::new(
self.call_set_helper(
super_token,
prop.as_arg(),
SuperReplacer::to_bin_expr(
Box::new(
AssignExpr {
span: DUMMY_SP,
left: update_ident.clone().into(),
op: op!("="),
right: Box::new(Expr::Unary(UnaryExpr {
span: DUMMY_SP,
op: op!(unary, "+"),
arg: left,
})),
}
.into(),
),
op,
rhs,
)
.as_arg(),
),
),
Box::new(Expr::Ident(update_ident)),
],
}
.into()
}
} else {
self.call_set_helper(
super_token,
prop.as_arg(),
SuperReplacer::to_bin_expr(left, op, rhs).as_arg(),
)
}
}
}
}
}
#[cfg(test)]
mod tests {
use swc_common::Mark;
use swc_ecma_parser::{EsSyntax, Syntax};
use swc_ecma_transforms_base::resolver;
use swc_ecma_transforms_testing::test;
use super::*;
use crate::{function_name, shorthand};
test!(
::swc_ecma_parser::Syntax::default(),
|_| {
let unresolved_mark = Mark::new();
let top_level_mark = Mark::new();
(
resolver(unresolved_mark, top_level_mark, false),
object_super(),
shorthand(),
function_name(),
)
},
get,
"let obj = {
a(){
let c = super.x;
}
}"
);
test!(
::swc_ecma_parser::Syntax::default(),
|_| {
(
resolver(Mark::new(), Mark::new(), false),
object_super(),
shorthand(),
function_name(),
)
},
call,
"let obj = {
a(){
super.y(1,2,3);
}
}"
);
test!(
::swc_ecma_parser::Syntax::default(),
|_| {
(
resolver(Mark::new(), Mark::new(), false),
object_super(),
shorthand(),
function_name(),
)
},
set,
"let obj = {
a(){
super.x = 1;
}
}"
);
test!(
::swc_ecma_parser::Syntax::default(),
|_| {
(
resolver(Mark::new(), Mark::new(), false),
object_super(),
shorthand(),
function_name(),
)
},
nest,
"let obj = {
b(){
super.bar()
let o = {
d(){
super.d()
}
}
},
}"
);
test!(
Syntax::Es(EsSyntax {
allow_super_outside_method: true,
..Default::default()
}),
|_| {
(
resolver(Mark::new(), Mark::new(), false),
object_super(),
shorthand(),
function_name(),
)
},
do_not_transform,
"let outer = {
b(){
let inner = {
d:function d(){
super.d() // should not transform
}
}
},
}"
);
}