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

feat(es/minifier): mark some builtin functions pure. #6842

Draft
wants to merge 16 commits into
base: main
Choose a base branch
from
65 changes: 56 additions & 9 deletions crates/swc_ecma_minifier/src/metadata/mod.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
use std::hash::Hash;

use rustc_hash::FxHashSet;
use swc_common::{
comments::{Comment, CommentKind, Comments},
EqIgnoreSpan, Span, SyntaxContext,
Expand All @@ -11,6 +14,39 @@ use swc_ecma_visit::{

use crate::option::CompressOptions;

mod pure_exprs;

#[derive(Debug, Eq)]
struct HashEqIgnoreSpanExprRef<'a>(&'a Expr);

impl<'a> PartialEq for HashEqIgnoreSpanExprRef<'a> {
fn eq(&self, other: &Self) -> bool {
Ident::within_ignored_ctxt(|| self.0.eq_ignore_span(other.0))
}
}

impl<'a> Hash for HashEqIgnoreSpanExprRef<'a> {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
// In pratice, most of cases/input we are dealing with are Expr::Member or
// Expr::Ident.
match self.0 {
Expr::Ident(i) => {
i.sym.hash(state);
}
Expr::Member(i) => {
Self(&i.obj).hash(state);
if let MemberProp::Ident(prop) = &i.prop {
prop.sym.hash(state);
}
}
_ => {
// Other expression kind would fallback to the same empty hash.
// So, their will spend linear time to do comparisons.
}
}
}
}

#[cfg(test)]
mod tests;

Expand All @@ -21,10 +57,25 @@ pub(crate) fn info_marker<'a>(
marks: Marks,
// unresolved_mark: Mark,
) -> impl 'a + VisitMut {
let pristine_globals = options.map_or(false, |opts| opts.pristine_globals);

let pure_funcs = options.map(|options| {
options
.pure_funcs
.iter()
.chain(if pristine_globals {
[].iter()
} else {
pure_exprs::PURE_FUNC_LIST.iter()
})
.map(|f| HashEqIgnoreSpanExprRef(f))
.collect()
});
InfoMarker {
options,
comments,
marks,
pure_funcs,
// unresolved_mark,
state: Default::default(),
}
Expand All @@ -37,8 +88,9 @@ struct State {
}

struct InfoMarker<'a> {
#[allow(dead_code)]
options: Option<&'a CompressOptions>,

pure_funcs: Option<FxHashSet<HashEqIgnoreSpanExprRef<'a>>>,
comments: Option<&'a dyn Comments>,
marks: Marks,
// unresolved_mark: Mark,
Expand Down Expand Up @@ -124,17 +176,12 @@ impl VisitMut for InfoMarker<'_> {

if self.has_pure(n.span) {
n.span = n.span.apply_mark(self.marks.pure);
} else if let Some(options) = self.options {
} else if let Some(pure_fns) = &self.pure_funcs {
if let Callee::Expr(e) = &n.callee {
// Check for pure_funcs

if options
.pure_funcs
.iter()
.any(|pure_func| Ident::within_ignored_ctxt(|| e.eq_ignore_span(pure_func)))
{
if pure_fns.contains(&HashEqIgnoreSpanExprRef(e)) {
n.span = n.span.apply_mark(self.marks.pure);
}
};
}
}
}
Expand Down
Loading