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
use std::iter;

use swc_common::{util::take::Take, Mark, Span, DUMMY_SP};
use swc_ecma_ast::*;
use swc_ecma_transforms_base::helper;
use swc_ecma_utils::{is_rest_arguments, quote_ident, ExprFactory};
use swc_ecma_visit::{noop_visit_mut_type, VisitMut, VisitMutWith};

use super::get_prototype_of;

/// Process function body.
///
/// # In
///
/// ```js
/// super.foo(a)
/// ```
///
/// # Out
///
///
/// _get(Child.prototype.__proto__ || Object.getPrototypeOf(Child.prototype),
/// 'foo', this).call(this, a);
pub struct SuperFieldAccessFolder<'a> {
    pub class_name: &'a Ident,

    pub vars: &'a mut Vec<VarDeclarator>,
    /// Mark for the `_this`. Used only when folding constructor.
    pub constructor_this_mark: Option<Mark>,
    pub is_static: bool,

    pub folding_constructor: bool,

    /// True while folding **injected** `_define_property` call
    pub in_injected_define_property_call: bool,

    /// True while folding a function / class.
    pub in_nested_scope: bool,

    /// `Some(mark)` if `var this2 = this`is required.
    pub this_alias_mark: Option<Mark>,

    /// assumes super is never changed, payload is the name of super class
    pub constant_super: bool,

    pub super_class: &'a Option<Ident>,

    pub in_pat: bool,
}

macro_rules! mark_nested {
    ($name:ident, $T:tt) => {
        fn $name(&mut self, n: &mut $T) {
            // injected `_define_property` should be handled like method
            if self.folding_constructor && !self.in_injected_define_property_call {
                let old = self.in_nested_scope;
                self.in_nested_scope = true;
                n.visit_mut_children_with(self);
                self.in_nested_scope = old;
            } else {
                n.visit_mut_children_with(self)
            }
        }
    };
}

impl<'a> VisitMut for SuperFieldAccessFolder<'a> {
    noop_visit_mut_type!();

    // mark_nested!(fold_function, Function);
    mark_nested!(visit_mut_class, Class);

    visit_mut_only_key!();

    fn visit_mut_expr(&mut self, n: &mut Expr) {
        match n {
            Expr::This(ThisExpr { span }) if self.in_nested_scope => {
                *n = Expr::Ident(quote_ident!(
                    span.apply_mark(
                        *self
                            .this_alias_mark
                            .get_or_insert_with(|| Mark::fresh(Mark::root()))
                    ),
                    "_this"
                ));
            }
            // We pretend method folding mode for while folding injected `_define_property`
            // calls.
            Expr::Call(CallExpr {
                callee: Callee::Expr(expr),
                ..
            }) if expr.is_ident_ref_to("_define_property") => {
                let old = self.in_injected_define_property_call;
                self.in_injected_define_property_call = true;
                n.visit_mut_children_with(self);
                self.in_injected_define_property_call = old;
            }
            Expr::SuperProp(..) => {
                self.visit_mut_super_member_get(n);
            }
            Expr::Update(UpdateExpr { arg, .. }) if arg.is_super_prop() => {
                if let Expr::SuperProp(SuperPropExpr {
                    obj: Super {
                        span: super_token, ..
                    },
                    prop,
                    ..
                }) = &**arg
                {
                    *arg = self.super_to_update_call(*super_token, prop.clone()).into();
                }
            }
            Expr::Assign(AssignExpr {
                ref left,
                op: op!("="),
                right,
                ..
            }) if is_assign_to_super_prop(left) => {
                right.visit_mut_with(self);
                self.visit_mut_super_member_set(n)
            }
            Expr::Assign(AssignExpr { left, right, .. }) if is_assign_to_super_prop(left) => {
                right.visit_mut_with(self);
                self.visit_mut_super_member_update(n);
            }
            Expr::Call(CallExpr {
                callee: Callee::Expr(callee_expr),
                args,
                ..
            }) if callee_expr.is_super_prop() => {
                args.visit_mut_children_with(self);

                self.visit_mut_super_member_call(n);
            }
            _ => {
                n.visit_mut_children_with(self);
            }
        }
    }

    fn visit_mut_pat(&mut self, n: &mut Pat) {
        let in_pat = self.in_pat;
        self.in_pat = true;
        n.visit_mut_children_with(self);
        self.in_pat = in_pat;
    }

    fn visit_mut_function(&mut self, n: &mut Function) {
        if self.folding_constructor {
            return;
        }

        if self.folding_constructor && !self.in_injected_define_property_call {
            let old = self.in_nested_scope;
            self.in_nested_scope = true;
            n.visit_mut_children_with(self);
            self.in_nested_scope = old;
        } else {
            n.visit_mut_children_with(self);
        }
    }
}

impl<'a> SuperFieldAccessFolder<'a> {
    /// # 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,
                ..
            }) = &**callee_expr
            {
                let this = match self.this_alias_mark.or(self.constructor_this_mark) {
                    Some(mark) => {
                        let ident = quote_ident!(DUMMY_SP.apply_mark(mark), "_this").as_arg();
                        // in constant super, call will be the only place where a assert is needed
                        if self.constant_super {
                            CallExpr {
                                span: DUMMY_SP,
                                callee: helper!(assert_this_initialized),
                                args: vec![ident],
                                type_args: Default::default(),
                            }
                            .as_arg()
                        } else {
                            ident
                        }
                    }
                    _ => ThisExpr { span: DUMMY_SP }.as_arg(),
                };

                let callee = self.super_to_get_call(*super_token, prop.clone());
                let mut args = args.clone();

                if args.len() == 1 && is_rest_arguments(&args[0]) {
                    *n = Expr::Call(CallExpr {
                        span: DUMMY_SP,
                        callee: callee.make_member(quote_ident!("apply")).as_callee(),
                        args: iter::once(this)
                            .chain(iter::once({
                                let mut arg = args.pop().unwrap();
                                arg.spread = None;
                                arg
                            }))
                            .collect(),
                        type_args: Default::default(),
                    });
                    return;
                }

                *n = Expr::Call(CallExpr {
                    span: DUMMY_SP,
                    callee: callee.make_member(quote_ident!("call")).as_callee(),
                    args: iter::once(this).chain(args).collect(),
                    type_args: Default::default(),
                });
            }
        }
    }

    /// # In
    /// ```js
    /// super.foo = bar
    /// # out
    /// ```js
    /// _set(_get_prototype_of(Clazz.prototype), "foo", bar, this, true)
    /// ```
    fn visit_mut_super_member_set(&mut self, n: &mut Expr) {
        if let Expr::Assign(AssignExpr {
            left:
                AssignTarget::Simple(SimpleAssignTarget::SuperProp(SuperPropExpr {
                    obj: Super { span: super_token },
                    prop,
                    ..
                })),
            op: op @ op!("="),
            right,
            ..
        }) = n
        {
            *n = self.super_to_set_call(*super_token, prop.take(), *op, right.take());
        }
    }

    /// # 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 super_token = *super_token;
            prop.visit_mut_children_with(self);

            let prop = prop.take();
            *n = if self.in_pat {
                self.super_to_update_call(super_token, prop).into()
            } else {
                *self.super_to_get_call(super_token, prop)
            };
        }
    }

    fn visit_mut_super_member_update(&mut self, n: &mut Expr) {
        if let Expr::Assign(AssignExpr { left, op, .. }) = n {
            debug_assert_ne!(*op, op!("="));

            if let AssignTarget::Simple(expr) = left {
                if let SimpleAssignTarget::SuperProp(SuperPropExpr {
                    obj: Super { span: super_token },
                    prop,
                    ..
                }) = expr.take()
                {
                    *expr = self.super_to_update_call(super_token, prop).into();
                }
            }
        }
    }

    fn super_to_get_call(&mut self, super_token: Span, prop: SuperProp) -> Box<Expr> {
        if self.constant_super {
            MemberExpr {
                span: super_token,
                obj: Box::new({
                    let name = self.super_class.clone().unwrap_or_else(|| {
                        quote_ident!(if self.is_static { "Function" } else { "Object" })
                    });
                    // in static default super class is Function.prototype
                    if self.is_static && self.super_class.is_some() {
                        Expr::Ident(name)
                    } else {
                        name.make_member(quote_ident!("prototype")).into()
                    }
                }),
                prop: match prop {
                    SuperProp::Ident(i) => MemberProp::Ident(i),
                    SuperProp::Computed(c) => MemberProp::Computed(c),
                },
            }
            .into()
        } else {
            let proto_arg = self.proto_arg();

            let prop_arg = prop_arg(prop).as_arg();

            let this_arg = self.this_arg(super_token).as_arg();

            CallExpr {
                span: super_token,
                callee: helper!(get),
                args: vec![proto_arg.as_arg(), prop_arg, this_arg],
                type_args: Default::default(),
            }
            .into()
        }
    }

    fn super_to_set_call(
        &mut self,
        super_token: Span,
        prop: SuperProp,
        op: AssignOp,
        rhs: Box<Expr>,
    ) -> Expr {
        debug_assert_eq!(op, op!("="));

        let this_expr = Box::new(match self.constructor_this_mark {
            Some(mark) => quote_ident!(super_token.apply_mark(mark), "_this").into(),
            None => ThisExpr { span: super_token }.into(),
        });

        if self.constant_super {
            let left = MemberExpr {
                span: super_token,
                obj: this_expr,
                prop: match prop {
                    SuperProp::Ident(i) => MemberProp::Ident(i),
                    SuperProp::Computed(c) => MemberProp::Computed(c),
                },
            };

            Expr::Assign(AssignExpr {
                span: super_token,
                left: left.into(),
                op,
                right: rhs,
            })
        } else {
            let proto_arg = self.proto_arg();

            let prop_arg = prop_arg(prop).as_arg();

            Expr::Call(CallExpr {
                span: super_token,
                callee: helper!(set),
                args: vec![
                    proto_arg.as_arg(),
                    prop_arg,
                    rhs.as_arg(),
                    this_expr.as_arg(),
                    // strict
                    true.as_arg(),
                ],
                type_args: Default::default(),
            })
        }
    }

    fn super_to_update_call(&mut self, super_token: Span, prop: SuperProp) -> MemberExpr {
        let proto_arg = self.proto_arg();

        let prop_arg = prop_arg(prop).as_arg();

        let this_arg = self.this_arg(super_token).as_arg();

        let expr = Expr::Call(CallExpr {
            span: super_token,
            callee: helper!(update),
            args: vec![
                proto_arg.as_arg(),
                prop_arg,
                this_arg,
                // strict
                true.as_arg(),
            ],
            type_args: Default::default(),
        });

        expr.make_member(quote_ident!("_"))
    }

    fn proto_arg(&mut self) -> Box<Expr> {
        let expr = if self.is_static {
            // Foo
            Box::new(Expr::Ident(self.class_name.clone()))
        } else {
            // Foo.prototype
            self.class_name
                .clone()
                .make_member(quote_ident!("prototype"))
                .into()
        };

        if self.constant_super {
            return expr;
        }

        let mut proto_arg = get_prototype_of(expr);

        if let Some(mark) = self.constructor_this_mark {
            let this = quote_ident!(DUMMY_SP.apply_mark(mark), "_this");

            proto_arg = SeqExpr {
                span: DUMMY_SP,
                exprs: vec![
                    Expr::Call(CallExpr {
                        span: DUMMY_SP,
                        callee: helper!(assert_this_initialized),
                        args: vec![this.as_arg()],
                        type_args: Default::default(),
                    })
                    .into(),
                    proto_arg,
                ],
            }
            .into()
        }

        proto_arg
    }

    fn this_arg(&self, super_token: Span) -> Expr {
        match self.constructor_this_mark {
            Some(mark) => quote_ident!(super_token.apply_mark(mark), "_this").into(),
            None => ThisExpr { span: super_token }.into(),
        }
    }
}

fn is_assign_to_super_prop(left: &AssignTarget) -> bool {
    match left {
        AssignTarget::Simple(expr) => expr.is_super_prop(),
        _ => false,
    }
}

fn prop_arg(prop: SuperProp) -> Expr {
    match prop {
        SuperProp::Ident(Ident {
            sym: value, span, ..
        }) => Expr::Lit(Lit::Str(Str {
            span,
            raw: None,
            value,
        })),
        SuperProp::Computed(c) => *c.expr,
    }
}