swc_ecma_minifier 48.0.0

EcmaScript code minifier.
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();
            }
        }
    }
}