swc_ecma_minifier/compress/optimize/dead_code.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
use swc_common::util::take::Take;
use swc_ecma_ast::*;
use super::Optimizer;
use crate::mode::Mode;
/// Methods related to option `dead_code`.
impl<M> Optimizer<'_, M>
where
M: Mode,
{
/// Optimize return value or argument of throw.
///
/// This methods removes some useless assignments.
///
/// # Example
///
/// Note: `a` being declared in the function is important in the example
/// below.
///
/// ```ts
/// function foo(){
/// var a;
/// throw a = x();
/// }
/// ```
///
/// can be optimized as
///
/// ```ts
/// function foo(){
/// var a; // Will be dropped in next pass.
/// throw x();
/// }
/// ```
pub(super) fn optimize_in_fn_termination(&mut self, e: &mut Expr) {
if !self.options.dead_code {
return;
}
// A return statement in a try block may not terminate function.
if self.ctx.in_try_block {
return;
}
if let Expr::Assign(assign @ AssignExpr { op: op!("="), .. }) = e {
self.optimize_in_fn_termination(&mut assign.right);
// We only handle identifiers on lhs for now.
if let Some(lhs) = assign.left.as_ident() {
//
if self
.data
.vars
.get(&lhs.to_id())
.map(|var| var.is_fn_local && !var.declared_as_fn_param)
.unwrap_or(false)
{
report_change!(
"dead_code: Dropping an assignment to a variable declared in function \
because function is being terminated"
);
self.changed = true;
*e = *assign.right.take();
return;
}
}
}
if let Expr::Assign(assign) = e {
// x += 1 => x + 1
if let Some(op) = assign.op.to_update() {
if let Some(lhs) = assign.left.as_ident() {
//
if self
.data
.vars
.get(&lhs.to_id())
.map(|var| var.is_fn_local)
.unwrap_or(false)
{
report_change!(
"dead_code: Converting an assignment into a binary expression in \
function termination"
);
self.changed = true;
*e = Expr::Bin(BinExpr {
span: assign.span,
op,
left: Box::new(Expr::Ident(lhs.clone())),
right: assign.right.take(),
});
}
}
}
}
}
}