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
use swc_ecma_ast::*;
use super::Optimizer;
/// Methods related to rest parameter optimization.
impl Optimizer<'_> {
/// Removes unused rest parameters from functions.
///
/// Example:
/// ```js
/// function f(a, ...b) {
/// console.log(a);
/// }
/// ```
/// =>
/// ```js
/// function f(a) {
/// console.log(a);
/// }
/// ```
pub(super) fn drop_unused_rest_params(&mut self, f: &mut Function) {
if !self.options.arguments && !self.options.unused {
return;
}
// Don't optimize if there's no rest parameter
if f.params.is_empty() {
return;
}
let last_param = match f.params.last() {
Some(p) => p,
None => return,
};
// Check if the last parameter is a rest parameter
let rest_pat = match &last_param.pat {
Pat::Rest(rest) => rest,
_ => return,
};
// Get the identifier of the rest parameter
let rest_id = match &*rest_pat.arg {
Pat::Ident(BindingIdent { id, .. }) => id.to_id(),
_ => return,
};
// Check if the rest parameter is used using ProgramData
if let Some(usage) = self.data.vars.get(&rest_id) {
// If the parameter is not referenced, we can remove it
if usage.ref_count == 0 {
self.changed = true;
report_change!("rest_params: Removing unused rest parameter");
f.params.pop();
}
}
}
}