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): Improve simplification of ?. #6681

Merged
merged 8 commits into from
Dec 20, 2022
Merged
Show file tree
Hide file tree
Changes from 7 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
24 changes: 24 additions & 0 deletions crates/swc_ecma_minifier/src/compress/pure/misc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -364,6 +364,30 @@ impl Pure<'_> {
}
}

pub(super) fn optimize_opt_chain(&mut self, e: &mut Expr) {
let opt = match e {
Expr::OptChain(c) => c,
_ => return,
};

if let OptChainBase::Member(base) = &mut opt.base {
if match &*base.obj {
Expr::Lit(Lit::Null(..)) => false,
Expr::Lit(..) | Expr::Object(..) | Expr::Array(..) => true,
_ => false,
} {
self.changed = true;
report_change!("Optimized optional chaining expression where object is not null");

*e = Expr::Member(MemberExpr {
span: opt.span,
obj: base.obj.take(),
prop: base.prop.take(),
});
}
}
}

/// new Array(...) -> Array(...)
pub(super) fn optimize_builtin_object(&mut self, e: &mut Expr) {
if !self.options.pristine_globals {
Expand Down
6 changes: 6 additions & 0 deletions crates/swc_ecma_minifier/src/compress/pure/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -551,6 +551,12 @@ impl VisitMut for Pure<'_> {
if e.is_seq() {
debug_assert_valid(e);
}

self.optimize_opt_chain(e);

if e.is_seq() {
debug_assert_valid(e);
}
}

fn visit_mut_expr_stmt(&mut self, s: &mut ExprStmt) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
const obj = { key: 42 };
const val = obj?.[null || 'key']
console.log('val', val)
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
console.log('val', 42);
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
const obj = { key: 42 };
const val = obj?.key.toString()
console.log('val', val)
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
console.log('val', "42");
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
const obj = { key: 42 };
const val = obj?.key?.toString()
console.log('val', val)
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
console.log('val', "42");
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
const obj = { key: 42 };
const val = obj.key?.toString()
console.log('val', val)
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
console.log('val', "42");