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
35 changes: 25 additions & 10 deletions crates/swc_ecma_minifier/src/metadata/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ use swc_ecma_visit::{

use crate::option::CompressOptions;

mod pure_exprs;

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

Expand Down Expand Up @@ -55,13 +57,24 @@ pub(crate) fn info_marker<'a>(
marks: Marks,
// unresolved_mark: Mark,
) -> impl 'a + VisitMut {
let pure_funcs = options.map(|options| {
options
.pure_funcs
.iter()
.map(|f| HashEqIgnoreSpanExprRef(f))
.collect()
});
let pristine_globals = options.map_or(false, |opts| opts.pristine_globals);
let mut pure_funcs = options
.map(|opts| {
opts.pure_funcs
.iter()
.map(|expr| HashEqIgnoreSpanExprRef(expr))
.collect::<FxHashSet<_>>()
})
.unwrap_or_default();

if pristine_globals {
pure_funcs.extend(
pure_exprs::PURE_FUNC_LIST
.iter()
.map(|expr| HashEqIgnoreSpanExprRef(expr)),
);
}

InfoMarker {
options,
comments,
Expand All @@ -81,7 +94,7 @@ struct State {
struct InfoMarker<'a> {
#[allow(dead_code)]
options: Option<&'a CompressOptions>,
pure_funcs: Option<FxHashSet<HashEqIgnoreSpanExprRef<'a>>>,
pure_funcs: FxHashSet<HashEqIgnoreSpanExprRef<'a>>,
comments: Option<&'a dyn Comments>,
marks: Marks,
// unresolved_mark: Mark,
Expand Down Expand Up @@ -167,10 +180,12 @@ impl VisitMut for InfoMarker<'_> {

if self.has_pure(n.span) {
n.span = n.span.apply_mark(self.marks.pure);
} else if let Some(pure_fns) = &self.pure_funcs {
}

if !self.pure_funcs.is_empty() {
if let Callee::Expr(e) = &n.callee {
// Check for pure_funcs
if pure_fns.contains(&HashEqIgnoreSpanExprRef(e)) {
if self.pure_funcs.contains(&HashEqIgnoreSpanExprRef(e)) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we use two hashset instead?
I think it will avoid allocations

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

One hashset with type Lazy<FxHashSet<HashEqIgnoreSpanExprRef<'static>>>

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Get it.

n.span = n.span.apply_mark(self.marks.pure);
};
}
Expand Down
Loading