swc_ecma_compat_es2021/
logical_assignments.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
use std::mem;

use swc_common::{util::take::Take, DUMMY_SP};
use swc_ecma_ast::*;
use swc_ecma_transforms_base::perf::Parallel;
use swc_ecma_utils::{alias_ident_for, prepend_stmt};
use swc_ecma_visit::{noop_visit_mut_type, visit_mut_pass, VisitMut, VisitMutWith};
use swc_trace_macro::swc_trace;

pub fn logical_assignments() -> impl Pass {
    visit_mut_pass(Operators::default())
}

#[derive(Debug, Default)]
struct Operators {
    vars: Vec<VarDeclarator>,
}

impl Operators {
    fn memorize_prop(&mut self, c: ComputedPropName) -> (ComputedPropName, ComputedPropName) {
        let alias = alias_ident_for(&c.expr, "_ref");
        self.vars.push(VarDeclarator {
            span: DUMMY_SP,
            name: alias.clone().into(),
            init: None,
            definite: false,
        });

        (
            ComputedPropName {
                span: c.span,
                expr: AssignExpr {
                    span: DUMMY_SP,
                    left: alias.clone().into(),
                    op: op!("="),
                    right: c.expr,
                }
                .into(),
            },
            ComputedPropName {
                span: c.span,
                expr: Box::new(alias.into()),
            },
        )
    }
}

#[swc_trace]
impl Parallel for Operators {
    fn create(&self) -> Self {
        Default::default()
    }

    fn merge(&mut self, other: Self) {
        self.vars.extend(other.vars);
    }
}

#[swc_trace]
impl VisitMut for Operators {
    noop_visit_mut_type!(fail);

    fn visit_mut_expr(&mut self, e: &mut Expr) {
        e.visit_mut_children_with(self);

        if let Expr::Assign(AssignExpr {
            span,
            op: op @ (op!("&&=") | op!("||=") | op!("??=")),
            left: AssignTarget::Simple(left),
            right,
        }) = e
        {
            let (left_expr, r_assign_target) = match &mut *left {
                SimpleAssignTarget::SuperProp(SuperPropExpr {
                    span,
                    obj,
                    prop: SuperProp::Computed(c),
                }) => {
                    let (left, right) = self.memorize_prop(c.take());

                    (
                        Box::new(
                            SuperPropExpr {
                                span: *span,
                                obj: *obj,
                                prop: SuperProp::Computed(left),
                            }
                            .into(),
                        ),
                        Box::new(
                            SuperPropExpr {
                                span: *span,
                                obj: *obj,
                                prop: SuperProp::Computed(right),
                            }
                            .into(),
                        ),
                    )
                }
                SimpleAssignTarget::Member(m) => {
                    let (left_obj, right_obj) = match *m.obj.take() {
                        // TODO: local vars
                        obj @ Expr::This(_) => (obj.clone().into(), obj.into()),
                        obj => {
                            let alias = alias_ident_for(&obj, "_ref");
                            self.vars.push(VarDeclarator {
                                span: DUMMY_SP,
                                name: alias.clone().into(),
                                init: None,
                                definite: false,
                            });

                            (
                                AssignExpr {
                                    span: DUMMY_SP,
                                    op: op!("="),
                                    left: alias.clone().into(),
                                    right: obj.into(),
                                }
                                .into(),
                                alias.into(),
                            )
                        }
                    };

                    let (left_prop, right_prop) = match m.prop.take() {
                        MemberProp::Computed(c) => {
                            let (left, right) = self.memorize_prop(c);
                            (left.into(), right.into())
                        }
                        prop => (prop.clone(), prop),
                    };

                    (
                        MemberExpr {
                            span: DUMMY_SP,
                            obj: left_obj,
                            prop: left_prop,
                        }
                        .into(),
                        MemberExpr {
                            span: DUMMY_SP,
                            obj: right_obj,
                            prop: right_prop,
                        }
                        .into(),
                    )
                }
                _ => {
                    let expr: Box<Expr> = left.take().into();
                    (expr.clone(), expr)
                }
            };

            let right = AssignExpr {
                span: DUMMY_SP,
                op: op!("="),
                left: r_assign_target.try_into().unwrap(),
                right: right.take(),
            }
            .into();

            let op = match *op {
                op!("??=") => op!("??"),
                op!("&&=") => op!("&&"),
                op!("||=") => op!("||"),
                _ => unreachable!(),
            };

            *e = BinExpr {
                span: *span,
                op,
                left: left_expr,
                right,
            }
            .into();
        }
    }

    /// [swc_ecma_ast::ModuleItem] is the top level Item in the current
    /// implementation of JavaScript until the proposal for
    /// [module-declarations] and [module-expressions] are officially added.
    ///
    /// [module declarations]: https://github.com/tc39/proposal-module-declarations.
    /// [module-expressions]: https://github.com/tc39/proposal-module-expressions
    fn visit_mut_module_items(&mut self, n: &mut Vec<ModuleItem>) {
        let vars = self.vars.take();
        n.visit_mut_children_with(self);

        let vars = mem::replace(&mut self.vars, vars);
        if !vars.is_empty() {
            prepend_stmt(
                n,
                VarDecl {
                    kind: VarDeclKind::Var,
                    decls: vars,
                    ..Default::default()
                }
                .into(),
            )
        }
    }

    fn visit_mut_stmts(&mut self, n: &mut Vec<Stmt>) {
        let vars = self.vars.take();
        n.visit_mut_children_with(self);

        let vars = mem::replace(&mut self.vars, vars);
        if !vars.is_empty() {
            prepend_stmt(
                n,
                VarDecl {
                    kind: VarDeclKind::Var,
                    decls: vars,
                    ..Default::default()
                }
                .into(),
            )
        }
    }
}