swc_ecma_minifier/compress/optimize/rest_params.rs
1use swc_ecma_ast::*;
2
3use super::Optimizer;
4
5/// Methods related to rest parameter optimization.
6impl Optimizer<'_> {
7 /// Removes unused rest parameters from functions.
8 ///
9 /// Example:
10 /// ```js
11 /// function f(a, ...b) {
12 /// console.log(a);
13 /// }
14 /// ```
15 /// =>
16 /// ```js
17 /// function f(a) {
18 /// console.log(a);
19 /// }
20 /// ```
21 pub(super) fn drop_unused_rest_params(&mut self, f: &mut Function) {
22 if !self.options.arguments && !self.options.unused {
23 return;
24 }
25
26 // Don't optimize if there's no rest parameter
27 if f.params.is_empty() {
28 return;
29 }
30
31 let last_param = match f.params.last() {
32 Some(p) => p,
33 None => return,
34 };
35
36 // Check if the last parameter is a rest parameter
37 let rest_pat = match &last_param.pat {
38 Pat::Rest(rest) => rest,
39 _ => return,
40 };
41
42 // Get the identifier of the rest parameter
43 let rest_id = match &*rest_pat.arg {
44 Pat::Ident(BindingIdent { id, .. }) => id.to_id(),
45 _ => return,
46 };
47
48 // Check if the rest parameter is used using ProgramData
49 if let Some(usage) = self.data.vars.get(&rest_id) {
50 // If the parameter is not referenced, we can remove it
51 if usage.ref_count == 0 {
52 self.changed = true;
53 report_change!("rest_params: Removing unused rest parameter");
54 f.params.pop();
55 }
56 }
57 }
58}