swc_ecma_minifier 61.0.7

EcmaScript code minifier.
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
use std::borrow::Borrow;

use swc_common::{util::take::Take, DUMMY_SP};
use swc_ecma_ast::*;
use swc_ecma_transforms_base::rename::contains_eval;
use swc_ecma_utils::{contains_this_expr, private_ident, prop_name_eq, ExprExt};

use super::{unused::PropertyAccessOpts, BitCtx, Optimizer};
use crate::{program_data::VarUsageInfoFlags, 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.bit_ctx.contains(BitCtx::IsExported) {
            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.flags.intersects(
                    VarUsageInfoFlags::INLINE_PREVENTED
                        .union(VarUsageInfoFlags::USED_ABOVE_DECL)
                        .union(VarUsageInfoFlags::USED_AS_REF)
                        .union(VarUsageInfoFlags::USED_AS_ARG)
                        .union(VarUsageInfoFlags::INDEXED_WITH_DYNAMIC_KEY)
                        .union(VarUsageInfoFlags::USED_RECURSIVELY),
                )
            {
                log_abort!("hoist_props: Variable `{}` is not a candidate", name.id);
                return None;
            }

            // `callee_count` is tracked for the object, not for each property. Once
            // properties are hoisted, all replacements lose the original object
            // receiver, so every property must be safe in callee position if any
            // property is called.
            let may_be_callee = usage.callee_count != 0;

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

            let accessed_props_count: u32 = usage.accessed_props.values().sum();
            if accessed_props_count < usage.ref_count {
                log_abort!(
                    "hoist_props: Variable `{}` is directly used without accessing its properties",
                    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,
                        #[cfg(swc_ast_unknown)]
                        _ => panic!("unable to access unknown nodes"),
                    };

                    match &**prop {
                        Prop::KeyValue(p) => {
                            if !is_expr_fine_for_hoist_props(&p.value, may_be_callee) {
                                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.borrow()) {
                                        *v = 0;
                                    }
                                }
                                _ => return None,
                            }
                        }
                        Prop::Shorthand(p) => {
                            if may_be_callee {
                                return None;
                            }

                            if let Some(v) = unknown_used_props.get_mut(p.sym.borrow()) {
                                *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,
                    #[cfg(swc_ast_unknown)]
                    _ => panic!("unable to access unknown nodes"),
                };

                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().into(), i.sym.clone()),
                        PropName::Str(s) => (
                            s.value.clone(),
                            s.value
                                .code_points()
                                .map(|c| {
                                    c.to_char()
                                        .filter(|&c| Ident::is_valid_start(c))
                                        .unwrap_or('$')
                                })
                                .collect::<String>()
                                .into(),
                        ),
                        _ => unreachable!(),
                    },
                    Prop::Shorthand(p) => (p.sym.clone().into(), 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.borrow(),
                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, may_be_callee: bool) -> bool {
    match value {
        // We do not track fixed values for every identifier, so detaching an
        // identifier from an object may change the `this` received by the callee.
        Expr::Ident(..) => !may_be_callee,

        Expr::Lit(..) | Expr::Class(..) => true,

        // Arrows keep their lexical `this` when detached from an object.
        Expr::Arrow(..) => true,

        Expr::Fn(f) => {
            // Parameter initializers run with the call receiver too, so checking
            // only the body can miss receiver-sensitive default values.
            !contains_this_expr(&f.function.params)
                && !contains_this_expr(&f.function.body)
                && (!may_be_callee || !contains_eval(&f.function, false))
        }

        // Expressions nested in these containers cannot receive the original
        // object's receiver, so do not propagate `may_be_callee` into them.
        Expr::Unary(u) => match u.op {
            op!("void") | op!("typeof") | op!("!") => is_expr_fine_for_hoist_props(&u.arg, false),
            _ => 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, false),
            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,
            },
            #[cfg(swc_ast_unknown)]
            _ => panic!("unable to access unknown nodes"),
        }),

        _ => 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
            .bit_ctx
            .intersects(BitCtx::IsUpdateArg | BitCtx::IsExactLhsOfAssign)
            || self.ctx.bit_ctx.contains(BitCtx::IsCallee)
                && (!self.options.hoist_props
                    || !self.ctx.bit_ctx.contains(BitCtx::IsCallCallee)
                    || self.ctx.bit_ctx.contains(BitCtx::IsNoInlineCallee))
        {
            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),
                    #[cfg(swc_ast_unknown)]
                    _ => panic!("unable to access unknown nodes"),
                },
                #[cfg(swc_ast_unknown)]
                _ => panic!("unable to access unknown nodes"),
            })
            .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(),
                #[cfg(swc_ast_unknown)]
                _ => panic!("unable to access unknown nodes"),
            },
            #[cfg(swc_ast_unknown)]
            _ => panic!("unable to access unknown nodes"),
        }) {
            log_abort!("Property accesses should not be inlined to preserve side effects");
            return;
        }

        for (idx, prop) in obj.props.iter().enumerate() {
            match prop {
                PropOrSpread::Spread(_) => {}
                PropOrSpread::Prop(p) => match &**p {
                    Prop::Shorthand(_) => {}
                    Prop::KeyValue(p) => {
                        if prop_name_eq(&p.key, &key.sym) {
                            if self.ctx.bit_ctx.contains(BitCtx::IsCallee)
                                && !is_expr_fine_for_hoist_props(&p.value, true)
                            {
                                return;
                            }

                            // A later spread can replace this property even if reading the
                            // spread itself has no observable side effect. Do not detach the
                            // earlier callee unless it remains the property's final value.
                            if self.ctx.bit_ctx.contains(BitCtx::IsCallee)
                                && obj.props[idx + 1..]
                                    .iter()
                                    .any(|prop| matches!(prop, PropOrSpread::Spread(_)))
                            {
                                return;
                            }

                            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(_) => {}
                    #[cfg(swc_ast_unknown)]
                    _ => panic!("unable to access unknown nodes"),
                },
                #[cfg(swc_ast_unknown)]
                _ => panic!("unable to access unknown nodes"),
            }
        }
    }
}