feat(es/minifier): Improve simplification of ?. (#6681)

**Related issue:**

 - Closes https://github.com/swc-project/swc/issues/6492.
This commit is contained in:
Donny/강동윤 2022-12-20 18:34:50 +09:00 committed by GitHub
parent 6109a4c188
commit 707b1e3cd2
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
10 changed files with 46 additions and 0 deletions

View File

@ -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 {

View File

@ -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) {

View File

@ -0,0 +1,3 @@
const obj = { key: 42 };
const val = obj?.[null || 'key']
console.log('val', val)

View File

@ -0,0 +1 @@
console.log('val', 42);

View File

@ -0,0 +1,3 @@
const obj = { key: 42 };
const val = obj?.key.toString()
console.log('val', val)

View File

@ -0,0 +1 @@
console.log('val', "42");

View File

@ -0,0 +1,3 @@
const obj = { key: 42 };
const val = obj?.key?.toString()
console.log('val', val)

View File

@ -0,0 +1 @@
console.log('val', "42");

View File

@ -0,0 +1,3 @@
const obj = { key: 42 };
const val = obj.key?.toString()
console.log('val', val)

View File

@ -0,0 +1 @@
console.log('val', "42");