feat(es/minifier): Implement more rules (#4763)

This commit is contained in:
Donny/강동윤 2022-05-24 07:09:33 +09:00 committed by GitHub
parent f7dc3fff1f
commit 20b724d3cd
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 57 additions and 20 deletions

View File

@ -5,7 +5,7 @@ use swc_atoms::js_word;
use swc_common::{pass::Either, util::take::Take, Mark, Spanned, SyntaxContext, DUMMY_SP};
use swc_ecma_ast::*;
use swc_ecma_utils::{
contains_arguments, contains_this_expr, find_pat_ids, undefined, ExprFactory,
contains_arguments, contains_this_expr, find_pat_ids, undefined, ExprFactory, IdentUsageFinder,
};
use swc_ecma_visit::VisitMutWith;
@ -489,7 +489,7 @@ where
}
if let Some(i) = &f.ident {
if idents_used_by(&f.function.body).contains(&i.to_id()) {
if IdentUsageFinder::find(&i.to_id(), &f.function.body) {
log_abort!("iife: [x] Recursive?");
return;
}
@ -648,7 +648,22 @@ where
// TODO: Check if parameter is used and inline if call is not related to parameters.
Expr::Call(e) => {
if let Some(..) = e.callee.as_expr().and_then(|e| e.as_ident()) {
return true;
}
let used = idents_used_by(&e.callee);
if used.iter().all(|id| {
self.data
.vars
.get(id)
.map(|usage| usage.ref_count == 1 && usage.used_as_callee)
.unwrap_or(false)
}) {
return true;
}
param_ids.iter().all(|param| !used.contains(&param.to_id()))
}

View File

@ -70,26 +70,46 @@ impl Pure<'_> {
..
}) = &mut *es.expr
{
if let Expr::Fn(FnExpr {
function:
Function {
params,
body: Some(body),
is_async: false,
..
},
..
}) = &mut **callee
{
if body.stmts.iter().any(|s| !is_fine_to_move(s)) {
return;
match &mut **callee {
Expr::Fn(FnExpr {
function:
Function {
params,
body: Some(body),
is_async: false,
is_generator: false,
..
},
..
}) => {
if args.is_empty()
&& params.is_empty()
&& body.stmts.iter().all(is_fine_to_move)
{
self.changed = true;
report_change!("Flattening iife");
*s = Stmt::Block(body.take());
}
}
if args.is_empty() && params.is_empty() {
self.changed = true;
report_change!("Flattening iife");
*s = Stmt::Block(body.take());
Expr::Arrow(ArrowExpr {
params,
is_async: false,
is_generator: false,
body: BlockStmtOrExpr::BlockStmt(body),
..
}) => {
if args.is_empty()
&& params.is_empty()
&& body.stmts.iter().all(is_fine_to_move)
{
self.changed = true;
report_change!("Flattening iife");
*s = Stmt::Block(body.take());
}
}
_ => {}
}
}
}

View File

@ -598,6 +598,8 @@ impl VisitMut for Pure<'_> {
self.merge_seq_call(e);
let can_drop_zero = matches!(&**e.exprs.last().unwrap(), Expr::Arrow(..));
let len = e.exprs.len();
for (idx, e) in e.exprs.iter_mut().enumerate() {
let is_last = idx == len - 1;
@ -606,7 +608,7 @@ impl VisitMut for Pure<'_> {
self.ignore_return_value(
&mut **e,
DropOpts {
drop_zero: false,
drop_zero: can_drop_zero,
drop_global_refs_if_unused: false,
drop_str_lit: true,
},