swc_ecma_minifier/compress/optimize/
props.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
use swc_common::{util::take::Take, DUMMY_SP};
use swc_ecma_ast::*;
use swc_ecma_utils::{contains_this_expr, private_ident, prop_name_eq, ExprExt};

use super::{unused::PropertyAccessOpts, Optimizer};
use crate::util::deeply_contains_this_expr;

/// Methods related to the option `hoist_props`.
impl Optimizer<'_> {
    pub(super) fn hoist_props_of_var(
        &mut self,
        n: &mut VarDeclarator,
    ) -> Option<Vec<VarDeclarator>> {
        if !self.options.hoist_props {
            log_abort!("hoist_props: option is disabled");
            return None;
        }
        if self.ctx.is_exported {
            log_abort!("hoist_props: Exported variable is not hoisted");
            return None;
        }
        if self.ctx.in_top_level() && !self.options.top_level() {
            log_abort!("hoist_props: Top-level variable is not hoisted");
            return None;
        }

        if let Pat::Ident(name) = &mut n.name {
            if name.id.ctxt == self.marks.top_level_ctxt
                && self.options.top_retain.contains(&name.id.sym)
            {
                log_abort!("hoist_props: Variable `{}` is retained", name.id.sym);
                return None;
            }

            if !self.may_add_ident() {
                return None;
            }

            // If a variable is initialized multiple time, we currently don't do anything
            // smart.
            let usage = self.data.vars.get(&name.to_id())?;
            if usage.mutated()
                || usage.used_in_cond
                || usage.used_above_decl
                || usage.used_as_ref
                || usage.used_as_arg
                || usage.indexed_with_dynamic_key
                || usage.used_recursively
            {
                log_abort!("hoist_props: Variable `{}` is not a candidate", name.id);
                return None;
            }

            if usage.accessed_props.is_empty() {
                log_abort!(
                    "hoist_props: Variable `{}` is not accessed with known keys",
                    name.id
                );
                return None;
            }

            // We should abort if unknown property is used.
            let mut unknown_used_props = self
                .data
                .vars
                .get(&name.to_id())
                .map(|v| v.accessed_props.clone())
                .unwrap_or_default();

            if let Some(Expr::Object(init)) = n.init.as_deref() {
                for prop in &init.props {
                    let prop = match prop {
                        PropOrSpread::Spread(_) => return None,
                        PropOrSpread::Prop(prop) => prop,
                    };

                    match &**prop {
                        Prop::KeyValue(p) => {
                            if !is_expr_fine_for_hoist_props(&p.value) {
                                return None;
                            }

                            match &p.key {
                                PropName::Str(s) => {
                                    if let Some(v) = unknown_used_props.get_mut(&s.value) {
                                        *v = 0;
                                    }
                                }
                                PropName::Ident(i) => {
                                    if let Some(v) = unknown_used_props.get_mut(&i.sym) {
                                        *v = 0;
                                    }
                                }
                                _ => return None,
                            }
                        }
                        Prop::Shorthand(p) => {
                            if let Some(v) = unknown_used_props.get_mut(&p.sym) {
                                *v = 0;
                            }
                        }
                        _ => return None,
                    }
                }
            } else {
                if self.mode.should_be_very_correct() {
                    return None;
                }
            }

            if !unknown_used_props.iter().all(|(_, v)| *v == 0) {
                log_abort!("[x] unknown used props: {:?}", unknown_used_props);
                return None;
            }

            if let Some(init) = n.init.as_deref() {
                self.mode.store(name.to_id(), init);
            }

            let mut new_vars = Vec::new();

            let object = n.init.as_mut()?.as_mut_object()?;

            self.changed = true;
            report_change!(
                "hoist_props: Hoisting properties of a variable `{}`",
                name.id.sym
            );

            for prop in &mut object.props {
                let prop = match prop {
                    PropOrSpread::Spread(_) => unreachable!(),
                    PropOrSpread::Prop(prop) => prop,
                };

                let value = match &mut **prop {
                    Prop::KeyValue(p) => p.value.take(),
                    Prop::Shorthand(p) => p.clone().into(),
                    _ => unreachable!(),
                };

                let (key, suffix) = match &**prop {
                    Prop::KeyValue(p) => match &p.key {
                        PropName::Ident(i) => (i.sym.clone(), i.sym.clone()),
                        PropName::Str(s) => (
                            s.value.clone(),
                            s.value
                                .clone()
                                .replace(|c: char| !Ident::is_valid_continue(c), "$")
                                .into(),
                        ),
                        _ => unreachable!(),
                    },
                    Prop::Shorthand(p) => (p.sym.clone(), p.sym.clone()),
                    _ => unreachable!(),
                };

                let new_var_name = private_ident!(format!("{}_{}", name.id.sym, suffix));

                let new_var = VarDeclarator {
                    span: DUMMY_SP,
                    name: new_var_name.clone().into(),
                    init: Some(value),
                    definite: false,
                };

                self.vars
                    .hoisted_props
                    .insert((name.to_id(), key), new_var_name);

                new_vars.push(new_var);
            }
            // Mark the variable as dropped.
            n.name.take();

            return Some(new_vars);
        }

        None
    }

    pub(super) fn replace_props(&mut self, e: &mut Expr) {
        let member = match e {
            Expr::Member(m) => m,
            Expr::OptChain(m) => match &mut *m.base {
                OptChainBase::Member(m) => m,
                _ => return,
            },
            _ => return,
        };
        if let Expr::Ident(obj) = &*member.obj {
            let sym = match &member.prop {
                MemberProp::Ident(i) => &i.sym,
                MemberProp::Computed(e) => match &*e.expr {
                    Expr::Lit(Lit::Str(s)) => &s.value,
                    _ => return,
                },
                _ => return,
            };

            if let Some(value) = self
                .vars
                .hoisted_props
                .get(&(obj.to_id(), sym.clone()))
                .cloned()
            {
                report_change!("hoist_props: Inlining `{}.{}`", obj.sym, sym);
                self.changed = true;
                *e = value.into();
            }
        }
    }
}

fn is_expr_fine_for_hoist_props(value: &Expr) -> bool {
    match value {
        Expr::Ident(..) | Expr::Lit(..) | Expr::Arrow(..) | Expr::Class(..) => true,

        Expr::Fn(f) => !contains_this_expr(&f.function.body),

        Expr::Unary(u) => match u.op {
            op!("void") | op!("typeof") | op!("!") => is_expr_fine_for_hoist_props(&u.arg),
            _ => false,
        },

        Expr::Array(a) => a.elems.iter().all(|elem| match elem {
            Some(elem) => elem.spread.is_none() && is_expr_fine_for_hoist_props(&elem.expr),
            None => true,
        }),

        Expr::Object(o) => o.props.iter().all(|prop| match prop {
            PropOrSpread::Spread(_) => false,
            PropOrSpread::Prop(p) => match &**p {
                Prop::Shorthand(..) => true,
                Prop::KeyValue(p) => is_expr_fine_for_hoist_props(&p.value),
                _ => false,
            },
        }),

        _ => false,
    }
}

impl Optimizer<'_> {
    /// Converts `{ a: 1 }.a` into `1`.
    pub(super) fn handle_property_access(&mut self, e: &mut Expr) {
        if !self.options.props {
            return;
        }

        if self.ctx.is_update_arg || self.ctx.is_callee || self.ctx.is_exact_lhs_of_assign {
            return;
        }

        let me = match e {
            Expr::Member(m) => m,
            _ => return,
        };

        let key = match &me.prop {
            MemberProp::Ident(prop) => prop,
            _ => return,
        };

        let obj = match &mut *me.obj {
            Expr::Object(o) => o,
            _ => return,
        };

        let duplicate_prop = obj
            .props
            .iter()
            .filter(|prop| match prop {
                PropOrSpread::Spread(_) => false,
                PropOrSpread::Prop(p) => match &**p {
                    Prop::Shorthand(p) => p.sym == key.sym,
                    Prop::KeyValue(p) => prop_name_eq(&p.key, &key.sym),
                    Prop::Assign(p) => p.key.sym == key.sym,
                    Prop::Getter(p) => prop_name_eq(&p.key, &key.sym),
                    Prop::Setter(p) => prop_name_eq(&p.key, &key.sym),
                    Prop::Method(p) => prop_name_eq(&p.key, &key.sym),
                },
            })
            .count()
            != 1;
        if duplicate_prop {
            return;
        }

        if obj.props.iter().any(|prop| match prop {
            PropOrSpread::Spread(s) => self.should_preserve_property_access(
                &s.expr,
                PropertyAccessOpts {
                    allow_getter: false,
                    only_ident: false,
                },
            ),
            PropOrSpread::Prop(p) => match &**p {
                Prop::Shorthand(..) => false,
                Prop::KeyValue(p) => {
                    p.key.is_computed()
                        || p.value.may_have_side_effects(&self.ctx.expr_ctx)
                        || deeply_contains_this_expr(&p.value)
                }
                Prop::Assign(p) => {
                    p.value.may_have_side_effects(&self.ctx.expr_ctx)
                        || deeply_contains_this_expr(&p.value)
                }
                Prop::Getter(p) => p.key.is_computed(),
                Prop::Setter(p) => p.key.is_computed(),
                Prop::Method(p) => p.key.is_computed(),
            },
        }) {
            log_abort!("Property accesses should not be inlined to preserve side effects");
            return;
        }

        for prop in &obj.props {
            match prop {
                PropOrSpread::Spread(_) => {}
                PropOrSpread::Prop(p) => match &**p {
                    Prop::Shorthand(_) => {}
                    Prop::KeyValue(p) => {
                        if prop_name_eq(&p.key, &key.sym) {
                            report_change!(
                                "properties: Inlining a key-value property `{}`",
                                key.sym
                            );
                            self.changed = true;
                            *e = *p.value.clone();
                            return;
                        }
                    }
                    Prop::Assign(_) => {}
                    Prop::Getter(_) => {}
                    Prop::Setter(_) => {}
                    Prop::Method(_) => {}
                },
            }
        }
    }
}