From b6ff4d6f717dfb4bd41c62c7085e15ace868f296 Mon Sep 17 00:00:00 2001 From: Niklas Mischkulnig <4586894+mischnic@users.noreply.github.com> Date: Mon, 3 May 2021 11:12:15 +0200 Subject: [PATCH] fix(es/transforms/optimization): Preserve `x instanceof Object` (#1630) --- .../transforms/optimization/src/simplify/expr/mod.rs | 12 +++++++++++- .../optimization/src/simplify/expr/tests.rs | 2 ++ 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/ecmascript/transforms/optimization/src/simplify/expr/mod.rs b/ecmascript/transforms/optimization/src/simplify/expr/mod.rs index 4a19b25fb13..d7a332a7813 100644 --- a/ecmascript/transforms/optimization/src/simplify/expr/mod.rs +++ b/ecmascript/transforms/optimization/src/simplify/expr/mod.rs @@ -466,12 +466,22 @@ impl SimplifyExpr { } } + fn is_obj(e: &Expr) -> bool { + match *e { + Expr::Array { .. } + | Expr::Object { .. } + | Expr::Fn { .. } + | Expr::New { .. } => true, + _ => false, + } + } + // Non-object types are never instances. if is_non_obj(&left) { return make_bool_expr(span, false, iter::once(right)); } - if right.is_ident_ref_to(js_word!("Object")) { + if is_obj(&left) && right.is_ident_ref_to(js_word!("Object")) { return make_bool_expr(span, true, iter::once(left)); } diff --git a/ecmascript/transforms/optimization/src/simplify/expr/tests.rs b/ecmascript/transforms/optimization/src/simplify/expr/tests.rs index d6afd272467..a60b5d48aa9 100644 --- a/ecmascript/transforms/optimization/src/simplify/expr/tests.rs +++ b/ecmascript/transforms/optimization/src/simplify/expr/tests.rs @@ -1140,6 +1140,7 @@ fn test_fold_instance_of() { // These cases is foldable, but no handled currently. fold("new Foo() instanceof Object", "new Foo(), true;"); + // These would require type information to fold. fold_same("[] instanceof Foo"); fold_same("({}) instanceof Foo"); @@ -1148,6 +1149,7 @@ fn test_fold_instance_of() { // An unknown value should never be folded. fold_same("x instanceof Foo"); + fold_same("x instanceof Object"); } #[test]