Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(es/minifier): Don't inline functions if keep_fnames is enabled #8093

Merged
merged 31 commits into from
Oct 12, 2023
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
keep_fn_name
  • Loading branch information
kdy1 committed Oct 11, 2023
commit 46d201018cf274026c7c5ffe6f09cd143d9492e7
72 changes: 72 additions & 0 deletions crates/swc_ecma_transforms_base/src/rename/ops.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,40 @@ impl Operator<'_> {

Some(class_expr)
}

fn keep_fn_name(&mut self, ident: &mut Ident, f: &mut Function) -> Option<FnExpr> {
if !self.config.keep_fn_names {
return None;
}

let mut orig_name = ident.clone();
orig_name.span.ctxt = SyntaxContext::empty();

{
// Remove span hygiene of the class.
let mut rename = AHashMap::default();

rename.insert(ident.to_id(), orig_name.sym.clone());

let mut operator = Operator {
rename: &rename,
config: self.config.clone(),
extra: Default::default(),
};

f.visit_mut_with(&mut operator);
}

let _ = self.rename_ident(ident);
f.visit_mut_with(self);

let fn_expr = FnExpr {
ident: Some(orig_name),
function: Box::new(f.take()),
};

Some(fn_expr)
}
}

impl Parallel for Operator<'_> {
Expand Down Expand Up @@ -107,6 +141,19 @@ impl<'a> VisitMut for Operator<'a> {
n.class.visit_mut_with(self);
}

fn visit_mut_fn_expr(&mut self, n: &mut FnExpr) {
if let Some(ident) = &mut n.ident {
if let Some(expr) = self.keep_fn_name(ident, &mut n.function) {
*n = expr;
return;
}
}

n.ident.visit_mut_with(self);

n.function.visit_mut_with(self);
}

fn visit_mut_decl(&mut self, decl: &mut Decl) {
match decl {
Decl::Class(cls) if self.config.keep_class_names => {
Expand All @@ -132,6 +179,31 @@ impl<'a> VisitMut for Operator<'a> {

return;
}

Decl::Fn(f) if self.config.keep_fn_names => {
let span = f.function.span;

let expr = self.keep_fn_name(&mut f.ident, &mut f.function);
if let Some(expr) = expr {
let var = VarDeclarator {
span,
name: f.ident.clone().into(),
init: Some(Box::new(Expr::Fn(expr))),
definite: false,
};
*decl = VarDecl {
span,
kind: VarDeclKind::Let,
declare: false,
decls: vec![var],
}
.into();
return;
}

return;
}

_ => {}
}

Expand Down