swc_ecma_minifier/compress/optimize/
unused.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
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
use swc_atoms::js_word;
use swc_common::{util::take::Take, Span, DUMMY_SP};
use swc_ecma_ast::*;
use swc_ecma_usage_analyzer::util::is_global_var_with_pure_property_access;
use swc_ecma_utils::contains_ident_ref;

use super::Optimizer;
#[cfg(feature = "debug")]
use crate::debug::dump;
use crate::{
    compress::optimize::util::extract_class_side_effect, mode::Mode, option::PureGetterOption,
};

#[derive(Debug, Default, Clone, Copy)]
pub(crate) struct PropertyAccessOpts {
    pub allow_getter: bool,

    pub only_ident: bool,
}

/// Methods related to the option `unused`.
impl<M> Optimizer<'_, M>
where
    M: Mode,
{
    #[cfg_attr(feature = "debug", tracing::instrument(skip_all))]
    pub(super) fn drop_unused_var_declarator(
        &mut self,
        var: &mut VarDeclarator,
        storage_for_side_effects: &mut Option<Box<Expr>>,
    ) {
        if var.name.is_invalid() {
            return;
        }

        if !self.options.top_level()
            && (self.ctx.is_top_level_for_block_level_vars() || self.ctx.in_top_level())
            && !var.span.has_mark(self.marks.non_top_level)
        {
            match self.ctx.var_kind {
                Some(VarDeclKind::Const) | Some(VarDeclKind::Let) => {
                    if self.ctx.is_top_level_for_block_level_vars() {
                        log_abort!("unused: Top-level (block level)");
                        return;
                    }
                }
                _ => {
                    if self.ctx.in_top_level() {
                        log_abort!("unused: Top-level");
                        return;
                    }
                }
            }
        }

        #[cfg(debug_assertions)]
        let had_init = var.init.is_some();

        match &mut var.init {
            Some(init) => match &**init {
                Expr::Invalid(..) => {
                    self.drop_unused_vars(var.span, &mut var.name, None);
                }
                // I don't know why, but terser preserves this
                Expr::Fn(FnExpr { function, .. })
                    if matches!(&**function, Function { is_async: true, .. }) => {}
                _ => {
                    self.drop_unused_vars(var.span, &mut var.name, Some(init));

                    if var.name.is_invalid() {
                        report_change!("unused: Removing an unused variable declarator");
                        let side_effects = self.ignore_return_value(init).map(Box::new);
                        if let Some(e) = side_effects {
                            *storage_for_side_effects = Some(e);
                        }
                    }
                }
            },
            None => {
                self.drop_unused_vars(var.span, &mut var.name, var.init.as_deref_mut());
            }
        }

        if var.name.is_invalid() {
            return;
        }

        #[cfg(debug_assertions)]
        {
            if let Some(VarDeclKind::Const | VarDeclKind::Let) = self.ctx.var_kind {
                if had_init && var.init.is_none() {
                    unreachable!("const/let variable without initializer: {:#?}", var);
                }
            }
        }
    }

    #[cfg_attr(feature = "debug", tracing::instrument(skip_all))]
    pub(super) fn drop_unused_param(&mut self, pat: &mut Pat, ignore_fn_length: bool) {
        if !self.options.unused && !self.options.reduce_fns {
            return;
        }

        if let Some(scope) = self.data.scopes.get(&self.ctx.scope) {
            if scope.has_eval_call || scope.has_with_stmt {
                return;
            }
        }

        if !ignore_fn_length {
            // Preserve `length` of function.
            if pat.is_ident() {
                return;
            }
        }

        self.take_pat_if_unused(DUMMY_SP, pat, None, false)
    }

    #[cfg_attr(feature = "debug", tracing::instrument(skip_all))]
    pub(super) fn drop_unused_vars(
        &mut self,
        var_declarator_span: Span,
        name: &mut Pat,
        init: Option<&mut Expr>,
    ) {
        if self.ctx.is_exported || self.ctx.in_asm {
            return;
        }

        let has_mark = var_declarator_span.has_mark(self.marks.non_top_level);

        if !has_mark {
            if (!self.options.unused && !self.options.side_effects)
                || self.ctx.in_var_decl_of_for_in_or_of_loop
            {
                return;
            }
        }

        trace_op!("unused: drop_unused_vars({})", dump(&*name, false));

        // Top-level
        if !has_mark {
            match self.ctx.var_kind {
                Some(VarDeclKind::Var) => {
                    if !self.options.top_level() && self.options.top_retain.is_empty() {
                        if self.ctx.in_top_level() {
                            log_abort!(
                                "unused: [X] Preserving `var` `{}` because it's top-level",
                                dump(&*name, false)
                            );

                            return;
                        }
                    }
                }
                Some(VarDeclKind::Let) | Some(VarDeclKind::Const) => {
                    if !self.options.top_level() && self.ctx.is_top_level_for_block_level_vars() {
                        log_abort!(
                            "unused: Preserving block scoped var `{}` because it's top-level",
                            dump(&*name, false)
                        );

                        return;
                    }
                }
                None => {}
            }
        }

        if let Some(scope) = self.data.scopes.get(&self.ctx.scope) {
            if scope.has_eval_call || scope.has_with_stmt {
                log_abort!(
                    "unused: Preserving `{}` because of usages",
                    dump(&*name, false)
                );
                return;
            }
        }

        if !name.is_ident() && init.is_none() {
            return;
        }

        self.take_pat_if_unused(var_declarator_span, name, init, true);
    }

    #[cfg_attr(feature = "debug", tracing::instrument(skip_all))]
    pub(super) fn drop_unused_params(&mut self, params: &mut Vec<Param>) {
        for param in params.iter_mut().rev() {
            self.take_pat_if_unused(DUMMY_SP, &mut param.pat, None, false);

            if !param.pat.is_invalid() {
                return;
            }
        }
    }

    #[cfg_attr(feature = "debug", tracing::instrument(skip_all))]
    fn take_ident_of_pat_if_unused(
        &mut self,
        parent_span: Span,
        i: &mut Ident,
        init: Option<&mut Expr>,
    ) {
        trace_op!("unused: Checking identifier `{}`", i);

        if !parent_span.has_mark(self.marks.non_top_level)
            && self.options.top_retain.contains(&i.sym)
        {
            log_abort!("unused: [X] Top-retain");
            return;
        }

        if let Some(v) = self.data.vars.get(&i.to_id()).cloned() {
            if v.ref_count == 0
                && v.usage_count == 0
                && !v.reassigned()
                && !v.has_property_mutation
                && !v.declared_as_catch_param
            {
                self.changed = true;
                report_change!(
                    "unused: Dropping a variable '{}{:?}' because it is not used",
                    i.sym,
                    i.span.ctxt
                );
                // This will remove variable.
                i.take();
                return;
            }

            if v.ref_count == 0 && v.usage_count == 0 {
                if let Some(e) = init {
                    if let Some(VarDeclKind::Const | VarDeclKind::Let) = self.ctx.var_kind {
                        if let Expr::Lit(Lit::Null(..)) = e {
                            return;
                        }
                    }

                    let ret = self.ignore_return_value(e);
                    if let Some(ret) = ret {
                        *e = ret;
                    } else {
                        if let Some(VarDeclKind::Const | VarDeclKind::Let) = self.ctx.var_kind {
                            *e = Null { span: DUMMY_SP }.into();
                        } else {
                            *e = Expr::Invalid(Invalid { span: DUMMY_SP });
                        }
                    }
                }
            }

            log_abort!(
                "unused: Cannot drop ({}) because it's used",
                dump(&*i, false)
            );
        }
    }

    pub(crate) fn should_preserve_property_access(
        &self,
        e: &Expr,
        opts: PropertyAccessOpts,
    ) -> bool {
        if opts.only_ident && !e.is_ident() {
            return true;
        }

        match e {
            Expr::Ident(e) => {
                if e.span.ctxt.outer() == self.marks.unresolved_mark {
                    if is_global_var_with_pure_property_access(&e.sym) {
                        return false;
                    }
                }

                if let Some(usage) = self.data.vars.get(&e.to_id()) {
                    if !usage.declared {
                        return true;
                    }

                    if !usage.mutated
                        && !usage.reassigned()
                        && usage.no_side_effect_for_member_access
                    {
                        return false;
                    }
                }
            }

            Expr::Object(o) => {
                // We should check properties
                return o.props.iter().any(|p| match p {
                    PropOrSpread::Spread(p) => self.should_preserve_property_access(&p.expr, opts),
                    PropOrSpread::Prop(p) => match &**p {
                        Prop::Assign(_) => true,
                        Prop::Getter(_) => !opts.allow_getter,
                        Prop::Shorthand(_) => false,
                        Prop::KeyValue(..) => false,

                        Prop::Setter(_) => false,
                        Prop::Method(_) => false,
                    },
                });
            }

            Expr::Paren(p) => return self.should_preserve_property_access(&p.expr, opts),

            Expr::Fn(..) | Expr::Arrow(..) | Expr::Array(..) | Expr::Class(..) => {
                return false;
            }

            Expr::Seq(e) => {
                if let Some(last) = e.exprs.last() {
                    return self.should_preserve_property_access(last, opts);
                }
                return true;
            }

            _ => {}
        }

        true
    }

    /// `parent_span` should be [Span] of [VarDeclarator] or [AssignExpr]
    #[allow(clippy::only_used_in_recursion)]
    #[cfg_attr(feature = "debug", tracing::instrument(skip_all))]
    pub(super) fn take_pat_if_unused(
        &mut self,
        parent_span: Span,
        name: &mut Pat,
        mut init: Option<&mut Expr>,
        is_var_decl: bool,
    ) {
        if self.ctx.is_exported {
            return;
        }

        trace_op!("unused: take_pat_if_unused({})", dump(&*name, false));

        if !name.is_ident() {
            // TODO: Use smart logic
            if self.options.pure_getters != PureGetterOption::Bool(true) {
                return;
            }

            if let Some(init) = init.as_mut() {
                if self.should_preserve_property_access(
                    init,
                    PropertyAccessOpts {
                        allow_getter: false,
                        only_ident: false,
                    },
                ) {
                    return;
                }
            }
        }

        match name {
            Pat::Ident(i) => {
                self.take_ident_of_pat_if_unused(parent_span, &mut i.id, init);

                // Removed
                if i.id.is_dummy() {
                    name.take();
                }
            }

            Pat::Array(arr) => {
                for (idx, elem) in arr.elems.iter_mut().enumerate() {
                    match elem {
                        Some(p) => {
                            if p.is_ident() {
                                continue;
                            }

                            let elem = init
                                .as_mut()
                                .and_then(|expr| self.access_numeric_property(expr, idx));

                            self.take_pat_if_unused(parent_span, p, elem, is_var_decl);
                        }
                        None => {}
                    }
                }

                arr.elems
                    .retain(|elem| !matches!(elem, Some(Pat::Invalid(..))))
            }

            Pat::Object(obj) => {
                // If a rest pattern exists, we can't remove anything at current level.
                if obj
                    .props
                    .iter()
                    .any(|p| matches!(p, ObjectPatProp::Rest(_)))
                {
                    return;
                }

                for prop in &mut obj.props {
                    match prop {
                        ObjectPatProp::KeyValue(p) => {
                            if p.key.is_computed() {
                                continue;
                            }

                            self.take_pat_if_unused(parent_span, &mut p.value, None, is_var_decl);
                        }
                        ObjectPatProp::Assign(AssignPatProp {
                            key, value: None, ..
                        }) => {
                            self.take_ident_of_pat_if_unused(parent_span, key, None);
                        }
                        _ => {}
                    }
                }

                obj.props.retain(|p| {
                    match p {
                        ObjectPatProp::KeyValue(p) => {
                            if p.value.is_invalid() {
                                return false;
                            }
                        }
                        ObjectPatProp::Assign(p) => {
                            if p.key.is_dummy() {
                                return false;
                            }
                        }
                        ObjectPatProp::Rest(_) => {}
                    }

                    true
                });

                if obj.props.is_empty() {
                    name.take();
                }
            }

            Pat::Rest(_) => {}
            Pat::Assign(_) => {
                // TODO
            }
            _ => {}
        }
    }

    /// Creates an empty [VarDecl] if `decl` should be removed.
    #[cfg_attr(feature = "debug", tracing::instrument(skip_all))]
    pub(super) fn drop_unused_decl(&mut self, decl: &mut Decl) {
        if self.ctx.is_exported {
            return;
        }

        if !self.options.top_level() && self.ctx.is_top_level_for_block_level_vars() {
            return;
        }

        if !self.options.unused {
            return;
        }

        if let Some(scope) = self.data.scopes.get(&self.ctx.scope) {
            if scope.has_eval_call || scope.has_with_stmt {
                return;
            }
        }

        match decl {
            Decl::Class(ClassDecl { ident, class, .. }) => {
                if ident.sym == js_word!("arguments") {
                    return;
                }

                // Fix https://github.com/swc-project/swc/issues/5588
                let may_have_side_effect = class.body.iter().any(|m| match m {
                    ClassMember::ClassProp(ClassProp {
                        is_static: true,
                        value: Some(_),
                        ..
                    })
                    | ClassMember::PrivateProp(PrivateProp {
                        is_static: true,
                        value: Some(_),
                        ..
                    }) => true,
                    ClassMember::StaticBlock(StaticBlock {
                        body: BlockStmt { stmts, .. },
                        ..
                    }) if !stmts.is_empty() => true,
                    _ => false,
                });
                if may_have_side_effect {
                    return;
                }

                // If it is not used, drop it.
                if self
                    .data
                    .vars
                    .get(&ident.to_id())
                    .map(|v| v.usage_count == 0 && !v.has_property_mutation)
                    .unwrap_or(false)
                {
                    self.changed = true;
                    report_change!(
                        "unused: Dropping a decl '{}{:?}' because it is not used",
                        ident.sym,
                        ident.span.ctxt
                    );
                    // This will remove the declaration.
                    let class = decl.take().class().unwrap();
                    let mut side_effects = extract_class_side_effect(&self.expr_ctx, *class.class);

                    if !side_effects.is_empty() {
                        self.prepend_stmts.push(Stmt::Expr(ExprStmt {
                            span: DUMMY_SP,
                            expr: if side_effects.len() > 1 {
                                Expr::Seq(SeqExpr {
                                    span: DUMMY_SP,
                                    exprs: side_effects,
                                })
                                .into()
                            } else {
                                side_effects.remove(0)
                            },
                        }))
                    }
                }
            }
            Decl::Fn(FnDecl { ident, .. }) => {
                // We should skip if the name of decl is arguments.
                if ident.sym == js_word!("arguments") {
                    return;
                }

                // If it is not used, drop it.
                if self
                    .data
                    .vars
                    .get(&ident.to_id())
                    .map(|v| v.usage_count == 0 && !v.has_property_mutation)
                    .unwrap_or(false)
                {
                    self.changed = true;
                    report_change!(
                        "unused: Dropping a decl '{}{:?}' because it is not used",
                        ident.sym,
                        ident.span.ctxt
                    );
                    // This will remove the declaration.
                    decl.take();
                }
            }

            Decl::Var(_) => {
                // Variable declarations are handled by other functions.
            }

            Decl::TsInterface(_) | Decl::TsTypeAlias(_) | Decl::TsEnum(_) | Decl::TsModule(_) => {
                // Nothing to do. We might change this to unreachable!()
            }
        }
    }

    /// This should be only called from ignore_return_value
    #[cfg_attr(feature = "debug", tracing::instrument(skip_all))]
    pub(super) fn drop_unused_update(&mut self, e: &mut Expr) {
        if !self.options.unused {
            return;
        }

        let update = match e {
            Expr::Update(u) => u,
            _ => return,
        };

        if let Expr::Ident(arg) = &*update.arg {
            if let Some(var) = self.data.vars.get(&arg.to_id()) {
                // Update is counted as usage
                if var.declared && var.is_fn_local && var.usage_count == 1 {
                    self.changed = true;
                    report_change!(
                        "unused: Dropping an update '{}{:?}' because it is not used",
                        arg.sym,
                        arg.span.ctxt
                    );
                    // This will remove the update.
                    e.take();
                }
            }
        }
    }

    /// This should be only called from ignore_return_value
    #[cfg_attr(feature = "debug", tracing::instrument(skip_all))]
    pub(super) fn drop_unused_op_assign(&mut self, e: &mut Expr) {
        if !self.options.unused {
            return;
        }

        if self.ctx.is_delete_arg {
            return;
        }

        if self.data.top.has_eval_call || self.data.top.has_with_stmt {
            return;
        }

        let assign = match e {
            Expr::Assign(AssignExpr { op: op!("="), .. }) => return,
            // RHS may not be evaluated
            Expr::Assign(AssignExpr { op, .. }) if op.may_short_circuit() => return,
            Expr::Assign(e) => e,
            _ => return,
        };
        assign.left.map_with_mut(|left| left.normalize_ident());

        if let PatOrExpr::Pat(p) = &assign.left {
            if let Pat::Ident(left) = &**p {
                if let Some(var) = self.data.vars.get(&left.to_id()) {
                    // TODO: We don't need fn_local check
                    if var.declared && var.is_fn_local && var.usage_count == 1 {
                        self.changed = true;
                        report_change!(
                            "unused: Dropping an op-assign '{}{:?}' because it is not used",
                            left.id.sym,
                            left.id.span.ctxt
                        );
                        // This will remove the op-assign.
                        *e = *assign.right.take();
                    }
                }
            }
        }
    }

    #[cfg_attr(feature = "debug", tracing::instrument(skip_all))]
    pub(super) fn drop_unused_assignments(&mut self, e: &mut Expr) {
        if self.ctx.is_delete_arg {
            return;
        }

        if self.data.top.has_eval_call || self.data.top.has_with_stmt {
            return;
        }

        let assign = match e {
            Expr::Assign(e) => e,
            _ => return,
        };

        let has_mark = assign.span.has_mark(self.marks.non_top_level);

        if !has_mark && !self.options.unused {
            return;
        }

        let used_arguments = self
            .data
            .scopes
            .get(&self.ctx.scope)
            .unwrap_or_else(|| {
                unreachable!(
                    "scope should exist\nScopes: {:?};\nCtxt: {:?}",
                    self.data.scopes, self.ctx.scope
                )
            })
            .used_arguments;

        trace_op!(
            "unused: drop_unused_assignments: Target: `{}`",
            dump(&assign.left, false)
        );

        if !has_mark
            && (!self.options.top_level() && self.options.top_retain.is_empty())
            && self.ctx.in_top_level()
        {
            log_abort!(
                "unused: Preserving assignment to `{}` because it's top-level",
                dump(&assign.left, false)
            );
            return;
        }

        assign.left.map_with_mut(|v| v.normalize_ident());

        match &mut assign.left {
            PatOrExpr::Expr(_) => {
                log_abort!(
                    "unused: Preserving assignment to `{}` because it's an expression",
                    dump(&assign.left, false)
                );
            }
            PatOrExpr::Pat(left) => {
                if let Pat::Ident(i) = &**left {
                    if self.options.top_retain.contains(&i.id.sym) {
                        return;
                    }

                    if let Some(var) = self.data.vars.get(&i.to_id()) {
                        // technically this is inline
                        if !var.inline_prevented
                            && var.usage_count == 0
                            && var.declared
                            && (!var.declared_as_fn_param || !used_arguments || self.ctx.in_strict)
                        {
                            report_change!(
                                "unused: Dropping assignment to var '{}{:?}', which is never used",
                                i.id.sym,
                                i.id.span.ctxt
                            );
                            self.changed = true;
                            if self.ctx.is_this_aware_callee {
                                *e = Expr::Seq(SeqExpr {
                                    span: DUMMY_SP,
                                    exprs: vec![0.into(), assign.right.take()],
                                })
                            } else {
                                *e = *assign.right.take();
                            }
                        } else {
                            log_abort!(
                                "unused: Preserving assignment to `{}` because of usage: {:?}",
                                dump(&assign.left, false),
                                var
                            )
                        }
                    }
                }
            }
        }
    }

    /// Make `name` [None] if the name is not used.
    #[cfg_attr(feature = "debug", tracing::instrument(skip_all))]
    pub(super) fn remove_name_if_not_used(&mut self, name: &mut Option<Ident>) {
        if !self.options.unused {
            return;
        }

        if self.ctx.is_exported {
            return;
        }

        if let Some(i) = &name {
            let can_remove_ident = self
                .data
                .vars
                .get(&i.to_id())
                .map(|v| {
                    (!v.used_recursively && v.ref_count == 0 && v.usage_count == 0)
                        || v.var_kind.is_some()
                })
                .unwrap_or(false);

            if can_remove_ident {
                self.changed = true;
                report_change!("Removing ident of an class / function expression");
                *name = None;
            }
        }
    }

    pub(super) fn remove_duplicate_var_decls(&mut self, s: &mut Stmt) -> Option<()> {
        if !self.options.unused {
            return None;
        }

        let var = match s {
            Stmt::Decl(Decl::Var(v)) => v,
            _ => return None,
        };

        for d in var.decls.iter_mut() {
            if d.init.is_none() {
                if let Pat::Ident(name) = &d.name {
                    if let Some(usage) = self.data.vars.get_mut(&name.to_id()) {
                        if usage.is_fn_local
                            && usage.declared_as_fn_param
                            && usage.declared_count >= 2
                        {
                            d.name.take();
                            usage.declared_count -= 1;

                            report_change!(
                                "Removing a variable statement because it's a function parameter"
                            );
                            self.changed = true;
                        }
                    }
                }
            }
        }

        var.decls.retain(|v| !v.name.is_invalid());

        None
    }

    /// `var Parser = function Parser() {};` => `var Parser = function () {}`
    pub(super) fn remove_duplicate_name_of_function(&mut self, v: &mut VarDeclarator) {
        if !self.options.unused {
            return;
        }

        if let Some(Expr::Fn(f)) = v.init.as_deref_mut() {
            if f.ident.is_none() {
                return;
            }

            if contains_ident_ref(&f.function.body, &f.ident.as_ref().unwrap().to_id()) {
                return;
            }

            self.changed = true;
            report_change!(
                "unused: Removing the name of a function expression because it's not used by it'"
            );
            f.ident = None;
        }
    }
}