file_path stringlengths 3 280 | file_language stringclasses 66 values | content stringlengths 1 1.04M | repo_name stringlengths 5 92 | repo_stars int64 0 154k | repo_description stringlengths 0 402 | repo_primary_language stringclasses 108 values | developer_username stringlengths 1 25 | developer_name stringlengths 0 30 | developer_company stringlengths 0 82 |
|---|---|---|---|---|---|---|---|---|---|
crates/swc_ecma_transforms_optimization/src/json_parse.rs | Rust | use serde_json::Value;
use swc_common::{util::take::Take, Spanned, DUMMY_SP};
use swc_ecma_ast::*;
use swc_ecma_transforms_base::perf::Parallel;
use swc_ecma_utils::{calc_literal_cost, member_expr, ExprFactory};
use swc_ecma_visit::{noop_visit_mut_type, visit_mut_pass, VisitMut, VisitMutWith};
/// Transform to optimize performance of literals.
///
///
/// This transform converts pure object literals like
///
/// ```js
/// {a: 1, b: 2}
/// ```
///
/// to
///
/// ```js
/// JSON.parse('{"a":1, "b"}')
/// ```
///
/// # Conditions
/// If any of the conditions below is matched, pure object literal is converter
/// to `JSON.parse`
///
/// - Object literal is deeply nested (threshold: )
///
/// See https://github.com/swc-project/swc/issues/409
pub fn json_parse(min_cost: usize) -> impl Pass {
visit_mut_pass(JsonParse { min_cost })
}
struct JsonParse {
pub min_cost: usize,
}
impl Parallel for JsonParse {
fn create(&self) -> Self {
JsonParse {
min_cost: self.min_cost,
}
}
fn merge(&mut self, _: Self) {}
}
impl Default for JsonParse {
fn default() -> Self {
JsonParse { min_cost: 1024 }
}
}
impl VisitMut for JsonParse {
noop_visit_mut_type!(fail);
/// Handles parent expressions before child expressions.
fn visit_mut_expr(&mut self, expr: &mut Expr) {
if self.min_cost == usize::MAX {
return;
}
let e = match expr {
Expr::Array(..) | Expr::Object(..) => {
let (is_lit, cost) = calc_literal_cost(&*expr, false);
if is_lit && cost >= self.min_cost {
let value =
serde_json::to_string(&jsonify(expr.take())).unwrap_or_else(|err| {
unreachable!("failed to serialize serde_json::Value as json: {}", err)
});
*expr = CallExpr {
span: expr.span(),
callee: member_expr!(Default::default(), DUMMY_SP, JSON.parse).as_callee(),
args: vec![Lit::Str(Str {
span: DUMMY_SP,
raw: None,
value: value.into(),
})
.as_arg()],
..Default::default()
}
.into();
return;
}
expr
}
_ => expr,
};
e.visit_mut_children_with(self)
}
}
fn jsonify(e: Expr) -> Value {
match e {
Expr::Object(obj) => Value::Object(
obj.props
.into_iter()
.map(|v| match v {
PropOrSpread::Prop(p) if p.is_key_value() => p.key_value().unwrap(),
_ => unreachable!(),
})
.map(|p: KeyValueProp| {
let value = jsonify(*p.value);
let key = match p.key {
PropName::Str(s) => s.value.to_string(),
PropName::Ident(id) => id.sym.to_string(),
PropName::Num(n) => format!("{}", n.value),
_ => unreachable!(),
};
(key, value)
})
.collect(),
),
Expr::Array(arr) => Value::Array(
arr.elems
.into_iter()
.map(|v| jsonify(*v.unwrap().expr))
.collect(),
),
Expr::Lit(Lit::Str(Str { value, .. })) => Value::String(value.to_string()),
Expr::Lit(Lit::Num(Number { value, .. })) => Value::Number((value as i64).into()),
Expr::Lit(Lit::Null(..)) => Value::Null,
Expr::Lit(Lit::Bool(v)) => Value::Bool(v.value),
Expr::Tpl(Tpl { quasis, .. }) => Value::String(match quasis.first() {
Some(TplElement {
cooked: Some(value),
..
}) => value.to_string(),
_ => String::new(),
}),
_ => unreachable!("jsonify: Expr {:?} cannot be converted to json", e),
}
}
#[cfg(test)]
mod tests {
use swc_ecma_transforms_testing::test;
use super::*;
test!(
::swc_ecma_parser::Syntax::default(),
|_| json_parse(0),
simple_object,
"let a = {b: 'foo'}"
);
test!(
::swc_ecma_parser::Syntax::default(),
|_| json_parse(0),
simple_arr,
"let a = ['foo']"
);
test!(
::swc_ecma_parser::Syntax::default(),
|_| json_parse(0),
empty_object,
"const a = {};"
);
test!(
::swc_ecma_parser::Syntax::default(),
|_| json_parse(15),
min_cost_15,
"const a = { b: 1, c: 2 };"
);
test!(
::swc_ecma_parser::Syntax::default(),
|_| json_parse(0),
min_cost_0,
"const a = { b: 1, c: 2 };"
);
test!(
::swc_ecma_parser::Syntax::default(),
|_| json_parse(0),
spread,
"const a = { ...a, b: 1 };"
);
test!(
::swc_ecma_parser::Syntax::default(),
|_| json_parse(0),
object_method,
"const a = {
method(arg) {
return arg;
},
b: 1
};"
);
test!(
::swc_ecma_parser::Syntax::default(),
|_| json_parse(0),
computed_property,
r#"const a = { b : "b_val", ["c"]: "c_val" };"#
);
test!(
::swc_ecma_parser::Syntax::default(),
|_| json_parse(0),
invalid_numeric_key,
r#"const a ={ 77777777777777777.1: "foo" };"#
);
test!(
::swc_ecma_parser::Syntax::default(),
|_| json_parse(0),
string,
r#"const a = { b: "b_val" };"#
);
test!(
::swc_ecma_parser::Syntax::default(),
|_| json_parse(0),
string_single_quote_1,
r#"const a = { b: "'abc'" };"#,
ok_if_code_eq
);
test!(
::swc_ecma_parser::Syntax::default(),
|_| json_parse(0),
string_single_quote_2,
r#"const a = { b: "ab\'c" };"#,
ok_if_code_eq
);
test!(
::swc_ecma_parser::Syntax::default(),
|_| json_parse(0),
number,
"const a = { b: 1 };"
);
test!(
::swc_ecma_parser::Syntax::default(),
|_| json_parse(0),
null,
"const a = { b: null };"
);
test!(
::swc_ecma_parser::Syntax::default(),
|_| json_parse(0),
boolean,
"const a = { b: false };"
);
test!(
::swc_ecma_parser::Syntax::default(),
|_| json_parse(0),
array,
"const a = { b: [1, 'b_val', null] };"
);
test!(
::swc_ecma_parser::Syntax::default(),
|_| json_parse(0),
nested_array,
"const a = { b: [1, ['b_val', { a: 1 }], null] };"
);
test!(
::swc_ecma_parser::Syntax::default(),
|_| json_parse(0),
object,
"const a = { b: { c: 1 } };"
);
test!(
::swc_ecma_parser::Syntax::default(),
|_| json_parse(0),
object_numeric_keys,
r#"const a = { 1: "123", 23: 45, b: "b_val" };"#
);
test!(
::swc_ecma_parser::Syntax::default(),
|_| json_parse(0),
tpl,
r"const a = [`\x22\x21\x224`];"
);
test!(
::swc_ecma_parser::Syntax::default(),
|_| json_parse(0),
tpl2,
r#"const a = [`1${b}2`];"#
);
test!(
::swc_ecma_parser::Syntax::default(),
|_| json_parse(0),
tpl3,
r#"const a = [`1${0}2`];"#
);
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_optimization/src/lib.rs | Rust | #![deny(clippy::all)]
#![deny(unused)]
#![allow(clippy::match_like_matches_macro)]
pub use self::{
const_modules::const_modules,
debug::{debug_assert_valid, AssertValid},
inline_globals::{inline_globals, inline_globals2, GlobalExprMap},
json_parse::json_parse,
simplify::simplifier,
};
mod const_modules;
mod debug;
mod inline_globals;
mod json_parse;
pub mod simplify;
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_optimization/src/simplify/branch/mod.rs | Rust | use std::{borrow::Cow, iter::once, mem::take};
use swc_common::{
pass::{CompilerPass, Repeated},
util::{move_map::MoveMap, take::Take},
Mark, Spanned, SyntaxContext, DUMMY_SP,
};
use swc_ecma_ast::*;
use swc_ecma_transforms_base::perf::{cpu_count, Parallel, ParallelExt};
use swc_ecma_utils::{
extract_var_ids, is_literal, prepend_stmt, ExprCtx, ExprExt, ExprFactory, Hoister, IsEmpty,
StmtExt, StmtLike, Value::Known,
};
use swc_ecma_visit::{
noop_visit_mut_type, noop_visit_type, visit_mut_pass, Visit, VisitMut, VisitMutWith, VisitWith,
};
use tracing::{debug, trace};
#[cfg(test)]
mod tests;
/// Not intended for general use. Use [simplifier] instead.
///
/// Ported from `PeepholeRemoveDeadCode` of google closure compiler.
pub fn dead_branch_remover(
unresolved_mark: Mark,
) -> impl Repeated + Pass + CompilerPass + VisitMut + 'static {
visit_mut_pass(Remover {
changed: false,
normal_block: Default::default(),
expr_ctx: ExprCtx {
unresolved_ctxt: SyntaxContext::empty().apply_mark(unresolved_mark),
is_unresolved_ref_safe: false,
in_strict: false,
remaining_depth: 3,
},
})
}
impl CompilerPass for Remover {
fn name(&self) -> Cow<'static, str> {
Cow::Borrowed("dead_branch_remover")
}
}
impl Repeated for Remover {
fn changed(&self) -> bool {
self.changed
}
fn reset(&mut self) {
self.changed = false;
}
}
#[derive(Debug)]
struct Remover {
changed: bool,
normal_block: bool,
expr_ctx: ExprCtx,
}
impl Parallel for Remover {
fn create(&self) -> Self {
Self { ..*self }
}
fn merge(&mut self, _: Self) {}
}
impl VisitMut for Remover {
noop_visit_mut_type!();
fn visit_mut_class_members(&mut self, members: &mut Vec<ClassMember>) {
self.maybe_par(cpu_count(), members, |v, member| {
member.visit_mut_with(v);
});
}
fn visit_mut_expr(&mut self, e: &mut Expr) {
e.visit_mut_children_with(self);
match e {
Expr::Seq(s) => {
if s.exprs.is_empty() {
*e = Expr::dummy();
} else if s.exprs.len() == 1 {
*e = *s.exprs.pop().unwrap();
}
}
Expr::Assign(AssignExpr {
op: op!("="),
left: AssignTarget::Simple(l),
right: r,
..
}) if match &*l {
SimpleAssignTarget::Ident(l) => match &**r {
Expr::Ident(r) => l.sym == r.sym && l.ctxt == r.ctxt,
_ => false,
},
_ => false,
} =>
{
if cfg!(feature = "debug") {
debug!("Dropping assignment to the same variable");
}
*e = r.take().ident().unwrap().into();
}
Expr::Assign(AssignExpr {
op: op!("="),
left: AssignTarget::Pat(left),
right,
..
}) if match &*left {
AssignTargetPat::Array(arr) => {
arr.elems.is_empty() || arr.elems.iter().all(|v| v.is_none())
}
_ => false,
} =>
{
if cfg!(feature = "debug") {
debug!("Dropping assignment to an empty array pattern");
}
*e = *right.take();
}
Expr::Assign(AssignExpr {
op: op!("="),
left: AssignTarget::Pat(left),
right,
..
}) if match &*left {
AssignTargetPat::Object(obj) => obj.props.is_empty(),
_ => false,
} =>
{
if cfg!(feature = "debug") {
debug!("Dropping assignment to an empty object pattern");
}
*e = *right.take();
}
Expr::Cond(cond)
if !cond.test.may_have_side_effects(self.expr_ctx)
&& (cond.cons.is_undefined(self.expr_ctx)
|| matches!(*cond.cons, Expr::Unary(UnaryExpr {
op: op!("void"),
ref arg,
..
}) if !arg.may_have_side_effects(self.expr_ctx)))
&& (cond.alt.is_undefined(self.expr_ctx)
|| matches!(*cond.alt, Expr::Unary(UnaryExpr {
op: op!("void"),
ref arg,
..
}) if !arg.may_have_side_effects(self.expr_ctx))) =>
{
if cfg!(feature = "debug") {
debug!("Dropping side-effect-free expressions");
}
*e = *cond.cons.take();
}
Expr::Bin(be) => match (be.left.is_invalid(), be.right.is_invalid()) {
(true, true) => {
*e = Expr::dummy();
}
(true, false) => {
*e = *be.right.take();
}
(false, true) => {
*e = *be.left.take();
}
_ => {}
},
_ => {}
}
}
fn visit_mut_expr_or_spreads(&mut self, n: &mut Vec<ExprOrSpread>) {
self.maybe_par(cpu_count() * 8, n, |v, n| {
n.visit_mut_with(v);
})
}
fn visit_mut_exprs(&mut self, n: &mut Vec<Box<Expr>>) {
self.maybe_par(cpu_count() * 8, n, |v, n| {
n.visit_mut_with(v);
})
}
fn visit_mut_for_stmt(&mut self, s: &mut ForStmt) {
s.visit_mut_children_with(self);
s.init = s.init.take().and_then(|e| match e {
VarDeclOrExpr::Expr(e) => {
ignore_result(e, true, self.expr_ctx).map(VarDeclOrExpr::from)
}
_ => Some(e),
});
s.update = s
.update
.take()
.and_then(|e| ignore_result(e, true, self.expr_ctx));
s.test = s.test.take().and_then(|e| {
let span = e.span();
if let Known(value) = e.as_pure_bool(self.expr_ctx) {
return if value {
None
} else {
Some(Lit::Bool(Bool { span, value: false }).into())
};
}
Some(e)
});
}
fn visit_mut_module_items(&mut self, n: &mut Vec<ModuleItem>) {
if cfg!(feature = "debug") {
debug!("Removing dead branches");
}
self.fold_stmt_like(n);
}
fn visit_mut_object_pat(&mut self, p: &mut ObjectPat) {
p.visit_mut_children_with(self);
// Don't remove if there exists a rest pattern
if p.props.iter().any(|p| matches!(p, ObjectPatProp::Rest(..))) {
return;
}
fn is_computed(k: &PropName) -> bool {
matches!(k, PropName::Computed(..))
}
p.props.retain(|p| match p {
ObjectPatProp::KeyValue(KeyValuePatProp { key, value, .. })
if match &**value {
Pat::Object(p) => !is_computed(key) && p.props.is_empty(),
_ => false,
} =>
{
if cfg!(feature = "debug") {
debug!(
"Dropping key-value pattern property because it's an empty object pattern"
);
}
false
}
ObjectPatProp::KeyValue(KeyValuePatProp { key, value, .. })
if match &**value {
Pat::Array(p) => !is_computed(key) && p.elems.is_empty(),
_ => false,
} =>
{
if cfg!(feature = "debug") {
debug!(
"Dropping key-value pattern property because it's an empty array pattern"
);
}
false
}
_ => true,
});
}
fn visit_mut_object_pat_prop(&mut self, p: &mut ObjectPatProp) {
p.visit_mut_children_with(self);
match p {
ObjectPatProp::Assign(AssignPatProp {
span,
key,
value: Some(expr),
}) if expr.is_undefined(self.expr_ctx)
|| match **expr {
Expr::Unary(UnaryExpr {
op: op!("void"),
ref arg,
..
}) => is_literal(&**arg),
_ => false,
} =>
{
*p = ObjectPatProp::Assign(AssignPatProp {
span: *span,
key: key.take(),
value: None,
});
}
_ => {}
}
}
fn visit_mut_opt_var_decl_or_expr(&mut self, n: &mut Option<VarDeclOrExpr>) {
n.visit_mut_children_with(self);
if let Some(VarDeclOrExpr::Expr(e)) = n {
if e.is_invalid() {
*n = None;
}
}
}
fn visit_mut_opt_vec_expr_or_spreads(&mut self, n: &mut Vec<Option<ExprOrSpread>>) {
self.maybe_par(cpu_count() * 8, n, |v, n| {
n.visit_mut_with(v);
})
}
fn visit_mut_pat(&mut self, p: &mut Pat) {
p.visit_mut_children_with(self);
match p {
Pat::Assign(assign)
if assign.right.is_undefined(self.expr_ctx)
|| match *assign.right {
Expr::Unary(UnaryExpr {
op: op!("void"),
ref arg,
..
}) => is_literal(&**arg),
_ => false,
} =>
{
*p = *assign.left.take();
}
_ => {}
}
}
fn visit_mut_prop_or_spreads(&mut self, n: &mut Vec<PropOrSpread>) {
self.maybe_par(cpu_count() * 8, n, |v, n| {
n.visit_mut_with(v);
})
}
fn visit_mut_seq_expr(&mut self, e: &mut SeqExpr) {
e.visit_mut_children_with(self);
if e.exprs.is_empty() {
return;
}
let last = e.exprs.pop().unwrap();
let should_preserved_this = last.directness_maters();
let mut exprs = if should_preserved_this {
e.exprs
.take()
.into_iter()
.enumerate()
.filter_map(|(idx, e)| {
if idx == 0 {
return Some(e);
}
ignore_result(e, true, self.expr_ctx)
})
.collect()
} else {
e.exprs
.take()
.move_flat_map(|e| ignore_result(e, false, self.expr_ctx))
};
exprs.push(last);
e.exprs = exprs;
}
fn visit_mut_stmt(&mut self, stmt: &mut Stmt) {
stmt.visit_mut_children_with(self);
stmt.map_with_mut(|stmt| {
match stmt {
Stmt::If(IfStmt {
span,
test,
cons,
alt,
}) => {
if let Stmt::If(IfStmt { alt: Some(..), .. }) = *cons {
return IfStmt {
test,
cons: Box::new(
BlockStmt {
stmts: vec![*cons],
..Default::default()
}
.into(),
),
alt,
span,
}
.into();
}
let mut stmts = Vec::new();
if let (p, Known(v)) = test.cast_to_bool(self.expr_ctx) {
if cfg!(feature = "debug") {
trace!("The condition for if statement is always {}", v);
}
// Preserve effect of the test
if !p.is_pure() {
if let Some(expr) = ignore_result(test, true, self.expr_ctx) {
stmts.push(ExprStmt { span, expr }.into())
}
}
if v {
// Preserve variables
if let Some(var) = alt.and_then(|alt| alt.extract_var_ids_as_var()) {
stmts.push(var.into())
}
stmts.push(*cons);
} else {
if let Some(var) = cons.extract_var_ids_as_var() {
stmts.push(var.into())
}
if let Some(alt) = alt {
stmts.push(*alt)
}
}
if stmts.is_empty() {
return EmptyStmt { span }.into();
}
if cfg!(feature = "debug") {
debug!("Optimized an if statement with known condition");
}
self.changed = true;
let mut block: Stmt = BlockStmt {
span,
stmts,
..Default::default()
}
.into();
block.visit_mut_with(self);
return block;
}
let alt = match &alt {
Some(stmt) if stmt.is_empty() => None,
_ => alt,
};
if alt.is_none() {
if let Stmt::Empty(..) = *cons {
self.changed = true;
return if let Some(expr) = ignore_result(test, true, self.expr_ctx) {
ExprStmt { span, expr }.into()
} else {
EmptyStmt { span }.into()
};
}
}
IfStmt {
span,
test,
cons,
alt,
}
.into()
}
Stmt::Decl(Decl::Var(v)) if v.decls.is_empty() => {
if cfg!(feature = "debug") {
debug!("Dropping an empty var declaration");
}
EmptyStmt { span: v.span }.into()
}
Stmt::Labeled(LabeledStmt {
label, span, body, ..
}) if body.is_empty() => {
debug!("Dropping an empty label statement: `{}`", label);
EmptyStmt { span }.into()
}
Stmt::Labeled(LabeledStmt {
span,
body,
ref label,
..
}) if match &*body {
Stmt::Break(BreakStmt { label: Some(b), .. }) => label.sym == b.sym,
_ => false,
} =>
{
debug!("Dropping a label statement with instant break: `{}`", label);
EmptyStmt { span }.into()
}
// `1;` -> `;`
Stmt::Expr(ExprStmt { span, expr, .. }) => {
// Directives
if let Expr::Lit(Lit::Str(..)) = &*expr {
return ExprStmt { span, expr }.into();
}
match ignore_result(expr, false, self.expr_ctx) {
Some(e) => ExprStmt { span, expr: e }.into(),
None => EmptyStmt { span: DUMMY_SP }.into(),
}
}
Stmt::Block(BlockStmt { span, stmts, ctxt }) => {
if stmts.is_empty() {
if cfg!(feature = "debug") {
debug!("Drooping an empty block statement");
}
EmptyStmt { span }.into()
} else if stmts.len() == 1
&& !is_block_scoped_stuff(&stmts[0])
&& stmt_depth(&stmts[0]) <= 1
{
if cfg!(feature = "debug") {
debug!("Optimizing a block statement with a single statement");
}
let mut v = stmts.into_iter().next().unwrap();
v.visit_mut_with(self);
v
} else {
BlockStmt { span, stmts, ctxt }.into()
}
}
Stmt::Try(s) => {
let TryStmt {
span,
block,
handler,
finalizer,
} = *s;
// Only leave the finally block if try block is empty
if block.is_empty() {
let var = handler.and_then(|h| Stmt::from(h.body).extract_var_ids_as_var());
return if let Some(mut finalizer) = finalizer {
if let Some(var) = var.map(Box::new).map(Decl::from).map(Stmt::from) {
prepend_stmt(&mut finalizer.stmts, var);
}
finalizer.into()
} else {
var.map(Box::new)
.map(Decl::from)
.map(Stmt::from)
.unwrap_or_else(|| EmptyStmt { span }.into())
};
}
// If catch block is not specified and finally block is empty, fold it to simple
// block.
if handler.is_none() && finalizer.is_empty() {
if cfg!(feature = "debug") {
debug!("Converting a try statement to a block statement");
}
return block.into();
}
TryStmt {
span,
block,
handler,
finalizer,
}
.into()
}
Stmt::Switch(mut s) => {
if s.cases
.iter()
.any(|case| matches!(case.test.as_deref(), Some(Expr::Update(..))))
{
return s.into();
}
if let Expr::Update(..) = &*s.discriminant {
if s.cases.len() != 1 {
return s.into();
}
}
let remove_break = |stmts: Vec<Stmt>| {
debug_assert!(
!has_conditional_stopper(&stmts) || has_unconditional_stopper(&stmts)
);
let mut done = false;
stmts.move_flat_map(|s| {
if done {
match s {
Stmt::Decl(Decl::Var(var))
if matches!(
&*var,
VarDecl {
kind: VarDeclKind::Var,
..
}
) =>
{
return Some(
VarDecl {
span: DUMMY_SP,
kind: VarDeclKind::Var,
decls: var.decls.move_map(|decl| VarDeclarator {
init: None,
..decl
}),
..Default::default()
}
.into(),
);
}
_ => (),
}
return None;
}
match s {
Stmt::Break(BreakStmt { label: None, .. }) => {
done = true;
None
}
Stmt::Return(..) | Stmt::Throw(..) => {
done = true;
Some(s)
}
_ => Some(s),
}
})
};
let is_matching_literal = match *s.discriminant {
Expr::Lit(Lit::Str(..))
| Expr::Lit(Lit::Null(..))
| Expr::Lit(Lit::Num(..)) => true,
ref e if e.is_nan() || e.is_global_ref_to(self.expr_ctx, "undefined") => {
true
}
_ => false,
};
// Remove empty switch
if s.cases.is_empty() {
if cfg!(feature = "debug") {
debug!("Removing an empty switch statement");
}
return match ignore_result(s.discriminant, true, self.expr_ctx) {
Some(expr) => ExprStmt { span: s.span, expr }.into(),
None => EmptyStmt { span: s.span }.into(),
};
}
// Handle a switch statement with only default.
if s.cases.len() == 1
&& s.cases[0].test.is_none()
&& !has_conditional_stopper(&s.cases[0].cons)
{
if cfg!(feature = "debug") {
debug!("Switch -> Block as default is the only case");
}
let mut stmts = remove_break(s.cases.remove(0).cons);
if let Some(expr) = ignore_result(s.discriminant, true, self.expr_ctx) {
prepend_stmt(&mut stmts, expr.into_stmt());
}
let mut block: Stmt = BlockStmt {
span: s.span,
stmts,
..Default::default()
}
.into();
block.visit_mut_with(self);
return block;
}
let mut non_constant_case_idx = None;
let selected = {
let mut i = 0;
s.cases.iter().position(|case| {
if non_constant_case_idx.is_some() {
i += 1;
return false;
}
if let Some(ref test) = case.test {
let v = match (&**test, &*s.discriminant) {
(
&Expr::Lit(Lit::Str(Str {
value: ref test, ..
})),
&Expr::Lit(Lit::Str(Str { value: ref d, .. })),
) => *test == *d,
(
&Expr::Lit(Lit::Num(Number { value: test, .. })),
&Expr::Lit(Lit::Num(Number { value: d, .. })),
) => (test - d).abs() < 1e-10,
(
&Expr::Lit(Lit::Bool(Bool { value: test, .. })),
&Expr::Lit(Lit::Bool(Bool { value: d, .. })),
) => test == d,
(&Expr::Lit(Lit::Null(..)), &Expr::Lit(Lit::Null(..))) => true,
_ => {
if !test.is_nan()
&& !test.is_global_ref_to(self.expr_ctx, "undefined")
{
non_constant_case_idx = Some(i);
}
false
}
};
i += 1;
return v;
}
i += 1;
false
})
};
let are_all_tests_known = s
.cases
.iter()
.map(|case| case.test.as_deref())
.all(|s| matches!(s, Some(Expr::Lit(..)) | None));
let mut var_ids = Vec::new();
if let Some(i) = selected {
if !has_conditional_stopper(&s.cases[i].cons) {
let mut exprs = Vec::new();
exprs.extend(ignore_result(s.discriminant, true, self.expr_ctx));
let mut stmts = s.cases[i].cons.take();
let mut cases = s.cases.drain((i + 1)..);
for case in cases.by_ref() {
let should_stop = has_unconditional_stopper(&case.cons);
stmts.extend(case.cons);
//
if should_stop {
break;
}
}
let mut stmts = remove_break(stmts);
let decls = cases
.flat_map(|case| {
exprs.extend(
case.test
.and_then(|e| ignore_result(e, true, self.expr_ctx)),
);
case.cons
})
.flat_map(|stmt| stmt.extract_var_ids())
.map(|i| VarDeclarator {
span: DUMMY_SP,
name: i.into(),
init: None,
definite: false,
})
.collect::<Vec<_>>();
if !decls.is_empty() {
prepend_stmt(
&mut stmts,
VarDecl {
span: DUMMY_SP,
kind: VarDeclKind::Var,
decls,
declare: false,
..Default::default()
}
.into(),
);
}
if !exprs.is_empty() {
prepend_stmt(
&mut stmts,
ExprStmt {
span: DUMMY_SP,
expr: if exprs.len() == 1 {
exprs.remove(0)
} else {
SeqExpr {
span: DUMMY_SP,
exprs,
}
.into()
},
}
.into(),
);
}
if cfg!(feature = "debug") {
debug!("Switch -> Block as we know discriminant");
}
let mut block: Stmt = BlockStmt {
span: s.span,
stmts,
..Default::default()
}
.into();
block.visit_mut_with(self);
return block;
}
} else if are_all_tests_known {
let mut vars = Vec::new();
if let Expr::Lit(..) = *s.discriminant {
let idx = s.cases.iter().position(|v| v.test.is_none());
if let Some(i) = idx {
for case in &s.cases[..i] {
for cons in &case.cons {
vars.extend(cons.extract_var_ids().into_iter().map(
|name| VarDeclarator {
span: DUMMY_SP,
name: name.into(),
init: None,
definite: Default::default(),
},
));
}
}
if !has_conditional_stopper(&s.cases[i].cons) {
let stmts = s.cases.remove(i).cons;
let mut stmts = remove_break(stmts);
if !vars.is_empty() {
prepend_stmt(
&mut stmts,
VarDecl {
span: DUMMY_SP,
kind: VarDeclKind::Var,
declare: Default::default(),
decls: take(&mut vars),
..Default::default()
}
.into(),
)
}
let mut block: Stmt = BlockStmt {
span: s.span,
stmts,
..Default::default()
}
.into();
block.visit_mut_with(self);
if cfg!(feature = "debug") {
debug!("Switch -> Block as the discriminant is a literal");
}
return block;
}
}
}
}
if is_matching_literal {
let mut idx = 0usize;
let mut breaked = false;
// Remove unmatchable cases.
s.cases = s.cases.move_flat_map(|case| {
if non_constant_case_idx.is_some()
&& idx >= non_constant_case_idx.unwrap()
{
idx += 1;
return Some(case);
}
// Detect unconditional break;
if selected.is_some() && selected <= Some(idx) {
// Done.
if breaked {
idx += 1;
if cfg!(feature = "debug") {
debug!("Dropping case because it is unreachable");
}
return None;
}
if !breaked {
// has unconditional break
breaked |= has_unconditional_stopper(&case.cons);
}
idx += 1;
return Some(case);
}
let res = match case.test {
Some(e)
if matches!(
&*e,
Expr::Lit(Lit::Num(..))
| Expr::Lit(Lit::Str(..))
| Expr::Lit(Lit::Null(..))
) =>
{
case.cons
.into_iter()
.for_each(|stmt| var_ids.extend(stmt.extract_var_ids()));
if cfg!(feature = "debug") {
debug!(
"Dropping case because it is unreachable (literal \
test)"
);
}
None
}
_ => Some(case),
};
idx += 1;
res
});
}
let is_default_last =
matches!(s.cases.last(), Some(SwitchCase { test: None, .. }));
{
// True if all cases except default is empty.
let is_all_case_empty = s
.cases
.iter()
.all(|case| case.test.is_none() || case.cons.is_empty());
let is_all_case_side_effect_free = s.cases.iter().all(|case| {
case.test
.as_ref()
.map(|e| e.is_ident() || !e.may_have_side_effects(self.expr_ctx))
.unwrap_or(true)
});
if is_default_last
&& is_all_case_empty
&& is_all_case_side_effect_free
&& !has_conditional_stopper(&s.cases.last().unwrap().cons)
{
let mut exprs = Vec::new();
exprs.extend(ignore_result(s.discriminant, true, self.expr_ctx));
exprs.extend(
s.cases
.iter_mut()
.filter_map(|case| case.test.take())
.filter_map(|e| ignore_result(e, true, self.expr_ctx)),
);
let stmts = s.cases.pop().unwrap().cons;
let mut stmts = remove_break(stmts);
if !exprs.is_empty() {
prepend_stmt(
&mut stmts,
ExprStmt {
span: DUMMY_SP,
expr: if exprs.len() == 1 {
exprs.remove(0)
} else {
SeqExpr {
span: DUMMY_SP,
exprs,
}
.into()
},
}
.into(),
);
}
if cfg!(feature = "debug") {
debug!("Stmt -> Block as all cases are empty");
}
let mut block: Stmt = BlockStmt {
span: s.span,
stmts,
..Default::default()
}
.into();
block.visit_mut_with(self);
return block;
}
}
if is_matching_literal
&& s.cases.iter().all(|case| match &case.test {
Some(e)
if matches!(
&**e,
Expr::Lit(Lit::Str(..))
| Expr::Lit(Lit::Null(..))
| Expr::Lit(Lit::Num(..))
) =>
{
true
}
_ => false,
})
{
// No case can be matched.
if s.cases
.iter()
.all(|case| !has_conditional_stopper(&case.cons))
{
if cfg!(feature = "debug") {
debug!("Removing swtich because all cases are unreachable");
}
// Preserve variables
let decls: Vec<_> = s
.cases
.into_iter()
.flat_map(|case| extract_var_ids(&case.cons))
.chain(var_ids)
.map(|i| VarDeclarator {
span: i.span,
name: i.into(),
init: None,
definite: false,
})
.collect();
if !decls.is_empty() {
return VarDecl {
span: DUMMY_SP,
kind: VarDeclKind::Var,
decls,
declare: false,
..Default::default()
}
.into();
}
return EmptyStmt { span: s.span }.into();
}
}
s.into()
}
Stmt::For(s)
if match &s.test {
Some(test) => {
matches!(&**test, Expr::Lit(Lit::Bool(Bool { value: false, .. })))
}
_ => false,
} =>
{
if cfg!(feature = "debug") {
debug!("Optimizing a for statement with a false test");
}
let decl = s.body.extract_var_ids_as_var();
let body = if let Some(var) = decl {
var.into()
} else {
EmptyStmt { span: s.span }.into()
};
if s.init.is_some() {
ForStmt {
body: Box::new(body),
update: None,
..s
}
.into()
} else {
body
}
}
Stmt::While(s) => {
if let (purity, Known(v)) = s.test.cast_to_bool(self.expr_ctx) {
if v {
if purity.is_pure() {
WhileStmt {
test: Lit::Bool(Bool {
span: s.test.span(),
value: true,
})
.into(),
..s
}
.into()
} else {
s.into()
}
} else {
let body = s.body.extract_var_ids_as_var();
let body = body.map(Box::new).map(Decl::Var).map(Stmt::Decl);
let body = body.unwrap_or(EmptyStmt { span: s.span }.into());
if purity.is_pure() {
body
} else {
WhileStmt {
body: Box::new(body),
..s
}
.into()
}
}
} else {
s.into()
}
}
Stmt::DoWhile(s) => {
if has_conditional_stopper(&[s.clone().into()]) {
return s.into();
}
if let Known(v) = s.test.as_pure_bool(self.expr_ctx) {
if v {
// `for(;;);` is shorter than `do ; while(true);`
ForStmt {
span: s.span,
init: None,
test: None,
update: None,
body: s.body,
}
.into()
} else {
let mut body = prepare_loop_body_for_inlining(*s.body);
body.visit_mut_with(self);
if let Some(test) = ignore_result(s.test, true, self.expr_ctx) {
BlockStmt {
span: s.span,
stmts: vec![body, test.into_stmt()],
..Default::default()
}
.into()
} else {
body
}
}
} else {
s.into()
}
}
Stmt::Decl(Decl::Var(v)) => {
let decls = v.decls.move_flat_map(|v| {
if !is_literal(&v.init) {
return Some(v);
}
//
match &v.name {
Pat::Object(o) if o.props.is_empty() => {
if cfg!(feature = "debug") {
debug!("Dropping an object pattern in a var declaration");
}
None
}
Pat::Array(a) if a.elems.is_empty() => {
if cfg!(feature = "debug") {
debug!("Dropping an array pattern in a var declaration");
}
None
}
_ => Some(v),
}
});
if decls.is_empty() {
if cfg!(feature = "debug") {
debug!("Dropping a useless variable declaration");
}
return EmptyStmt { span: v.span }.into();
}
VarDecl { decls, ..*v }.into()
}
_ => stmt,
}
})
}
fn visit_mut_stmts(&mut self, n: &mut Vec<Stmt>) {
self.fold_stmt_like(n)
}
fn visit_mut_switch_stmt(&mut self, s: &mut SwitchStmt) {
s.visit_mut_children_with(self);
if s.cases
.iter()
.any(|case| matches!(case.test.as_deref(), Some(Expr::Update(..))))
{
return;
}
if s.cases.iter().all(|case| {
if let Some(test) = case.test.as_deref() {
if test.may_have_side_effects(self.expr_ctx) {
return false;
}
}
if case.cons.is_empty() {
return true;
}
matches!(case.cons[0], Stmt::Break(BreakStmt { label: None, .. }))
}) {
s.cases.clear();
}
}
fn visit_mut_var_declarators(&mut self, n: &mut Vec<VarDeclarator>) {
self.maybe_par(cpu_count() * 8, n, |v, n| {
n.visit_mut_with(v);
})
}
}
impl Remover {
fn fold_stmt_like<T>(&mut self, stmts: &mut Vec<T>)
where
T: StmtLike + VisitWith<Hoister> + VisitMutWith<Self>,
{
let orig_len = stmts.len();
let is_block_stmt = self.normal_block;
self.normal_block = false;
let mut new_stmts = Vec::with_capacity(stmts.len());
self.maybe_par(cpu_count() * 8, &mut *stmts, |visitor, stmt| {
visitor.normal_block = true;
stmt.visit_mut_with(visitor);
});
let mut iter = stmts.take().into_iter();
while let Some(stmt_like) = iter.next() {
let stmt_like = match stmt_like.try_into_stmt() {
Ok(stmt) => {
let stmt = match stmt {
// Remove empty statements.
Stmt::Empty(..) => continue,
Stmt::Expr(ExprStmt { ref expr, .. })
if match &**expr {
Expr::Lit(Lit::Str(..)) => false,
Expr::Lit(..) => true,
_ => false,
} && is_block_stmt =>
{
continue
}
// Control flow
Stmt::Throw(..)
| Stmt::Return { .. }
| Stmt::Continue { .. }
| Stmt::Break { .. } => {
// Hoist function and `var` declarations above return.
let mut decls = Vec::new();
let mut hoisted_fns = Vec::new();
for t in iter {
match t.try_into_stmt() {
Ok(Stmt::Decl(Decl::Fn(f))) => {
hoisted_fns.push(T::from(f.into()));
}
Ok(t) => {
let ids = extract_var_ids(&t).into_iter().map(|i| {
VarDeclarator {
span: i.span,
name: i.into(),
init: None,
definite: false,
}
});
decls.extend(ids);
}
Err(item) => new_stmts.push(item),
}
}
if !decls.is_empty() {
new_stmts.push(T::from(
VarDecl {
span: DUMMY_SP,
kind: VarDeclKind::Var,
decls,
declare: false,
..Default::default()
}
.into(),
));
}
let stmt_like = T::from(stmt);
new_stmts.push(stmt_like);
new_stmts.extend(hoisted_fns);
*stmts = new_stmts;
if stmts.len() != orig_len {
self.changed = true;
if cfg!(feature = "debug") {
debug!("Dropping statements after a control keyword");
}
}
return;
}
Stmt::Block(BlockStmt {
span,
mut stmts,
ctxt,
..
}) => {
if stmts.is_empty() {
continue;
}
if !is_ok_to_inline_block(&stmts) {
stmts.visit_mut_with(self);
BlockStmt { span, stmts, ctxt }.into()
} else {
new_stmts.extend(
stmts
.into_iter()
.filter(|s| !matches!(s, Stmt::Empty(..)))
.map(T::from),
);
continue;
}
}
// Optimize if statement.
Stmt::If(IfStmt {
test,
cons,
alt,
span,
}) => {
// check if
match test.cast_to_bool(self.expr_ctx) {
(purity, Known(val)) => {
self.changed = true;
if !purity.is_pure() {
let expr = ignore_result(test, true, self.expr_ctx);
if let Some(expr) = expr {
new_stmts.push(T::from(
ExprStmt {
span: DUMMY_SP,
expr,
}
.into(),
));
}
}
if val {
// Hoist vars from alt
if let Some(var) =
alt.and_then(|alt| alt.extract_var_ids_as_var())
{
new_stmts.push(T::from(var.into()))
}
*cons
} else {
// Hoist vars from cons
if let Some(var) = cons.extract_var_ids_as_var() {
new_stmts.push(T::from(var.into()))
}
match alt {
Some(alt) => *alt,
None => continue,
}
}
}
_ => IfStmt {
test,
cons,
alt,
span,
}
.into(),
}
}
_ => stmt,
};
T::from(stmt)
}
Err(stmt_like) => stmt_like,
};
new_stmts.push(stmt_like);
}
*stmts = new_stmts
}
}
/// Ignores the result.
///
/// Returns
/// - [Some] if `e` has a side effect.
/// - [None] if `e` does not have a side effect.
#[inline(never)]
fn ignore_result(e: Box<Expr>, drop_str_lit: bool, ctx: ExprCtx) -> Option<Box<Expr>> {
match *e {
Expr::Lit(Lit::Num(..))
| Expr::Lit(Lit::Bool(..))
| Expr::Lit(Lit::Null(..))
| Expr::Lit(Lit::Regex(..)) => None,
Expr::Lit(Lit::Str(ref v)) if drop_str_lit || v.value.is_empty() => None,
Expr::Paren(ParenExpr { expr, .. }) => ignore_result(expr, true, ctx),
Expr::Assign(AssignExpr {
op: op!("="),
left: AssignTarget::Simple(left),
right,
..
}) if match &left {
SimpleAssignTarget::Ident(l) => match &*right {
Expr::Ident(r) => l.sym == r.sym && l.ctxt == r.ctxt,
_ => false,
},
_ => false,
} =>
{
None
}
Expr::Bin(BinExpr {
span,
left,
op,
right,
}) if !op.may_short_circuit() => {
let left = ignore_result(left, true, ctx);
let right = ignore_result(right, true, ctx);
match (left, right) {
(Some(l), Some(r)) => ignore_result(
ctx.preserve_effects(span, Expr::undefined(span), vec![l, r]),
true,
ctx,
),
(Some(l), None) => Some(l),
(None, Some(r)) => Some(r),
(None, None) => None,
}
}
Expr::Bin(BinExpr {
span,
left,
op,
right,
}) => {
if op == op!("&&") {
let right = if let Some(right) = ignore_result(right, true, ctx) {
right
} else {
return ignore_result(left, true, ctx);
};
let l = left.as_pure_bool(ctx);
if let Known(l) = l {
if l {
Some(right)
} else {
None
}
} else {
Some(
BinExpr {
span,
left,
op,
right,
}
.into(),
)
}
} else {
debug_assert!(op == op!("||") || op == op!("??"));
let l = left.as_pure_bool(ctx);
if let Known(l) = l {
if l {
None
} else {
ignore_result(right, true, ctx)
}
} else {
let right = ignore_result(right, true, ctx);
if let Some(right) = right {
Some(
BinExpr {
span,
left,
op,
right,
}
.into(),
)
} else {
ignore_result(left, true, ctx)
}
}
}
}
Expr::Unary(UnaryExpr { span, op, arg }) => match op {
// Don't remove ! from negated iifes.
op!("!")
if match &*arg {
Expr::Call(call) => match &call.callee {
Callee::Expr(callee) => matches!(&**callee, Expr::Fn(..)),
_ => false,
},
_ => false,
} =>
{
Some(UnaryExpr { span, op, arg }.into())
}
op!("void") | op!(unary, "+") | op!(unary, "-") | op!("!") | op!("~") => {
ignore_result(arg, true, ctx)
}
_ => Some(UnaryExpr { span, op, arg }.into()),
},
Expr::Array(ArrayLit { span, elems, .. }) => {
let mut has_spread = false;
let elems = elems.move_flat_map(|v| match v {
Some(ExprOrSpread {
spread: Some(..), ..
}) => {
has_spread = true;
Some(v)
}
None => None,
Some(ExprOrSpread { spread: None, expr }) => ignore_result(expr, true, ctx)
.map(|expr| Some(ExprOrSpread { spread: None, expr })),
});
if elems.is_empty() {
None
} else if has_spread {
Some(ArrayLit { span, elems }.into())
} else {
ignore_result(
ctx.preserve_effects(
span,
Expr::undefined(span),
elems.into_iter().map(|v| v.unwrap().expr),
),
true,
ctx,
)
}
}
Expr::Object(ObjectLit { span, props, .. }) => {
let props = props.move_flat_map(|v| match v {
PropOrSpread::Spread(..) => Some(v),
PropOrSpread::Prop(ref p) => {
if is_literal(&**p) {
None
} else {
Some(v)
}
}
});
if props.is_empty() {
None
} else {
ignore_result(
ctx.preserve_effects(
span,
Expr::undefined(DUMMY_SP),
once(ObjectLit { span, props }.into()),
),
true,
ctx,
)
}
}
Expr::New(NewExpr {
span,
ref callee,
args,
..
}) if callee.is_pure_callee(ctx) => ignore_result(
ArrayLit {
span,
elems: args
.map(|args| args.into_iter().map(Some).collect())
.unwrap_or_else(Default::default),
}
.into(),
true,
ctx,
),
Expr::Call(CallExpr {
span,
callee: Callee::Expr(ref callee),
args,
..
}) if callee.is_pure_callee(ctx) => ignore_result(
ArrayLit {
span,
elems: args.into_iter().map(Some).collect(),
}
.into(),
true,
ctx,
),
Expr::Tpl(Tpl { span, exprs, .. }) => ignore_result(
ctx.preserve_effects(span, Expr::undefined(span), exprs),
true,
ctx,
),
Expr::TaggedTpl(TaggedTpl { span, tag, tpl, .. }) if tag.is_pure_callee(ctx) => {
ignore_result(
ctx.preserve_effects(span, Expr::undefined(span), tpl.exprs),
true,
ctx,
)
}
//
// Function expressions are useless if they are not used.
//
// As function expressions cannot start with 'function',
// this will be reached only if other things
// are removed while folding children.
Expr::Fn(..) => None,
Expr::Seq(SeqExpr {
span, mut exprs, ..
}) => {
if exprs.is_empty() {
return None;
}
let last = ignore_result(exprs.pop().unwrap(), true, ctx);
exprs.extend(last);
if exprs.is_empty() {
return None;
}
if exprs.len() == 1 {
return Some(exprs.pop().unwrap());
}
Some(SeqExpr { span, exprs }.into())
}
Expr::Cond(CondExpr {
span,
test,
cons,
alt,
}) => {
let alt = if let Some(alt) = ignore_result(alt, true, ctx) {
alt
} else {
return ignore_result(
BinExpr {
span,
left: test,
op: op!("&&"),
right: cons,
}
.into(),
true,
ctx,
);
};
let cons = if let Some(cons) = ignore_result(cons, true, ctx) {
cons
} else {
return ignore_result(
BinExpr {
span,
left: test,
op: op!("||"),
right: alt,
}
.into(),
true,
ctx,
);
};
Some(
CondExpr {
span,
test,
cons,
alt,
}
.into(),
)
}
_ => Some(e),
}
}
/// # Returns true for
///
/// ```js
/// {
/// var x = 1;
/// }
/// ```
///
/// ```js
/// {
/// var x;
/// var y;
/// var z;
/// {
/// var a;
/// var b;
/// }
/// }
/// ```
///
/// ```js
/// {
/// var a = 0;
/// foo();
/// }
/// ```
///
/// # Returns false for
///
/// ```js
/// a: {
/// break a;
/// var x = 1;
/// }
/// ```
fn is_ok_to_inline_block(s: &[Stmt]) -> bool {
// TODO: This may be inlinable if return / throw / break / continue exists
if s.iter().any(is_block_scoped_stuff) {
return false;
}
// variable declared as `var` is hoisted
let last_var = s.iter().rposition(|s| match s {
Stmt::Decl(Decl::Var(v))
if matches!(
&**v,
VarDecl {
kind: VarDeclKind::Var,
..
},
) =>
{
true
}
_ => false,
});
let last_var = if let Some(pos) = last_var {
pos
} else {
return true;
};
let last_stopper = s.iter().rposition(|s| {
matches!(
s,
Stmt::Return(..) | Stmt::Throw(..) | Stmt::Break(..) | Stmt::Continue(..)
)
});
if let Some(last_stopper) = last_stopper {
last_stopper > last_var
} else {
true
}
}
fn is_block_scoped_stuff(s: &Stmt) -> bool {
match s {
Stmt::Decl(Decl::Var(v)) if v.kind == VarDeclKind::Const || v.kind == VarDeclKind::Let => {
true
}
Stmt::Decl(Decl::Fn(..)) | Stmt::Decl(Decl::Class(..)) => true,
_ => false,
}
}
fn prepare_loop_body_for_inlining(stmt: Stmt) -> Stmt {
let span = stmt.span();
let mut stmts = match stmt {
Stmt::Block(BlockStmt { stmts, .. }) => stmts,
_ => vec![stmt],
};
let mut done = false;
stmts.retain(|stmt| {
if done {
return false;
}
match stmt {
Stmt::Break(BreakStmt { label: None, .. })
| Stmt::Continue(ContinueStmt { label: None, .. }) => {
done = true;
false
}
Stmt::Return(..) | Stmt::Throw(..) => {
done = true;
true
}
_ => true,
}
});
BlockStmt {
span,
stmts,
..Default::default()
}
.into()
}
fn has_unconditional_stopper(s: &[Stmt]) -> bool {
check_for_stopper(s, false)
}
fn has_conditional_stopper(s: &[Stmt]) -> bool {
check_for_stopper(s, true)
}
fn check_for_stopper(s: &[Stmt], only_conditional: bool) -> bool {
struct Visitor {
in_cond: bool,
found: bool,
}
impl Visit for Visitor {
noop_visit_type!();
fn visit_switch_case(&mut self, node: &SwitchCase) {
let old = self.in_cond;
self.in_cond = true;
node.cons.visit_with(self);
self.in_cond = old;
}
fn visit_break_stmt(&mut self, s: &BreakStmt) {
if self.in_cond && s.label.is_none() {
self.found = true
}
}
fn visit_continue_stmt(&mut self, s: &ContinueStmt) {
if self.in_cond && s.label.is_none() {
self.found = true
}
}
fn visit_return_stmt(&mut self, _: &ReturnStmt) {
if self.in_cond {
self.found = true
}
}
fn visit_throw_stmt(&mut self, _: &ThrowStmt) {
if self.in_cond {
self.found = true
}
}
fn visit_class(&mut self, _: &Class) {}
fn visit_function(&mut self, _: &Function) {}
fn visit_if_stmt(&mut self, node: &IfStmt) {
let old = self.in_cond;
self.in_cond = true;
node.cons.visit_with(self);
self.in_cond = true;
node.alt.visit_with(self);
self.in_cond = old;
}
}
let mut v = Visitor {
in_cond: !only_conditional,
found: false,
};
v.visit_stmts(s);
v.found
}
/// Finds the depth of statements without hitting a block
fn stmt_depth(s: &Stmt) -> u32 {
let mut depth = 0;
match s {
// Stop when hitting a statement we know can't increase statement depth.
Stmt::Block(_) | Stmt::Labeled(_) | Stmt::Switch(_) | Stmt::Decl(_) | Stmt::Expr(_) => {}
// Take the max depth of if statements
Stmt::If(i) => {
depth += 1;
if let Some(alt) = &i.alt {
depth += std::cmp::max(stmt_depth(&i.cons), stmt_depth(alt));
} else {
depth += stmt_depth(&i.cons);
}
}
// These statements can have bodies without a wrapping block
Stmt::With(WithStmt { body, .. })
| Stmt::While(WhileStmt { body, .. })
| Stmt::DoWhile(DoWhileStmt { body, .. })
| Stmt::For(ForStmt { body, .. })
| Stmt::ForIn(ForInStmt { body, .. })
| Stmt::ForOf(ForOfStmt { body, .. }) => {
depth += 1;
depth += stmt_depth(body);
}
// All other statements increase the depth by 1
_ => depth += 1,
}
depth
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_optimization/src/simplify/branch/tests.rs | Rust | use swc_common::{Mark, SyntaxContext};
use swc_ecma_transforms_base::{fixer::paren_remover, resolver};
use swc_ecma_utils::ExprCtx;
use swc_ecma_visit::visit_mut_pass;
use super::super::expr_simplifier;
macro_rules! test_stmt {
($l:expr, $r:expr) => {
swc_ecma_transforms_testing::test_transform(
::swc_ecma_parser::Syntax::default(),
None,
|_| {
let unresolved_mark = Mark::new();
let top_level_mark = Mark::new();
(
resolver(unresolved_mark, top_level_mark, false),
paren_remover(None),
expr_simplifier(top_level_mark, Default::default()),
visit_mut_pass(super::Remover {
changed: false,
normal_block: Default::default(),
expr_ctx: ExprCtx {
unresolved_ctxt: SyntaxContext::empty().apply_mark(unresolved_mark),
// This is hack
is_unresolved_ref_safe: true,
in_strict: false,
remaining_depth: 4,
},
}),
)
},
$l,
$r,
)
};
}
fn test(src: &str, expected: &str) {
test_stmt!(src, expected)
}
/// Should not modify expression.
fn test_same(s: &str) {
test(s, s)
}
// /// Should not modify expression.
// macro_rules! same_stmt {
// ($l:expr) => {
// test_stmt!($l, $l)
// };
// }
/// Ensures that it is removed.
macro_rules! compiled_out {
($src:expr) => {
test_stmt!($src, "")
};
}
#[test]
fn usage() {
test_stmt!("use(8+8);", "use(16);");
}
#[test]
fn compiled_out_simple() {
compiled_out!(";");
compiled_out!("8;");
compiled_out!("8+8;");
}
#[test]
fn test_remove_no_op_labelled_statement() {
test("a: break a;", "");
test("a: { break a; }", "");
test("a: { break a; console.log('unreachable'); }", "");
test(
"a: { break a; var x = 1; } x = 2;",
"a: { var x; break a; } x = 2; ",
);
test("b: { var x = 1; } x = 2;", "b: var x = 1; x = 2;");
test("a: b: { var x = 1; } x = 2;", "a: b: var x = 1; x = 2;");
}
#[test]
fn test_fold_block() {
test("{{foo()}}", "foo()");
test("{foo();{}}", "foo()");
test("{{foo()}{}}", "foo()");
test("{{foo()}{bar()}}", "foo();bar()");
test("{if(false)foo(); {bar()}}", "bar()");
test("{if(false)if(false)if(false)foo(); {bar()}}", "bar()");
test("{'hi'}", "'hi'");
test("{x==3}", "x");
test("{`hello ${foo}`}", "");
test("{ (function(){x++}) }", "");
test_same("function f(){return;}");
test("function f(){return 3;}", "function f(){return 3}");
test_same("function f(){if(x)return; x=3; return; }");
test("{x=3;;;y=2;;;}", "x=3;y=2");
// Cases to test for empty block.
test("while(x()){x}", "while(x())x;");
test("while(x()){x()}", "while(x())x()");
test("for(x=0;x<100;x++){x}", "for(x=0;x<100;x++)x;");
test("for(x in y){x}", "for(x in y)x;");
test("for (x of y) {x}", "for(x of y)x;");
test_same("for (let x = 1; x <10; x++ );");
test_same("for (var x = 1; x <10; x++ );");
}
#[test]
fn test_fold_block_with_declaration() {
test_same("{let x}");
test_same("function f() {let x}");
test_same("{const x = 1}");
test_same("{x = 2; y = 4; let z;}");
test("{'hi'; let x;}", "{'hi'; let x}");
test("{x = 4; {let y}}", "x = 4; {let y}");
test_same("{class C {}} {class C1 {}}");
test("{label: var x}", "label: var x");
// `{label: let x}` is a syntax error
test_same("{label: var x; let y;}");
}
#[test]
/// Try to remove spurious blocks with multiple children
fn test_fold_blocks_with_many_children() {
test("function f() { if (false) {} }", "function f(){}");
test(
"function f() { { if (false) {} if (true) {} {} } }",
"function f(){}",
);
test(
"{var x; var y; var z; class Foo { constructor() { var a; { var b; } } } }",
"{var x;var y;var z;class Foo { constructor() { var a;var b} } }",
);
test(
"{var x; var y; var z; { { var a; { var b; } } } }",
"var x;var y;var z; var a;var b",
);
}
#[test]
fn test_if() {
test("if (1){ x=1; } else { x = 2;}", "x=1");
test("if (false){ x = 1; } else { x = 2; }", "x=2");
test("if (undefined){ x = 1; } else { x = 2; }", "x=2");
test("if (null){ x = 1; } else { x = 2; }", "x=2");
test("if (void 0){ x = 1; } else { x = 2; }", "x=2");
test("if (void foo()){ x = 1; } else { x = 2; }", "foo();x=2");
test(
"if (false){ x = 1; } else if (true) { x = 3; } else { x = 2; }",
"x=3",
);
test("if (x){ x = 1; } else if (false) { x = 3; }", "if(x)x=1");
test_same(concat!(
"if (x) {",
" if (y) log(1);",
" else if (z) log(2);",
"} else log(3);",
));
test_same("if (0 | x) y = 1; else y = 2;");
// test("if (1 | x) y = 1; else y = 2;", "y=1;");
// test("if (0 & x) y = 1; else y = 2;", "y=2");
test_same("if (1 & x) y = 1; else y = 2;");
}
#[test]
fn test_hook() {
test("true ? a() : b()", "a()");
test("false ? a() : b()", "b()");
test("a() ? b() : true", "a() && b()");
test("a() ? true : b()", "a() || b()");
test("(a = true) ? b() : c()", "a = true, b()");
test("(a = false) ? b() : c()", "a = false, c()");
test(
"do {f()} while((a = true) ? b() : c())",
"do f(); while(a = true , b())",
);
test(
"do {f()} while((a = false) ? b() : c())",
"do f(); while(a = false , c())",
);
test("var x = (true) ? 1 : 0", "var x=1");
test(
"var y = (true) ? ((false) ? 12 : (cond ? 1 : 2)) : 13",
"var y=cond?1:2",
);
test_same("var z=x?void 0:y()");
test_same("z=x?void 0:y()");
test_same("z*=x?void 0:y()");
test_same("var z=x?y():void 0");
test_same("(w?x:void 0).y=z");
test_same("(w?x:void 0).y+=z");
test("y = (x ? void 0 : void 0)", "y = void 0");
}
#[test]
#[ignore]
fn test_hook_extra() {
test("y = (x ? f() : f())", "y = f()");
test("(function(){}) ? function(){} : function(){}", "");
}
#[test]
fn test_constant_condition_with_side_effect1() {
test("if (b=true) x=1;", "b=true;x=1");
test("if (b=/ab/) x=1;", "b=/ab/;x=1");
test("if (b=/ab/){ x=1; } else { x=2; }", "b=/ab/;x=1");
// test("var b;b=/ab/;if(b)x=1;", "var b;b=/ab/;x=1");
test_same("var b;b=f();if(b)x=1;");
// test("var b=/ab/;if(b)x=1;", "var b=/ab/;x=1");
test_same("var b=f();if(b)x=1;");
test_same("b=b++;if(b)x=b;");
test("(b=0,b=1);if(b)x=b;", "b=0,b=1;if(b)x=b;");
// test("b=1;if(foo,b)x=b;", "b=1;x=b;");
test_same("b=1;if(foo=1,b)x=b;");
}
#[test]
fn test_constant_condition_with_side_effect2() {
test("(b=true)?x=1:x=2;", "b=true,x=1");
test("(b=false)?x=1:x=2;", "b=false,x=2");
test("if (b=/ab/) x=1;", "b=/ab/;x=1");
// test("var b;b=/ab/;(b)?x=1:x=2;", "var b;b=/ab/;x=1");
test_same("var b;b=f();b?x=1:x=2;");
// test("var b=/ab/;(b)?x=1:x=2;", "var b=/ab/;x=1");
test_same("var b=f();b?x=1:x=2;");
}
#[test]
fn test_var_lifting() {
test("if(true)var a", "var a");
test("if(false)var a", "var a");
// More var lifting tests in PeepholeIntegrationTests
}
#[test]
fn test_let_const_lifting() {
test("if(true) {const x = 1}", "{const x = 1}");
test("if(false) {const x = 1}", "");
test("if(true) {let x}", "{let x}");
test("if(false) {let x}", "");
}
#[test]
fn test_fold_useless_for() {
test("for(;false;) { foo() }", "");
test("for(;void 0;) { foo() }", "");
test("for(;undefined;) { foo() }", "");
test("for(;true;) foo() ", "for(;;) foo() ");
test_same("for(;;) foo()");
test("for(;false;) { var a = 0; }", "var a");
test("for(;false;) { const a = 0; }", "");
test("for(;false;) { let a = 0; }", "");
// Make sure it plays nice with minimizing
test("for(;false;) { foo(); continue }", "");
}
#[test]
fn test_fold_useless_do_1() {
test("do { foo() } while(false);", "foo()");
test("do { foo() } while(void 0);", "foo()");
test("do { foo() } while(undefined);", "foo(); undefined");
test("do { foo() } while(true);", "for(;;) foo();");
test("do { var a = 0; } while(false);", "var a=0");
}
#[test]
#[ignore]
fn test_fold_useless_do_2() {
// Can't fold with break or continues.
test("do { foo(); continue; } while(0)", "foo();");
}
#[test]
fn test_fold_useless_do_3() {
test(
"do { try { foo() } catch (e) { break; } } while (0);",
"try { foo(); } catch (e) { break; }",
);
test("do { foo(); break; } while(0)", "foo();");
test(
"do { for (;;) {foo(); continue;} } while(0)",
"for (;;) {foo(); continue;}",
);
test(
"l1: do { for (;;) { foo() } } while(0)",
"l1: for(;;) foo();",
);
test(
"do { switch (1) { default: foo(); break} } while(0)",
"foo();",
);
test(
"do { switch (1) { default: foo(); continue} } while(0)",
"foo();",
);
test(
"l1: { do { x = 1; break l1; } while (0); x = 2; }",
"l1: { x = 1; break l1; x = 2;}",
);
}
#[test]
#[ignore]
fn test_fold_useless_do_extra() {
test("do { x = 1; } while (x = 0);", "x = 1; x = 0;");
test(
"let x = 1; (function() { do { let x = 2; } while (x = 10, false); })();",
"let x = 1; (function() { { let x = 2 } x = 10 })();",
);
}
#[test]
fn test_no_fold_do_with_conditional_stopper() {
test_same("do { if (Date.now() > 0) break; } while (0);");
test_same("do { if (Date.now() > 0) continue; } while (0);");
}
#[test]
fn test_fold_empty_do() {
test("do { } while(true);", "for (;;);");
}
#[test]
fn test_minimize_loop_with_constant_condition_vanilla_for() {
test("for(;true;) foo()", "for(;;) foo()");
test("for(;0;) foo()", "");
test("for(;0.0;) foo()", "");
test("for(;NaN;) foo()", "");
test("for(;null;) foo()", "");
test("for(;undefined;) foo()", "");
test("for(;'';) foo()", "");
}
#[test]
fn test_minimize_loop_with_constant_condition_do_while() {
test("do { foo(); } while (true)", "for(;;)foo();");
test("do { foo(); } while (0)", "foo();");
test("do { foo(); } while (0.0)", "foo();");
test("do { foo(); } while (NaN)", "foo(); NaN");
test("do { foo(); } while (null)", "foo();");
test("do { foo(); } while (undefined)", "foo(); undefined");
test("do { foo(); } while ('')", "foo();");
}
#[test]
fn test_fold_constant_comma_expressions() {
test("if (true, false) {foo()}", "");
test("if (false, true) {foo()}", "foo()");
test("true, foo()", "foo()");
test("(1 + 2 + ''), foo()", "foo()");
}
#[test]
fn test_remove_useless_ops1() {
test_same("(function () { f(); })();");
}
#[test]
fn test_remove_useless_ops2() {
// There are four place where expression results are discarded:
// - a top-level expression EXPR_RESULT
// - the LHS of a COMMA
// - the FOR init expression
// - the FOR increment expression
// Known side-effect free functions calls are removed.
test("Math.random()", "");
test("Math.random(f() + g())", "f(),g();");
test("Math.random(f(),g(),h())", "f(),g(),h();");
// Calls to functions with unknown side-effects are left.
test_same("f();");
test_same("(function () { f(); })();");
// We know that this function has no side effects because of the
// PureFunctionIdentifier.
test("(function () {})();", "");
// Uncalled function expressions are removed
test("(function () {});", "");
test("(function f() {});", "");
test("(function* f() {})", "");
// ... including any code they contain.
test("(function () {foo();});", "");
// Useless operators are removed.
test("+f()", "f()");
test("a=(+f(),g())", "a=(f(),g())");
test("a=(true,g())", "a=g()");
test("f(),true", "f()");
test("f() + g()", "f(),g()");
test("for(;;+f()){}", "for(;;f());");
test("for(+f();;g()){}", "for(f();;g());");
test("for(;;Math.random(f(),g(),h())){}", "for(;;f(),g(),h());");
// The optimization cascades into conditional expressions:
test("g() && +f()", "g() && f()");
test("g() || +f()", "g() || f()");
test("x ? g() : +f()", "x ? g() : f()");
test("+x()", "x()");
test("+x() * 2", "x()");
test("-(+x() * 2)", "x()");
test("2 -(+x() * 2)", "x()");
//test("x().foo", "x()");
test_same("x().foo()");
test_same("x++");
test_same("++x");
test_same("x--");
test_same("--x");
test_same("x = 2");
test_same("x *= 2");
// Sanity check, other expression are left alone.
test_same("function f() {}");
test_same("var x;");
}
#[test]
fn test_optimize_switch_1() {
test("switch(a){}", "a");
test("switch(foo()){}", "foo()");
test("switch(a){default:}", "a");
test("switch(a){default:break;}", "a");
test("switch(a){default:var b;break;}", "a;var b");
test("switch(a){case 1: default:}", "a");
test("switch(a){default: case 1:}", "a");
test("switch(a){default: break; case 1:break;}", "a");
//test(
// "switch(a){default: var b; break; case 1: var c; break;}",
// "var c; var b;",
//);
//test("var x=1; switch(x) { case 1: var y; }", "var y; var x=1;");
// Can't remove cases if a default exists and is not the last case.
test_same("function f() {switch(a){default: return; case 1: break;}}");
test(
"function f() {switch(1){default: return; case 1: break;}}",
"function f() {}",
);
test_same("function f() {switch(a){case 1: foo();}}");
test_same("function f() {switch(a){case 3: case 2: case 1: foo();}}");
test(
"function f() {switch(a){case 2: case 1: default: foo();}}",
"function f() { a; foo(); }",
);
//test(
// "switch(a){case 1: default:break; case 2: foo()}",
// "switch(a){case 2: foo()}",
//);
test_same("switch(a){case 1: goo(); default:break; case 2: foo()}");
// TODO(johnlenz): merge the useless "case 2"
test_same("switch(a){case 1: goo(); case 2:break; case 3: foo()}");
// Can't remove unused code with a "var" in it.
test("switch(1){case 2: var x=0;}", "var x;");
test(
"switch ('repeated') {\ncase 'repeated':\n foo();\n break;\ncase 'repeated':\n var \
x=0;\n break;\n}",
"foo(); var x;",
);
// Can't remove cases if something useful is done.
test_same("switch(a){case 1: var c =2; break;}");
test_same("function f() {switch(a){case 1: return;}}");
test_same("x:switch(a){case 1: break x;}");
test(
"switch ('foo') {\ncase 'foo':\n foo();\n break;\ncase 'bar':\n bar();\n break;\n}",
"foo();",
);
test(
"switch ('noMatch') {\ncase 'foo':\n foo();\n break;\ncase 'bar':\n bar();\n break;\n}",
"",
);
}
#[test]
#[ignore]
fn test_optimize_switch_2() {
test(
concat!(
"switch ('fallThru') {",
"case 'fallThru':",
" if (foo(123) > 0) {",
" foobar(1);",
" break;",
" }",
" foobar(2);",
"case 'bar':",
" bar();",
"}",
),
concat!(
"switch ('fallThru') {",
"case 'fallThru':",
" if (foo(123) > 0) {",
" foobar(1);",
" break;",
" }",
" foobar(2);",
" bar();",
"}",
),
);
}
#[test]
#[ignore]
fn test_optimize_switch_3() {
test(
concat!(
"switch ('fallThru') {",
"case 'fallThru':",
" foo();",
"case 'bar':",
" bar();",
"}",
),
concat!("foo();", "bar();"),
);
}
#[test]
fn test_optimize_switch_4() {
test(
"switch ('repeated') {\ncase 'repeated':\n foo();\n break;\ncase 'repeated':\n \
bar();\n break;\n}",
"foo();",
);
test(
"switch ('foo') {\ncase 'bar':\n bar();\n break;\ncase notConstant:\n foobar();\n \
break;\ncase 'foo':\n foo();\n break;\n}",
"switch ('foo') {\ncase notConstant:\n foobar();\n break;\ncase 'foo':\n foo();\n \
break;\n}",
);
test(
"switch (1) {\ncase 1:\n foo();\n break;\ncase 2:\n bar();\n break;\n}",
"foo();",
);
test(
"switch (true) {\ncase true:\n foo();\n break;\ncase false:\n bar();\n break;
default: foobar(); break; \n}",
"foo();",
);
test(
"switch (1) {\ncase 1.1:\n foo();\n break;\ncase 2:\n bar();\n break;\n}",
"",
);
test(
"switch (0) {\ncase NaN:\n foobar();\n break;\ncase -0.0:\n foo();\n break;\ncase \
2:\n bar();\n break;\n}",
"foo();",
);
// test_same("switch ('\\v') {\ncase '\\u000B':\n foo();\n}");
test(
concat!(
"switch ('empty') {",
"case 'empty':",
"case 'foo':",
" foo();",
"}",
),
"foo()",
);
// TODO:
//test(
// concat!(
// "let x;", //
// "switch (use(x)) {",
// " default: {let y;}",
// "}",
// ),
// concat!(
// "let x;", //
// "use(x);", "{let y}",
// ),
//);
test(
concat!(
"let x;", //
"switch (use(x)) {",
" default: {let y;}",
"}",
),
concat!(
"let x;", //
"use(x); { let y; }",
),
);
test(
concat!(
"let x;", //
"switch (use(x)) {",
" default: let y;",
"}",
),
concat!(
"let x;", //
"{ use(x); let y; }",
),
);
}
#[test]
fn test_optimize_switch_bug11536863() {
test(
"outer: { switch (2) {\n case 2:\n f();\n break outer;\n }}",
"outer: {f(); break outer;}",
);
}
#[test]
fn test_optimize_switch2() {
test(
"outer: switch (2) {\n case 2:\n f();\n break outer;\n}",
"outer: {f(); break outer;}",
);
}
#[test]
fn test_optimize_switch3() {
test(
concat!(
"switch (1) {",
" case 1:",
" case 2:",
" case 3: {",
" break;",
" }",
" case 4:",
" case 5:",
" case 6:",
" default:",
" fail('Should not get here');",
" break;",
"}",
),
"",
);
}
#[test]
fn test_optimize_switch_with_labelless_break() {
test(
concat!(
"function f() {",
" switch('x') {",
" case 'x': var x = 1; break;",
" case 'y': break;",
" }",
"}",
),
"function f() { var x = 1; }",
);
// TODO(moz): Convert this to an if statement for better optimization
test_same(concat!(
"function f() {",
" switch(x) {",
" case 'y': break;",
" default: var x = 1;",
" }",
"}",
));
test(
concat!(
"var exit;",
"switch ('a') {",
" case 'a':",
" break;",
" default:",
" exit = 21;",
" break;",
"}",
"switch(exit) {",
" case 21: throw 'x';",
" default : console.log('good');",
"}",
),
concat!(
"var exit;",
"switch(exit) {",
" case 21: throw 'x';",
" default : console.log('good');",
"}",
),
);
test(
concat!(
"let x = 1;",
"switch('x') {",
" case 'x': let x = 2; break;",
"}",
),
concat!("let x = 1;", "{let x = 2}"),
);
}
#[test]
fn test_optimize_switch_with_labelled_break() {
test(
concat!(
"function f() {",
" label:",
" switch('x') {",
" case 'x': break label;",
" case 'y': throw f;",
" }",
"}",
),
"function f() { }",
);
test(
concat!(
"function f() {",
" label:",
" switch('x') {",
" case 'x': break label;",
" default: throw f;",
" }",
"}",
),
"function f() { }",
);
}
#[test]
fn test_optimize_switch_with_return() {
test(
concat!(
"function f() {",
" switch('x') {",
" case 'x': return 1;",
" case 'y': return 2;",
" }",
"}",
),
"function f() { return 1; }",
);
test(
concat!(
"function f() {",
" let x = 1;",
" switch('x') {",
" case 'x': { let x = 2; } return 3;",
" case 'y': return 4;",
" }",
"}",
),
concat!(
"function f() {",
" let x = 1;",
" { let x = 2; } return 3; ",
"}",
),
);
}
#[test]
fn test_optimize_switch_with_throw() {
test(
concat!(
"function f() {",
" switch('x') {",
" case 'x': throw f;",
" case 'y': throw f;",
" }",
"}",
),
"function f() { throw f; }",
);
}
#[test]
fn test_optimize_switch_with_continue() {
test(
concat!(
"function f() {",
" for (;;) {",
" switch('x') {",
" case 'x': continue;",
" case 'y': continue;",
" }",
" }",
"}",
),
"function f() { for (;;) continue; }",
);
}
#[test]
#[ignore]
fn test_optimize_switch_with_default_case_with_fallthru() {
test(
concat!(
"function f() {",
" switch(a) {",
" case 'x':",
" case foo():",
" default: return 3",
" }",
"}",
),
"foo()",
);
}
// GitHub issue #1722: https://github.com/google/closure-compiler/issues/1722
#[test]
fn test_optimize_switch_with_default_case() {
test(
concat!(
"function f() {",
" switch('x') {",
" case 'x': return 1;",
" case 'y': return 2;",
" default: return 3",
" }",
"}",
),
"function f() { return 1; }",
);
test(
concat!(
"switch ('hasDefaultCase') {",
" case 'foo':",
" foo();",
" break;",
" default:",
" bar();",
" break;",
"}",
),
"bar();",
);
test_same("switch (x) { default: if (a) break; bar(); }");
// Potentially foldable
test_same(concat!(
"switch (x) {",
" case x:",
" foo();",
" break;",
" default:",
" if (a) break;",
" bar();",
"}",
));
test(
concat!(
"switch ('hasDefaultCase') {",
" case 'foo':",
" foo();",
" break;",
" default:",
" if (true) { break; }",
" bar();",
"}",
),
"",
);
test(
concat!(
"switch ('hasDefaultCase') {",
" case 'foo':",
" foo();",
" break;",
" default:",
" if (a) { break; }",
" bar();",
"}",
),
"switch ('hasDefaultCase') { default: if (a) break; bar(); }",
);
test(
concat!(
"l: switch ('hasDefaultCase') {",
" case 'foo':",
" foo();",
" break;",
" default:",
" if (a) { break l; }",
" bar();",
" break;",
"}",
),
"l:{ if (a) break l; bar(); }",
);
test(
concat!(
"switch ('hasDefaultCase') {",
" case 'foo':",
" bar();",
" break;",
" default:",
" foo();",
" break;",
"}",
),
"foo();",
);
test("switch (a()) { default: bar(); break;}", "a(); bar();");
test("switch (a()) { default: break; bar();}", "a();");
test(
concat!(
"loop: ",
"for (;;) {",
" switch (a()) {",
" default:",
" bar();",
" break loop;",
" }",
"}",
),
"loop: for (;;) { a(); bar(); break loop; }",
);
}
#[test]
fn test_remove_number() {
test("3", "");
}
#[test]
fn test_remove_var_get1() {
test("a", "a");
}
#[test]
fn test_remove_var_get2() {
test("var a = 1;a", "var a = 1; a");
}
#[test]
#[ignore]
fn test_remove_namespace_get1() {
test("var a = {};a.b", "var a = {}");
}
#[test]
#[ignore]
fn test_remove_namespace_get2() {
test("var a = {};a.b=1;a.b", "var a = {};a.b=1");
}
#[test]
#[ignore]
fn test_remove_prototype_get1() {
test("var a = {};a.prototype.b", "var a = {}");
}
#[test]
#[ignore]
fn test_remove_prototype_get2() {
test(
"var a = {};a.prototype.b = 1;a.prototype.b",
"var a = {};a.prototype.b = 1",
);
}
#[test]
fn test_remove_add1() {
test("1 + 2", "");
}
#[test]
fn test_no_remove_var1() {
test_same("var a = 1");
}
#[test]
fn test_no_remove_var2() {
test_same("var a = 1, b = 2");
}
#[test]
fn test_no_remove_assign1() {
test_same("a = 1");
}
#[test]
fn test_no_remove_assign2() {
test_same("a = b = 1");
}
#[test]
fn test_no_remove_assign3() {
test("1 + (a = 2)", "a = 2");
}
#[test]
fn test_no_remove_assign4() {
test_same("x.a = 1");
}
#[test]
fn test_no_remove_assign5() {
test_same("x.a = x.b = 1");
}
#[test]
fn test_no_remove_assign6() {
test("1 + (x.a = 2)", "x.a = 2");
}
#[test]
fn test_no_remove_call1() {
test_same("a()");
}
#[test]
fn test_no_remove_call2() {
test("a()+b()", "a(),b()");
}
#[test]
fn test_no_remove_call3() {
test_same("a() && b()");
}
#[test]
fn test_no_remove_call4() {
test_same("a() || b()");
}
#[test]
fn test_no_remove_call5() {
test("a() || 1", "a()");
}
#[test]
fn test_no_remove_call6() {
test("1 || a()", "");
}
#[test]
fn test_no_remove_throw1() {
test_same("function f(){throw a()}");
}
#[test]
fn test_no_remove_throw2() {
test_same("function f(){throw a}");
}
#[test]
fn test_no_remove_throw3() {
test_same("function f(){throw 10}");
}
#[test]
fn test_remove_in_control_structure1() {
test("if(x()) 1", "x()");
}
#[test]
fn test_remove_in_control_structure3() {
test("for(1;2;3) 4", "for(;;);");
}
#[test]
fn test_hook1() {
test("1 ? 2 : 3", "");
}
#[test]
fn test_hook2() {
test("x ? a() : 3", "x && a()");
}
#[test]
fn test_hook3() {
test("x ? 2 : a()", "x || a()");
}
#[test]
fn test_hook4() {
test_same("x ? a() : b()");
}
#[test]
fn test_hook5() {
test("a() ? 1 : 2", "a()");
}
#[test]
fn test_hook6() {
test("a() ? b() : 2", "a() && b()");
}
// TODO(johnlenz): Consider adding a post optimization pass to
// convert OR into HOOK to save parentheses when the operator
// precedents would require them.
#[test]
fn test_hook7() {
test("a() ? 1 : b()", "a() || b()");
}
#[test]
fn test_hook8() {
test_same("a() ? b() : c()");
}
#[test]
fn test_hook9() {
test("true ? a() : (function f() {})()", "a()");
test(
"false ? a() : (function f() {alert(x)})()",
"(function f() {alert(x)})()",
);
}
#[test]
fn test_hook10() {
test("((function () {}), true) ? a() : b()", "a()");
test(
"((function () {alert(x)})(), true) ? a() : b()",
"(function(){alert(x)})(),a()",
);
}
#[test]
fn test_short_circuit1() {
test("1 && a()", "a()");
}
#[test]
fn test_short_circuit2() {
test("1 && a() && 2", "a()");
}
#[test]
fn test_short_circuit3() {
test("a() && 1 && 2", "a()");
}
#[test]
fn test_short_circuit4() {
test_same("a() && 1 && b()");
}
#[test]
fn test_complex1() {
test("1 && a() + b() + c()", "a(), b(), c()");
}
#[test]
fn test_complex2() {
test("1 && (a() ? b() : 1)", "a() && b()");
}
#[test]
fn test_complex3() {
test("1 && (a() ? b() : 1 + c())", "a() ? b() : c()");
}
#[test]
fn test_complex4() {
test("1 && (a() ? 1 : 1 + c())", "a() || c()");
}
#[test]
fn test_complex5() {
// can't simplify LHS of short circuit statements with side effects
test_same("(a() ? 1 : 1 + c()) && foo()");
}
#[test]
fn test_no_remove_function_declaration1() {
test_same("function foo(){}");
}
#[test]
fn test_no_remove_function_declaration2() {
test_same("var foo = function (){}");
}
#[test]
fn test_no_simplify_function_args1() {
test("f(1 + 2, 3 + g())", "f(3, 3 + g())");
}
#[test]
fn test_no_simplify_function_args2() {
test("1 && f(1 + 2, 3 + g())", "f(3, 3 + g())");
}
#[test]
fn test_no_simplify_function_args3() {
test("1 && foo(a() ? b() : 1 + c())", "foo(a() ? b() : 1 + c())");
}
#[test]
fn test_no_remove_inherits1() {
test_same("var a = {}; this.b = {}; var goog = {}; goog.inherits(b, a)");
}
#[test]
fn test_no_remove_inherits2() {
test(
"var a = {}; this.b = {}; var goog = {}; goog.inherits(b, a) + 1",
"var a = {}; this.b = {}; var goog = {}; goog.inherits(b, a)",
);
}
#[test]
fn test_no_remove_inherits3() {
test_same("this.a = {}; var b = {}; b.inherits(a);");
}
#[test]
fn test_no_remove_inherits4() {
test(
"this.a = {}; var b = {}; b.inherits(a) + 1;",
"this.a = {}; var b = {}; b.inherits(a)",
);
}
#[test]
fn test_remove_from_label1() {
test("LBL: void 0", "");
}
#[test]
fn test_remove_from_label2() {
test("LBL: foo() + 1 + bar()", "LBL: foo(),bar()");
}
#[test]
fn test_call() {
test_same("foo(0)");
// We use a function with no side-effects, otherwise the entire invocation would
// be preserved.
test("Math.sin(0);", "");
test("1 + Math.sin(0);", "");
}
#[test]
fn test_call_containing_spread() {
// We use a function with no side-effects, otherwise the entire invocation would
// be preserved.
test("Math.sin(...c)", "[...c]");
test("Math.sin(4, ...c, a)", "[...c, a]");
test("Math.sin(foo(), ...c, bar())", "[foo(), ...c, bar()]");
test("Math.sin(...a, b, ...c)", "[...a, b, ...c]");
test("Math.sin(...b, ...c)", "[...b, ...c]");
}
#[test]
fn test_new() {
test_same("new foo(0)");
// We use a function with no side-effects, otherwise the entire invocation would
// be preserved.
test("new Date;", "");
test("1 + new Date;", "");
}
#[test]
fn test_new_containing_spread_1() {
// We use a function with no side-effects, otherwise the entire invocation would
// be preserved.
test("new Date(...c)", "[...c]");
test("new Date(4, ...c, a)", "[...c, a]");
test("new Date(...a, b, ...c)", "[...a, b, ...c]");
test("new Date(...b, ...c)", "[...b, ...c]");
}
#[test]
#[ignore]
fn test_new_containing_spread_2() {
// We use a function with no side-effects, otherwise the entire invocation would
// be preserved.
test("new Date(foo(), ...c, bar())", "(foo(), [...c], bar())");
}
#[test]
fn test_tagged_template_lit_simple_template() {
test_same("foo`Simple`");
// We use a function with no side-effects, otherwise the entire invocation would
// be preserved.
test("Math.sin`Simple`", "");
test("1 + Math.sin`Simple`", "");
}
#[test]
fn test_tagged_template_lit_substituting_template() {
test_same("foo`Complex ${butSafe}`");
// We use a function with no side-effects, otherwise the entire invocation would
// be preserved.
test("Math.sin`Complex ${butSafe}`", "");
test("Math.sin`Complex ${andDangerous()}`", "andDangerous()");
}
#[test]
fn test_fold_assign() {
test("x=x", "x");
test_same("x=xy");
test_same("x=x + 1");
test_same("x.a=x.a");
test("var y=(x=x)", "var y=x");
test("y=1 + (x=x)", "y=1 + x");
}
#[test]
fn test_try_catch_finally() {
test_same("try {foo()} catch (e) {bar()}");
test_same("try { try {foo()} catch (e) {bar()}} catch (x) {bar()}");
test("try {var x = 1} finally {}", "var x = 1;");
test_same("try {var x = 1} finally {x()}");
test(
"function f() { return; try{var x = 1}finally{} }",
"function f() { var x; return; }",
);
test("try {} finally {x()}", "x()");
test("try {} catch (e) { bar()} finally {x()}", "x()");
test("try {} catch (e) { bar()}", "");
test(
"try {} catch (e) { var a = 0; } finally {x()}",
"var a; x()",
);
test("try {} catch (e) {}", "");
test("try {} finally {}", "");
test("try {} catch (e) {} finally {}", "");
}
#[test]
fn test_object_literal() {
test("({})", "");
test("({a:1})", "");
test("({a:foo()})", "foo()");
test("({'a':foo()})", "foo()");
test("({}).foo", "({}).foo");
// Object-spread may trigger getters.
test_same("({...a})");
test_same("({...foo()})");
}
#[test]
fn test_array_literal() {
test("([])", "");
test("([1])", "");
test("([a])", "");
test("([foo()])", "foo()");
}
#[test]
fn test_array_literal_containing_spread() {
test("([...c])", "[...c]");
test("([4, ...c, a])", "[...c, a]");
test("([foo(), ...c, bar()])", "[foo(), ...c, bar()]");
test("([...a, b, ...c])", "[...a, b, ...c]");
test("([...b, ...c])", "[...b, ...c]");
}
#[test]
fn test_await() {
test_same("async function f() { await something(); }");
test_same("async function f() { await some.thing(); }");
}
#[test]
fn test_empty_pattern_in_declaration_removed_1() {
test("var [] = [];", "");
test("let [] = [];", "");
test("const [] = [];", "");
test("var {} = [];", "");
}
#[test]
#[ignore]
fn test_empty_pattern_in_declaration_removed_2() {
test("var [] = foo();", "foo()");
}
#[test]
fn test_empty_array_pattern_in_assign_removed() {
test("({} = {});", "");
test("({} = foo());", "foo()");
test("[] = [];", "");
test("[] = foo();", "foo()");
}
#[test]
fn test_empty_pattern_in_params_not_removed() {
test_same("function f([], a) {}");
test_same("function f({}, a) {}");
}
#[test]
fn test_empty_pattern_in_for_of_loop_not_removed() {
test_same("for (let [] of foo());");
test_same("for (const [] of foo());");
test_same("for ([] of foo());");
test_same("for ({} of foo());");
}
#[test]
#[ignore]
fn test_empty_slot_in_array_pattern_with_default_value_maybe_removed_1() {
test("[a,[] = 0] = [];", "[a] = [];");
}
#[test]
fn test_empty_slot_in_array_pattern_with_default_value_maybe_removed_2() {
test_same("[a,[] = foo()] = [];");
}
#[test]
fn test_empty_key_in_object_pattern_removed() {
test("const {f: {}} = {};", "");
test("const {f: []} = {};", "");
test("const {f: {}, g} = {};", "const {g} = {};");
test("const {f: [], g} = {};", "const {g} = {};");
test_same("const {[foo()]: {}} = {};");
}
#[test]
fn test_empty_key_in_object_pattern_not_removed_with_object_rest() {
test_same("const {f: {}, ...g} = foo()");
test_same("const {f: [], ...g} = foo()");
}
#[test]
fn test_undefined_default_parameter_removed() {
test(
"function f(x=undefined,y) { }", //
"function f(x,y) { }",
);
test(
"function f(x,y=undefined,z) { }", //
"function f(x,y ,z) { }",
);
test(
"function f(x=undefined,y=undefined,z=undefined) { }", //
"function f(x, y, z) { }",
);
}
#[test]
fn test_pure_void_default_parameter_removed_1() {
test(
"function f(x = void 0) { }", //
"function f(x ) { }",
);
test(
"function f(x = void \"XD\") { }", //
"function f(x ) { }",
);
}
#[test]
#[ignore]
fn test_pure_void_default_parameter_removed_2() {
test(
"function f(x = void f()) { }", //
"function f(x) { }",
);
}
#[test]
fn test_no_default_parameter_not_removed() {
test_same("function f(x,y) { }");
test_same("function f(x) { }");
test_same("function f() { }");
}
#[test]
fn test_effectful_default_parameter_not_removed() {
test_same("function f(x = void console.log(1)) { }");
test_same("function f(x = void f()) { alert(x); }");
}
#[test]
fn test_destructuring_undefined_default_parameter() {
test(
"function f({a=undefined,b=1,c}) { }", //
"function f({a ,b=1,c}) { }",
);
test(
"function f({a={},b=0}=undefined) { }", //
"function f({a={},b=0}) { }",
);
test(
"function f({a=undefined,b=0}) { }", //
"function f({a,b=0}) { }",
);
test(
" function f({a: {b = undefined}}) { }", //
" function f({a: {b}}) { }",
);
test_same("function f({a,b}) { }");
test_same("function f({a=0, b=1}) { }");
test_same("function f({a=0,b=0}={}) { }");
test_same("function f({a={},b=0}={}) { }");
}
#[test]
fn test_undefined_default_object_patterns() {
test(
"const {a = undefined} = obj;", //
"const {a} = obj;",
);
test(
"const {a = void 0} = obj;", //
"const {a} = obj;",
);
}
#[test]
fn test_do_not_remove_getter_only_access() {
test_same(concat!(
"var a = {", //
" get property() {}",
"};",
"a.property;",
));
test_same(concat!(
"var a = {};", //
"Object.defineProperty(a, 'property', {",
" get() {}",
"});",
"a.property;",
));
}
#[test]
fn test_do_not_remove_nested_getter_only_access() {
test_same(concat!(
"var a = {", //
" b: { get property() {} }",
"};",
"a.b.property;",
));
}
#[test]
#[ignore]
fn test_remove_after_nested_getter_only_access() {
test(
concat!(
"var a = {", //
" b: { get property() {} }",
"};",
"a.b.property.d.e;",
),
concat!(
"var a = {", //
" b: { get property() {} }",
"};",
"a.b.property;",
),
);
}
#[test]
fn test_retain_setter_only_access() {
test_same(concat!(
"var a = {", //
" set property(v) {}",
"};",
"a.property;",
));
}
#[test]
fn test_do_not_remove_getter_setter_access() {
test_same(concat!(
"var a = {", //
" get property() {},",
" set property(x) {}",
"};",
"a.property;",
));
}
#[test]
fn test_do_not_remove_set_setter_to_getter() {
test_same(concat!(
"var a = {", //
" get property() {},",
" set property(x) {}",
"};",
"a.property = a.property;",
));
}
#[test]
fn test_do_not_remove_access_if_other_property_is_getter() {
test_same(concat!(
"var a = {", //
" get property() {}",
"};",
"var b = {",
" property: 0,",
"};",
// This pass should be conservative and not remove this since it sees a getter for
// "property"
"b.property;",
));
test_same(concat!(
"var a = {};", //
"Object.defineProperty(a, 'property', {",
" get() {}",
"});",
"var b = {",
" property: 0,",
"};",
"b.property;",
));
}
#[test]
fn test_function_call_references_getter_is_not_removed() {
test_same(concat!(
"var a = {", //
" get property() {}",
"};",
"function foo() { a.property; }",
"foo();",
));
}
#[test]
fn test_function_call_references_setter_is_not_removed() {
test_same(concat!(
"var a = {", //
" set property(v) {}",
"};",
"function foo() { a.property = 0; }",
"foo();",
));
}
#[test]
fn custom_loop_1() {
test(
"let b = 2;
let a = 1;
if (2) {
a = 2;
}
let c;
if (a) {
c = 3;
}",
"let b = 2;
let a = 1;
a = 2;
let c;
if (a) c = 3;",
);
}
#[test]
fn custom_loop_2() {
test(
"let b = 2;
let a = 1;
if (2) {
a = 2;
}
let c;
if (a) {
c = 3;
}",
"let b = 2;
let a = 1;
a = 2;
let c;
if (a) c = 3;",
);
}
#[test]
fn custom_loop_3() {
test(
"let c;
if (2) c = 3;
console.log(c);",
"let c;
c = 3;
console.log(c);",
);
}
#[test]
fn nested_block_stmt() {
test(
"if (Date.now() < 0) {
for(let i = 0; i < 10; i++){
if (Date.now() < 0) {
console.log(1);
}
}
} else {
console.log(2);
}",
"if (Date.now() < 0) {
for(let i = 0; i < 10; i++)if (Date.now() < 0) console.log(1);
} else console.log(2);",
);
}
#[test]
fn return_function_hoisting() {
test(
"function test() {
return foo();
function foo() {
return 2;
}
console.log('hi');
}",
"function test() {
return foo();
function foo() {
return 2;
}
}",
);
}
#[test]
fn issue_1825() {
test(
"
function p(){
throw new Error('Something');
}
while ((p(), 1)) {
console.log('Hello world');
}
",
"
function p() {
throw new Error('Something');
}
while(p(), 1)console.log('Hello world');
",
);
}
#[test]
fn issue_1851_1() {
test("x ?? (x = 'abc');", "x ?? (x = 'abc');");
}
#[test]
fn issue_6732_1() {
test(
"
if (false) {
foo(function () {
var module = {};
return module;
});
}
",
"",
);
}
#[test]
fn issue_6732_2() {
test(
"
if (false) {
function foo() {
var module = {};
return module;
};
}
",
"var foo;",
);
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_optimization/src/simplify/const_propagation.rs | Rust | #![allow(clippy::borrowed_box)]
use rustc_hash::FxHashMap;
use swc_common::util::take::Take;
use swc_ecma_ast::*;
use swc_ecma_visit::{noop_visit_mut_type, visit_mut_pass, VisitMut, VisitMutWith};
/// This pass is kind of inliner, but it's far faster.
pub fn constant_propagation() -> impl 'static + Pass + VisitMut {
visit_mut_pass(ConstPropagation::default())
}
#[derive(Default)]
struct ConstPropagation<'a> {
scope: Scope<'a>,
}
#[derive(Default)]
struct Scope<'a> {
parent: Option<&'a Scope<'a>>,
/// Stores only inlinable constant variables.
vars: FxHashMap<Id, Box<Expr>>,
}
impl<'a> Scope<'a> {
fn new(parent: &'a Scope<'a>) -> Self {
Self {
parent: Some(parent),
vars: Default::default(),
}
}
fn find_var(&self, id: &Id) -> Option<&Box<Expr>> {
if let Some(v) = self.vars.get(id) {
return Some(v);
}
self.parent.and_then(|parent| parent.find_var(id))
}
}
impl VisitMut for ConstPropagation<'_> {
noop_visit_mut_type!(fail);
/// No-op
fn visit_mut_assign_expr(&mut self, _: &mut AssignExpr) {}
fn visit_mut_export_named_specifier(&mut self, n: &mut ExportNamedSpecifier) {
let id = match &n.orig {
ModuleExportName::Ident(ident) => ident.to_id(),
ModuleExportName::Str(..) => return,
};
if let Some(expr) = self.scope.find_var(&id) {
if let Expr::Ident(v) = &**expr {
let orig = n.orig.clone();
n.orig = ModuleExportName::Ident(v.clone());
if n.exported.is_none() {
n.exported = Some(orig);
}
}
}
match &n.exported {
Some(ModuleExportName::Ident(exported)) => match &n.orig {
ModuleExportName::Ident(orig) => {
if exported.sym == orig.sym && exported.ctxt == orig.ctxt {
n.exported = None;
}
}
ModuleExportName::Str(..) => {}
},
Some(ModuleExportName::Str(..)) => {}
None => {}
}
}
fn visit_mut_expr(&mut self, e: &mut Expr) {
if let Expr::Ident(i) = e {
if let Some(expr) = self.scope.find_var(&i.to_id()) {
*e = *expr.clone();
return;
}
}
e.visit_mut_children_with(self);
}
/// Although span hygiene is magic, bundler creates invalid code in aspect
/// of span hygiene. (The bundled code can have two variables with
/// identical name with each other, with respect to span hygiene.)
///
/// We avoid bugs caused by the bundler's wrong behavior by
/// scoping variables.
fn visit_mut_function(&mut self, n: &mut Function) {
let scope = Scope::new(&self.scope);
let mut v = ConstPropagation { scope };
n.visit_mut_children_with(&mut v);
}
fn visit_mut_prop(&mut self, p: &mut Prop) {
p.visit_mut_children_with(self);
if let Prop::Shorthand(i) = p {
if let Some(expr) = self.scope.find_var(&i.to_id()) {
*p = Prop::KeyValue(KeyValueProp {
key: PropName::Ident(i.take().into()),
value: expr.clone(),
});
}
}
}
fn visit_mut_var_decl(&mut self, var: &mut VarDecl) {
var.decls.visit_mut_with(self);
if let VarDeclKind::Const = var.kind {
for decl in &var.decls {
if let Pat::Ident(name) = &decl.name {
if let Some(init) = &decl.init {
match &**init {
Expr::Lit(Lit::Bool(..))
| Expr::Lit(Lit::Num(..))
| Expr::Lit(Lit::Null(..)) => {
self.scope.vars.insert(name.to_id(), init.clone());
}
Expr::Ident(init)
if name.span.is_dummy()
|| var.span.is_dummy()
|| init.span.is_dummy() =>
{
// This check is required to prevent breaking some codes.
if let Some(value) = self.scope.vars.get(&init.to_id()).cloned() {
self.scope.vars.insert(name.to_id(), value);
} else {
self.scope.vars.insert(name.to_id(), init.clone().into());
}
}
_ => {}
}
}
}
}
}
}
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_optimization/src/simplify/dce/mod.rs | Rust | use std::{borrow::Cow, sync::Arc};
use indexmap::IndexSet;
use petgraph::{algo::tarjan_scc, Direction::Incoming};
use rustc_hash::{FxBuildHasher, FxHashMap, FxHashSet};
use swc_atoms::{atom, Atom};
use swc_common::{
pass::{CompilerPass, Repeated},
util::take::Take,
Mark, SyntaxContext, DUMMY_SP,
};
use swc_ecma_ast::*;
use swc_ecma_transforms_base::{
helpers::{Helpers, HELPERS},
perf::{cpu_count, ParVisitMut, Parallel},
};
use swc_ecma_utils::{
collect_decls, find_pat_ids, ExprCtx, ExprExt, IsEmpty, ModuleItemLike, StmtLike, Value::Known,
};
use swc_ecma_visit::{
noop_visit_mut_type, noop_visit_type, visit_mut_pass, Visit, VisitMut, VisitMutWith, VisitWith,
};
use swc_fast_graph::digraph::FastDiGraphMap;
use tracing::{debug, span, Level};
use crate::debug_assert_valid;
/// Note: This becomes parallel if `concurrent` feature is enabled.
pub fn dce(
config: Config,
unresolved_mark: Mark,
) -> impl Pass + VisitMut + Repeated + CompilerPass {
visit_mut_pass(TreeShaker {
expr_ctx: ExprCtx {
unresolved_ctxt: SyntaxContext::empty().apply_mark(unresolved_mark),
is_unresolved_ref_safe: false,
in_strict: false,
remaining_depth: 2,
},
config,
changed: false,
pass: 0,
in_fn: false,
in_block_stmt: false,
var_decl_kind: None,
data: Default::default(),
bindings: Default::default(),
})
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Config {
/// If this [Mark] is applied to a function expression, it's treated as a
/// separate module.
///
/// **Note**: This is hack to make operation parallel while allowing invalid
/// module produced by the `swc_bundler`.
pub module_mark: Option<Mark>,
/// If true, top-level items will be removed if they are not used.
///
/// Defaults to `true`.
pub top_level: bool,
/// Declarations with a symbol in this set will be preserved.
pub top_retain: Vec<Atom>,
/// If false, imports with side effects will be removed.
pub preserve_imports_with_side_effects: bool,
}
impl Default for Config {
fn default() -> Self {
Self {
module_mark: Default::default(),
top_level: true,
top_retain: Default::default(),
preserve_imports_with_side_effects: true,
}
}
}
struct TreeShaker {
expr_ctx: ExprCtx,
config: Config,
changed: bool,
pass: u16,
in_fn: bool,
in_block_stmt: bool,
var_decl_kind: Option<VarDeclKind>,
data: Arc<Data>,
bindings: Arc<FxHashSet<Id>>,
}
impl CompilerPass for TreeShaker {
fn name(&self) -> Cow<'static, str> {
Cow::Borrowed("tree-shaker")
}
}
#[derive(Default)]
struct Data {
used_names: FxHashMap<Id, VarInfo>,
/// Variable usage graph
///
/// We use `u32` because [FastDiGraphMap] stores types as `(N, 1 bit)` so if
/// we use u32 it fits into the cache line of cpu.
graph: FastDiGraphMap<u32, VarInfo>,
/// Entrypoints.
entries: FxHashSet<u32>,
graph_ix: IndexSet<Id, FxBuildHasher>,
}
impl Data {
fn node(&mut self, id: &Id) -> u32 {
self.graph_ix.get_index_of(id).unwrap_or_else(|| {
let ix = self.graph_ix.len();
self.graph_ix.insert_full(id.clone());
ix
}) as _
}
/// Add an edge to dependency graph
fn add_dep_edge(&mut self, from: &Id, to: &Id, assign: bool) {
let from = self.node(from);
let to = self.node(to);
match self.graph.edge_weight_mut(from, to) {
Some(info) => {
if assign {
info.assign += 1;
} else {
info.usage += 1;
}
}
None => {
self.graph.add_edge(
from,
to,
VarInfo {
usage: u32::from(!assign),
assign: u32::from(assign),
},
);
}
};
}
/// Traverse the graph and subtract usages from `used_names`.
fn subtract_cycles(&mut self) {
let cycles = tarjan_scc(&self.graph);
'c: for cycle in cycles {
if cycle.len() == 1 {
continue;
}
// We have to exclude cycle from remove list if an outer node refences an item
// of cycle.
for &node in &cycle {
// It's referenced by an outer node.
if self.entries.contains(&node) {
continue 'c;
}
if self.graph.neighbors_directed(node, Incoming).any(|node| {
// Node in cycle does not matter
!cycle.contains(&node)
}) {
continue 'c;
}
}
for &i in &cycle {
for &j in &cycle {
if i == j {
continue;
}
let id = self.graph_ix.get_index(j as _);
let id = match id {
Some(id) => id,
None => continue,
};
if let Some(w) = self.graph.edge_weight(i, j) {
let e = self.used_names.entry(id.clone()).or_default();
e.usage -= w.usage;
e.assign -= w.assign;
}
}
}
}
}
}
#[derive(Debug, Default)]
struct VarInfo {
/// This does not include self-references in a function.
pub usage: u32,
/// This does not include self-references in a function.
pub assign: u32,
}
struct Analyzer<'a> {
#[allow(dead_code)]
config: &'a Config,
in_var_decl: bool,
scope: Scope<'a>,
data: &'a mut Data,
cur_class_id: Option<Id>,
cur_fn_id: Option<Id>,
}
#[derive(Debug, Default)]
struct Scope<'a> {
parent: Option<&'a Scope<'a>>,
kind: ScopeKind,
bindings_affected_by_eval: FxHashSet<Id>,
found_direct_eval: bool,
found_arguemnts: bool,
bindings_affected_by_arguements: Vec<Id>,
/// Used to construct a graph.
///
/// This includes all bindings to current node.
ast_path: Vec<Id>,
}
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
enum ScopeKind {
Fn,
ArrowFn,
}
impl Default for ScopeKind {
fn default() -> Self {
Self::Fn
}
}
impl Analyzer<'_> {
fn with_ast_path<F>(&mut self, ids: Vec<Id>, op: F)
where
F: for<'aa> FnOnce(&mut Analyzer<'aa>),
{
let prev_len = self.scope.ast_path.len();
self.scope.ast_path.extend(ids);
op(self);
self.scope.ast_path.truncate(prev_len);
}
fn with_scope<F>(&mut self, kind: ScopeKind, op: F)
where
F: for<'aa> FnOnce(&mut Analyzer<'aa>),
{
let child_scope = {
let child = Scope {
parent: Some(&self.scope),
..Default::default()
};
let mut v = Analyzer {
scope: child,
data: self.data,
cur_fn_id: self.cur_fn_id.clone(),
cur_class_id: self.cur_class_id.clone(),
..*self
};
op(&mut v);
Scope {
parent: None,
..v.scope
}
};
// If we found eval, mark all declarations in scope and upper as used
if child_scope.found_direct_eval {
for id in child_scope.bindings_affected_by_eval {
self.data.used_names.entry(id).or_default().usage += 1;
}
self.scope.found_direct_eval = true;
}
if child_scope.found_arguemnts {
// Parameters
for id in child_scope.bindings_affected_by_arguements {
self.data.used_names.entry(id).or_default().usage += 1;
}
if !matches!(kind, ScopeKind::Fn) {
self.scope.found_arguemnts = true;
}
}
}
/// Mark `id` as used
fn add(&mut self, id: Id, assign: bool) {
if id.0 == atom!("arguments") {
self.scope.found_arguemnts = true;
}
if let Some(f) = &self.cur_fn_id {
if id == *f {
return;
}
}
if let Some(f) = &self.cur_class_id {
if id == *f {
return;
}
}
if self.scope.is_ast_path_empty() {
// Add references from top level items into graph
let idx = self.data.node(&id);
self.data.entries.insert(idx);
} else {
let mut scope = Some(&self.scope);
while let Some(s) = scope {
for component in &s.ast_path {
self.data.add_dep_edge(component, &id, assign);
}
if s.kind == ScopeKind::Fn && !s.ast_path.is_empty() {
break;
}
scope = s.parent;
}
}
if assign {
self.data.used_names.entry(id).or_default().assign += 1;
} else {
self.data.used_names.entry(id).or_default().usage += 1;
}
}
}
impl Visit for Analyzer<'_> {
noop_visit_type!();
fn visit_callee(&mut self, n: &Callee) {
n.visit_children_with(self);
if let Callee::Expr(e) = n {
if e.is_ident_ref_to("eval") {
self.scope.found_direct_eval = true;
}
}
}
fn visit_assign_pat_prop(&mut self, n: &AssignPatProp) {
n.visit_children_with(self);
self.add(n.key.to_id(), true);
}
fn visit_class_decl(&mut self, n: &ClassDecl) {
self.with_ast_path(vec![n.ident.to_id()], |v| {
let old = v.cur_class_id.take();
v.cur_class_id = Some(n.ident.to_id());
n.visit_children_with(v);
v.cur_class_id = old;
if !n.class.decorators.is_empty() {
v.add(n.ident.to_id(), false);
}
})
}
fn visit_class_expr(&mut self, n: &ClassExpr) {
n.visit_children_with(self);
if !n.class.decorators.is_empty() {
if let Some(i) = &n.ident {
self.add(i.to_id(), false);
}
}
}
fn visit_export_named_specifier(&mut self, n: &ExportNamedSpecifier) {
if let ModuleExportName::Ident(orig) = &n.orig {
self.add(orig.to_id(), false);
}
}
fn visit_export_decl(&mut self, n: &ExportDecl) {
let name = match &n.decl {
Decl::Class(c) => vec![c.ident.to_id()],
Decl::Fn(f) => vec![f.ident.to_id()],
Decl::Var(v) => v
.decls
.iter()
.flat_map(|d| find_pat_ids(d).into_iter())
.collect(),
_ => Vec::new(),
};
for ident in name {
self.add(ident, false);
}
n.visit_children_with(self)
}
fn visit_expr(&mut self, e: &Expr) {
let old_in_var_decl = self.in_var_decl;
self.in_var_decl = false;
e.visit_children_with(self);
if let Expr::Ident(i) = e {
self.add(i.to_id(), false);
}
self.in_var_decl = old_in_var_decl;
}
fn visit_assign_expr(&mut self, n: &AssignExpr) {
match n.op {
op!("=") => {
if let Some(i) = n.left.as_ident() {
self.add(i.to_id(), true);
n.right.visit_with(self);
} else {
n.visit_children_with(self);
}
}
_ => {
if let Some(i) = n.left.as_ident() {
self.add(i.to_id(), false);
self.add(i.to_id(), true);
n.right.visit_with(self);
} else {
n.visit_children_with(self);
}
}
}
}
fn visit_jsx_element_name(&mut self, e: &JSXElementName) {
e.visit_children_with(self);
if let JSXElementName::Ident(i) = e {
self.add(i.to_id(), false);
}
}
fn visit_jsx_object(&mut self, e: &JSXObject) {
e.visit_children_with(self);
if let JSXObject::Ident(i) = e {
self.add(i.to_id(), false);
}
}
fn visit_arrow_expr(&mut self, n: &ArrowExpr) {
self.with_scope(ScopeKind::ArrowFn, |v| {
n.visit_children_with(v);
if v.scope.found_direct_eval {
v.scope.bindings_affected_by_eval = collect_decls(n);
}
})
}
fn visit_function(&mut self, n: &Function) {
self.with_scope(ScopeKind::Fn, |v| {
n.visit_children_with(v);
if v.scope.found_direct_eval {
v.scope.bindings_affected_by_eval = collect_decls(n);
}
if v.scope.found_arguemnts {
v.scope.bindings_affected_by_arguements = find_pat_ids(&n.params);
}
})
}
fn visit_fn_decl(&mut self, n: &FnDecl) {
self.with_ast_path(vec![n.ident.to_id()], |v| {
let old = v.cur_fn_id.take();
v.cur_fn_id = Some(n.ident.to_id());
n.visit_children_with(v);
v.cur_fn_id = old;
if !n.function.decorators.is_empty() {
v.add(n.ident.to_id(), false);
}
})
}
fn visit_fn_expr(&mut self, n: &FnExpr) {
n.visit_children_with(self);
if !n.function.decorators.is_empty() {
if let Some(i) = &n.ident {
self.add(i.to_id(), false);
}
}
}
fn visit_pat(&mut self, p: &Pat) {
p.visit_children_with(self);
if !self.in_var_decl {
if let Pat::Ident(i) = p {
self.add(i.to_id(), true);
}
}
}
fn visit_prop(&mut self, p: &Prop) {
p.visit_children_with(self);
if let Prop::Shorthand(i) = p {
self.add(i.to_id(), false);
}
}
fn visit_var_declarator(&mut self, n: &VarDeclarator) {
let old = self.in_var_decl;
self.in_var_decl = true;
n.name.visit_with(self);
self.in_var_decl = false;
n.init.visit_with(self);
self.in_var_decl = old;
}
}
impl Repeated for TreeShaker {
fn changed(&self) -> bool {
self.changed
}
fn reset(&mut self) {
self.pass += 1;
self.changed = false;
self.data = Default::default();
}
}
impl Parallel for TreeShaker {
fn create(&self) -> Self {
Self {
expr_ctx: self.expr_ctx,
data: self.data.clone(),
config: self.config.clone(),
bindings: self.bindings.clone(),
..*self
}
}
fn merge(&mut self, other: Self) {
self.changed |= other.changed;
}
}
impl TreeShaker {
fn visit_mut_stmt_likes<T>(&mut self, stmts: &mut Vec<T>)
where
T: StmtLike + ModuleItemLike + VisitMutWith<Self> + Send + Sync,
Vec<T>: VisitMutWith<Self>,
{
if let Some(Stmt::Expr(ExprStmt { expr, .. })) = stmts.first().and_then(|s| s.as_stmt()) {
if let Expr::Lit(Lit::Str(v)) = &**expr {
if &*v.value == "use asm" {
return;
}
}
}
self.visit_mut_par(cpu_count() * 8, stmts);
stmts.retain(|s| match s.as_stmt() {
Some(Stmt::Empty(..)) => false,
Some(Stmt::Block(s)) if s.is_empty() => {
debug!("Dropping an empty block statement");
false
}
_ => true,
});
}
fn can_drop_binding(&self, name: Id, is_var: bool) -> bool {
if !self.config.top_level {
if is_var {
if !self.in_fn {
return false;
}
} else if !self.in_block_stmt {
return false;
}
}
if self.config.top_retain.contains(&name.0) {
return false;
}
match self.data.used_names.get(&name) {
Some(v) => v.usage == 0 && v.assign == 0,
None => true,
}
}
fn can_drop_assignment_to(&self, name: Id, is_var: bool) -> bool {
if !self.config.top_level {
if is_var {
if !self.in_fn {
return false;
}
} else if !self.in_block_stmt {
return false;
}
// Abort if the variable is declared on top level scope.
let ix = self.data.graph_ix.get_index_of(&name);
if let Some(ix) = ix {
if self.data.entries.contains(&(ix as u32)) {
return false;
}
}
}
if self.config.top_retain.contains(&name.0) {
return false;
}
self.bindings.contains(&name)
&& self
.data
.used_names
.get(&name)
.map(|v| v.usage == 0)
.unwrap_or_default()
}
/// Drops RHS from `null && foo`
fn optimize_bin_expr(&mut self, n: &mut Expr) {
let Expr::Bin(b) = n else {
return;
};
if b.op == op!("&&") && b.left.as_pure_bool(self.expr_ctx) == Known(false) {
*n = *b.left.take();
self.changed = true;
return;
}
if b.op == op!("||") && b.left.as_pure_bool(self.expr_ctx) == Known(true) {
*n = *b.left.take();
self.changed = true;
}
}
}
impl VisitMut for TreeShaker {
noop_visit_mut_type!();
fn visit_mut_assign_expr(&mut self, n: &mut AssignExpr) {
n.visit_mut_children_with(self);
if let Some(id) = n.left.as_ident() {
// TODO: `var`
if self.can_drop_assignment_to(id.to_id(), false)
&& !n.right.may_have_side_effects(self.expr_ctx)
{
self.changed = true;
debug!("Dropping an assignment to `{}` because it's not used", id);
n.left.take();
}
}
}
fn visit_mut_block_stmt(&mut self, n: &mut BlockStmt) {
let old_in_block_stmt = self.in_block_stmt;
self.in_block_stmt = true;
n.visit_mut_children_with(self);
self.in_block_stmt = old_in_block_stmt;
}
fn visit_mut_class_members(&mut self, members: &mut Vec<ClassMember>) {
self.visit_mut_par(cpu_count() * 8, members);
}
fn visit_mut_decl(&mut self, n: &mut Decl) {
n.visit_mut_children_with(self);
match n {
Decl::Fn(f) => {
if self.can_drop_binding(f.ident.to_id(), true) {
debug!("Dropping function `{}` as it's not used", f.ident);
self.changed = true;
n.take();
}
}
Decl::Class(c) => {
if self.can_drop_binding(c.ident.to_id(), false)
&& c.class
.super_class
.as_deref()
.map_or(true, |e| !e.may_have_side_effects(self.expr_ctx))
&& c.class.body.iter().all(|m| match m {
ClassMember::Method(m) => !matches!(m.key, PropName::Computed(..)),
ClassMember::ClassProp(m) => {
!matches!(m.key, PropName::Computed(..))
&& !m
.value
.as_deref()
.map_or(false, |e| e.may_have_side_effects(self.expr_ctx))
}
ClassMember::AutoAccessor(m) => {
!matches!(m.key, Key::Public(PropName::Computed(..)))
&& !m
.value
.as_deref()
.map_or(false, |e| e.may_have_side_effects(self.expr_ctx))
}
ClassMember::PrivateProp(m) => !m
.value
.as_deref()
.map_or(false, |e| e.may_have_side_effects(self.expr_ctx)),
ClassMember::StaticBlock(_) => false,
ClassMember::TsIndexSignature(_)
| ClassMember::Empty(_)
| ClassMember::Constructor(_)
| ClassMember::PrivateMethod(_) => true,
})
{
debug!("Dropping class `{}` as it's not used", c.ident);
self.changed = true;
n.take();
}
}
_ => {}
}
}
fn visit_mut_export_decl(&mut self, n: &mut ExportDecl) {
match &mut n.decl {
Decl::Var(v) => {
for decl in v.decls.iter_mut() {
decl.init.visit_mut_with(self);
}
}
_ => {
// Bypass visit_mut_decl
n.decl.visit_mut_children_with(self);
}
}
}
/// Noop.
fn visit_mut_export_default_decl(&mut self, _: &mut ExportDefaultDecl) {}
fn visit_mut_expr(&mut self, n: &mut Expr) {
n.visit_mut_children_with(self);
self.optimize_bin_expr(n);
if let Expr::Call(CallExpr {
callee: Callee::Expr(callee),
args,
..
}) = n
{
//
if args.is_empty() {
match &mut **callee {
Expr::Fn(FnExpr {
ident: None,
function: f,
}) if matches!(
&**f,
Function {
is_async: false,
is_generator: false,
body: Some(..),
..
}
) =>
{
if f.params.is_empty() && f.body.as_ref().unwrap().stmts.len() == 1 {
if let Stmt::Return(ReturnStmt { arg: Some(arg), .. }) =
&mut f.body.as_mut().unwrap().stmts[0]
{
if let Expr::Object(ObjectLit { props, .. }) = &**arg {
if props.iter().all(|p| match p {
PropOrSpread::Spread(_) => false,
PropOrSpread::Prop(p) => match &**p {
Prop::Shorthand(_) => true,
Prop::KeyValue(p) => p.value.is_ident(),
_ => false,
},
}) {
self.changed = true;
debug!("Dropping a wrapped esm");
*n = *arg.take();
return;
}
}
}
}
}
_ => (),
}
}
}
if let Expr::Assign(a) = n {
if match &a.left {
AssignTarget::Simple(l) => l.is_invalid(),
AssignTarget::Pat(l) => l.is_invalid(),
} {
*n = *a.right.take();
}
}
if !n.is_invalid() {
debug_assert_valid(n);
}
}
fn visit_mut_expr_or_spreads(&mut self, n: &mut Vec<ExprOrSpread>) {
self.visit_mut_par(cpu_count() * 8, n);
}
fn visit_mut_exprs(&mut self, n: &mut Vec<Box<Expr>>) {
self.visit_mut_par(cpu_count() * 8, n);
}
fn visit_mut_for_head(&mut self, n: &mut ForHead) {
match n {
ForHead::VarDecl(..) | ForHead::UsingDecl(..) => {}
ForHead::Pat(v) => {
v.visit_mut_with(self);
}
}
}
fn visit_mut_function(&mut self, n: &mut Function) {
let old_in_fn = self.in_fn;
self.in_fn = true;
n.visit_mut_children_with(self);
self.in_fn = old_in_fn;
}
fn visit_mut_import_specifiers(&mut self, ss: &mut Vec<ImportSpecifier>) {
ss.retain(|s| {
let local = match s {
ImportSpecifier::Named(l) => &l.local,
ImportSpecifier::Default(l) => &l.local,
ImportSpecifier::Namespace(l) => &l.local,
};
if self.can_drop_binding(local.to_id(), false) {
debug!(
"Dropping import specifier `{}` because it's not used",
local
);
self.changed = true;
return false;
}
true
});
}
fn visit_mut_module(&mut self, m: &mut Module) {
debug_assert_valid(m);
let _tracing = span!(Level::ERROR, "tree-shaker", pass = self.pass).entered();
if self.bindings.is_empty() {
self.bindings = Arc::new(collect_decls(&*m))
}
let mut data = Default::default();
{
let mut analyzer = Analyzer {
config: &self.config,
in_var_decl: false,
scope: Default::default(),
data: &mut data,
cur_class_id: Default::default(),
cur_fn_id: Default::default(),
};
m.visit_with(&mut analyzer);
}
data.subtract_cycles();
self.data = Arc::new(data);
HELPERS.set(&Helpers::new(true), || {
m.visit_mut_children_with(self);
})
}
fn visit_mut_module_item(&mut self, n: &mut ModuleItem) {
match n {
ModuleItem::ModuleDecl(ModuleDecl::Import(i)) => {
let is_for_side_effect = i.specifiers.is_empty();
i.visit_mut_with(self);
if !self.config.preserve_imports_with_side_effects
&& !is_for_side_effect
&& i.specifiers.is_empty()
{
debug!("Dropping an import because it's not used");
self.changed = true;
*n = EmptyStmt { span: DUMMY_SP }.into();
}
}
_ => {
n.visit_mut_children_with(self);
}
}
debug_assert_valid(n);
}
fn visit_mut_module_items(&mut self, s: &mut Vec<ModuleItem>) {
self.visit_mut_stmt_likes(s);
}
fn visit_mut_opt_vec_expr_or_spreads(&mut self, n: &mut Vec<Option<ExprOrSpread>>) {
self.visit_mut_par(cpu_count() * 8, n);
}
fn visit_mut_prop_or_spreads(&mut self, n: &mut Vec<PropOrSpread>) {
self.visit_mut_par(cpu_count() * 8, n);
}
fn visit_mut_script(&mut self, m: &mut Script) {
let _tracing = span!(Level::ERROR, "tree-shaker", pass = self.pass).entered();
if self.bindings.is_empty() {
self.bindings = Arc::new(collect_decls(&*m))
}
let mut data = Default::default();
{
let mut analyzer = Analyzer {
config: &self.config,
in_var_decl: false,
scope: Default::default(),
data: &mut data,
cur_class_id: Default::default(),
cur_fn_id: Default::default(),
};
m.visit_with(&mut analyzer);
}
data.subtract_cycles();
self.data = Arc::new(data);
HELPERS.set(&Helpers::new(true), || {
m.visit_mut_children_with(self);
})
}
fn visit_mut_stmt(&mut self, s: &mut Stmt) {
s.visit_mut_children_with(self);
if let Stmt::Decl(Decl::Var(v)) = s {
if v.decls.is_empty() {
s.take();
return;
}
}
debug_assert_valid(s);
if let Stmt::Decl(Decl::Var(v)) = s {
let span = v.span;
let cnt = v.decls.len();
// If all name is droppable, do so.
if cnt != 0
&& v.decls.iter().all(|vd| match &vd.name {
Pat::Ident(i) => self.can_drop_binding(i.to_id(), v.kind == VarDeclKind::Var),
_ => false,
})
{
let exprs = v
.decls
.take()
.into_iter()
.filter_map(|v| v.init)
.collect::<Vec<_>>();
debug!(
count = cnt,
"Dropping names of variables as they are not used",
);
self.changed = true;
if exprs.is_empty() {
*s = EmptyStmt { span: DUMMY_SP }.into();
return;
} else {
*s = ExprStmt {
span,
expr: Expr::from_exprs(exprs),
}
.into();
}
}
}
if let Stmt::Decl(Decl::Var(v)) = s {
if v.decls.is_empty() {
*s = EmptyStmt { span: DUMMY_SP }.into();
}
}
debug_assert_valid(s);
}
fn visit_mut_stmts(&mut self, s: &mut Vec<Stmt>) {
self.visit_mut_stmt_likes(s);
}
fn visit_mut_unary_expr(&mut self, n: &mut UnaryExpr) {
if matches!(n.op, op!("delete")) {
return;
}
n.visit_mut_children_with(self);
}
#[cfg_attr(feature = "debug", tracing::instrument(skip_all))]
fn visit_mut_using_decl(&mut self, n: &mut UsingDecl) {
for decl in n.decls.iter_mut() {
decl.init.visit_mut_with(self);
}
}
fn visit_mut_var_decl(&mut self, n: &mut VarDecl) {
let old_var_decl_kind = self.var_decl_kind;
self.var_decl_kind = Some(n.kind);
n.visit_mut_children_with(self);
self.var_decl_kind = old_var_decl_kind;
}
fn visit_mut_var_decl_or_expr(&mut self, n: &mut VarDeclOrExpr) {
match n {
VarDeclOrExpr::VarDecl(..) => {}
VarDeclOrExpr::Expr(v) => {
v.visit_mut_with(self);
}
}
}
fn visit_mut_var_declarator(&mut self, v: &mut VarDeclarator) {
v.visit_mut_children_with(self);
if let Pat::Ident(i) = &v.name {
let can_drop = if let Some(init) = &v.init {
!init.may_have_side_effects(self.expr_ctx)
} else {
true
};
if can_drop
&& self.can_drop_binding(i.to_id(), self.var_decl_kind == Some(VarDeclKind::Var))
{
self.changed = true;
debug!("Dropping {} because it's not used", i);
v.name.take();
}
}
}
fn visit_mut_var_declarators(&mut self, n: &mut Vec<VarDeclarator>) {
self.visit_mut_par(cpu_count() * 8, n);
n.retain(|v| {
if v.name.is_invalid() {
return false;
}
true
});
}
fn visit_mut_with_stmt(&mut self, n: &mut WithStmt) {
n.obj.visit_mut_with(self);
}
}
impl Scope<'_> {
/// Returns true if it's not in a function or class.
fn is_ast_path_empty(&self) -> bool {
if !self.ast_path.is_empty() {
return false;
}
match &self.parent {
Some(p) => p.is_ast_path_empty(),
None => true,
}
}
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_optimization/src/simplify/expr/mod.rs | Rust | use std::{borrow::Cow, iter, iter::once};
use swc_atoms::Atom;
use swc_common::{
pass::{CompilerPass, Repeated},
util::take::Take,
Mark, Span, Spanned, SyntaxContext, DUMMY_SP,
};
use swc_ecma_ast::*;
use swc_ecma_transforms_base::{
ext::ExprRefExt,
perf::{cpu_count, Parallel, ParallelExt},
};
use swc_ecma_utils::{
is_literal, number::JsNumber, prop_name_eq, to_int32, BoolType, ExprCtx, ExprExt, NullType,
NumberType, ObjectType, StringType, SymbolType, UndefinedType, Value,
};
use swc_ecma_visit::{noop_visit_mut_type, visit_mut_pass, VisitMut, VisitMutWith};
use Value::{Known, Unknown};
use crate::debug::debug_assert_valid;
#[cfg(test)]
mod tests;
macro_rules! try_val {
($v:expr) => {{
match $v {
Value::Known(v) => v,
Value::Unknown => return Value::Unknown,
}
}};
}
/// All [bool] fields defaults to [false].
#[derive(Debug, Clone, Copy, Default, Hash)]
pub struct Config {}
/// Not intended for general use. Use [simplifier] instead.
///
/// Ported from `PeepholeFoldConstants` of google closure compiler.
pub fn expr_simplifier(
unresolved_mark: Mark,
config: Config,
) -> impl Repeated + Pass + CompilerPass + VisitMut + 'static {
visit_mut_pass(SimplifyExpr {
expr_ctx: ExprCtx {
unresolved_ctxt: SyntaxContext::empty().apply_mark(unresolved_mark),
is_unresolved_ref_safe: false,
in_strict: false,
remaining_depth: 4,
},
config,
changed: false,
is_arg_of_update: false,
is_modifying: false,
in_callee: false,
})
}
impl Parallel for SimplifyExpr {
fn create(&self) -> Self {
Self { ..*self }
}
fn merge(&mut self, other: Self) {
self.changed |= other.changed;
}
}
#[derive(Debug)]
struct SimplifyExpr {
expr_ctx: ExprCtx,
config: Config,
changed: bool,
is_arg_of_update: bool,
is_modifying: bool,
in_callee: bool,
}
impl CompilerPass for SimplifyExpr {
fn name(&self) -> Cow<'static, str> {
Cow::Borrowed("simplify-expr")
}
}
impl Repeated for SimplifyExpr {
fn changed(&self) -> bool {
self.changed
}
fn reset(&mut self) {
self.changed = false;
}
}
impl SimplifyExpr {
fn optimize_member_expr(&mut self, expr: &mut Expr) {
let MemberExpr { obj, prop, .. } = match expr {
Expr::Member(member) => member,
_ => return,
};
if self.is_modifying {
return;
}
#[derive(Clone, PartialEq)]
enum KnownOp {
/// [a, b].length
Len,
/// [a, b][0]
///
/// {0.5: "bar"}[0.5]
/// Note: callers need to check `v.fract() == 0.0` in some cases.
/// ie non-integer indexes for arrays result in `undefined`
/// but not for objects (because indexing an object
/// returns the value of the key, ie `0.5` will not
/// return `undefined` if a key `0.5` exists
/// and its value is not `undefined`).
Index(f64),
/// ({}).foo
IndexStr(Atom),
}
let op = match prop {
MemberProp::Ident(IdentName { sym, .. }) if &**sym == "length" && !obj.is_object() => {
KnownOp::Len
}
MemberProp::Ident(IdentName { sym, .. }) => {
if self.in_callee {
return;
}
KnownOp::IndexStr(sym.clone())
}
MemberProp::Computed(ComputedPropName { expr, .. }) => {
if self.in_callee {
return;
}
if let Expr::Lit(Lit::Num(Number { value, .. })) = &**expr {
// x[5]
KnownOp::Index(*value)
} else if let Known(s) = expr.as_pure_string(self.expr_ctx) {
if s == "length" && !obj.is_object() {
// Length of non-object type
KnownOp::Len
} else if let Ok(n) = s.parse::<f64>() {
// x['0'] is treated as x[0]
KnownOp::Index(n)
} else {
// x[''] or x[...] where ... is an expression like [], ie x[[]]
KnownOp::IndexStr(s.into())
}
} else {
return;
}
}
_ => return,
};
// Note: pristine_globals refers to the compress config option pristine_globals.
// Any potential cases where globals are not pristine are handled in compress,
// e.g. x[-1] is not changed as the object's prototype may be modified.
// For example, Array.prototype[-1] = "foo" will result in [][-1] returning
// "foo".
match &mut **obj {
Expr::Lit(Lit::Str(Str { value, span, .. })) => match op {
// 'foo'.length
//
// Prototype changes do not affect .length, so we don't need to worry
// about pristine_globals here.
KnownOp::Len => {
self.changed = true;
*expr = Lit::Num(Number {
value: value.chars().map(|c| c.len_utf16()).sum::<usize>() as _,
span: *span,
raw: None,
})
.into();
}
// 'foo'[1]
KnownOp::Index(idx) => {
if idx.fract() != 0.0 || idx < 0.0 || idx as usize >= value.len() {
// Prototype changes affect indexing if the index is out of bounds, so we
// don't replace out-of-bound indexes.
return;
}
let Some(value) = nth_char(value, idx as _) else {
return;
};
self.changed = true;
*expr = Lit::Str(Str {
raw: None,
value: value.into(),
span: *span,
})
.into()
}
// 'foo'['']
//
// Handled in compress
KnownOp::IndexStr(..) => {}
},
// [1, 2, 3].length
//
// [1, 2, 3][0]
Expr::Array(ArrayLit { elems, span }) => {
// do nothing if spread exists
let has_spread = elems.iter().any(|elem| {
elem.as_ref()
.map(|elem| elem.spread.is_some())
.unwrap_or(false)
});
if has_spread {
return;
}
match op {
KnownOp::Len => {
// do nothing if replacement will have side effects
let may_have_side_effects = elems
.iter()
.filter_map(|e| e.as_ref())
.any(|e| e.expr.may_have_side_effects(self.expr_ctx));
if may_have_side_effects {
return;
}
// Prototype changes do not affect .length
self.changed = true;
*expr = Lit::Num(Number {
value: elems.len() as _,
span: *span,
raw: None,
})
.into();
}
KnownOp::Index(idx) => {
// If the fraction part is non-zero, or if the index is out of bounds,
// then we handle this in compress as Array's prototype may be modified.
if idx.fract() != 0.0 || idx < 0.0 || idx as usize >= elems.len() {
return;
}
// Don't change if after has side effects.
let after_has_side_effect =
elems
.iter()
.skip((idx as usize + 1) as _)
.any(|elem| match elem {
Some(elem) => elem.expr.may_have_side_effects(self.expr_ctx),
None => false,
});
if after_has_side_effect {
return;
}
self.changed = true;
// elements before target element
let before: Vec<Option<ExprOrSpread>> =
elems.drain(..(idx as usize)).collect();
let mut iter = elems.take().into_iter();
// element at idx
let e = iter.next().flatten();
// elements after target element
let after: Vec<Option<ExprOrSpread>> = iter.collect();
// element value
let v = match e {
None => Expr::undefined(*span),
Some(e) => e.expr,
};
// Replacement expressions.
let mut exprs = Vec::new();
// Add before side effects.
for elem in before.into_iter().flatten() {
self.expr_ctx
.extract_side_effects_to(&mut exprs, *elem.expr);
}
// Element value.
let val = v;
// Add after side effects.
for elem in after.into_iter().flatten() {
self.expr_ctx
.extract_side_effects_to(&mut exprs, *elem.expr);
}
// Note: we always replace with a SeqExpr so that
// `this` remains undefined in strict mode.
if exprs.is_empty() {
// No side effects exist, replace with:
// (0, val)
*expr = SeqExpr {
span: val.span(),
exprs: vec![0.into(), val],
}
.into();
return;
}
// Add value and replace with SeqExpr
exprs.push(val);
*expr = SeqExpr { span: *span, exprs }.into();
}
// Handled in compress
KnownOp::IndexStr(..) => {}
}
}
// { foo: true }['foo']
//
// { 0.5: true }[0.5]
Expr::Object(ObjectLit { props, span }) => {
// get key
let key = match op {
KnownOp::Index(i) => Atom::from(i.to_string()),
KnownOp::IndexStr(key) if key != *"yield" && is_literal(props) => key,
_ => return,
};
// Get `key`s value. Non-existent keys are handled in compress.
// This also checks if spread exists.
let Some(v) = get_key_value(&key, props) else {
return;
};
self.changed = true;
*expr = *self.expr_ctx.preserve_effects(
*span,
v,
once(
ObjectLit {
props: props.take(),
span: *span,
}
.into(),
),
);
}
_ => {}
}
}
fn optimize_bin_expr(&mut self, expr: &mut Expr) {
let BinExpr {
left,
op,
right,
span,
} = match expr {
Expr::Bin(bin) => bin,
_ => return,
};
macro_rules! try_replace {
($v:expr) => {{
match $v {
Known(v) => {
// TODO: Optimize
self.changed = true;
*expr = *make_bool_expr(self.expr_ctx, *span, v, {
iter::once(left.take()).chain(iter::once(right.take()))
});
return;
}
_ => {}
}
}};
(number, $v:expr) => {{
match $v {
Known(v) => {
self.changed = true;
let value_expr = if !v.is_nan() {
Expr::Lit(Lit::Num(Number {
value: v,
span: *span,
raw: None,
}))
} else {
Expr::Ident(Ident::new(
"NaN".into(),
*span,
self.expr_ctx.unresolved_ctxt,
))
};
*expr = *self.expr_ctx.preserve_effects(*span, value_expr.into(), {
iter::once(left.take()).chain(iter::once(right.take()))
});
return;
}
_ => {}
}
}};
}
match op {
op!(bin, "+") => {
// It's string concatenation if either left or right is string.
if left.is_str() || left.is_array_lit() || right.is_str() || right.is_array_lit() {
if let (Known(l), Known(r)) = (
left.as_pure_string(self.expr_ctx),
right.as_pure_string(self.expr_ctx),
) {
let mut l = l.into_owned();
l.push_str(&r);
self.changed = true;
*expr = Lit::Str(Str {
raw: None,
value: l.into(),
span: *span,
})
.into();
return;
}
}
match expr.get_type(self.expr_ctx) {
// String concatenation
Known(StringType) => match expr {
Expr::Bin(BinExpr {
left, right, span, ..
}) => {
if !left.may_have_side_effects(self.expr_ctx)
&& !right.may_have_side_effects(self.expr_ctx)
{
if let (Known(l), Known(r)) = (
left.as_pure_string(self.expr_ctx),
right.as_pure_string(self.expr_ctx),
) {
self.changed = true;
let value = format!("{}{}", l, r);
*expr = Lit::Str(Str {
raw: None,
value: value.into(),
span: *span,
})
.into();
}
}
}
_ => unreachable!(),
},
// Numerical calculation
Known(BoolType) | Known(NullType) | Known(NumberType)
| Known(UndefinedType) => {
match expr {
Expr::Bin(BinExpr {
left, right, span, ..
}) => {
if let Known(v) =
self.perform_arithmetic_op(op!(bin, "+"), left, right)
{
self.changed = true;
let span = *span;
let value_expr = if !v.is_nan() {
Lit::Num(Number {
value: v,
span,
raw: None,
})
.into()
} else {
Ident::new(
"NaN".into(),
span,
self.expr_ctx.unresolved_ctxt,
)
.into()
};
*expr = *self.expr_ctx.preserve_effects(
span,
value_expr,
iter::once(left.take()).chain(iter::once(right.take())),
);
}
}
_ => unreachable!(),
};
}
_ => {}
}
//TODO: try string concat
}
op!("&&") | op!("||") => {
if let (_, Known(val)) = left.cast_to_bool(self.expr_ctx) {
let node = if *op == op!("&&") {
if val {
// 1 && $right
right
} else {
self.changed = true;
// 0 && $right
*expr = *left.take();
return;
}
} else if val {
self.changed = true;
// 1 || $right
*expr = *(left.take());
return;
} else {
// 0 || $right
right
};
if !left.may_have_side_effects(self.expr_ctx) {
self.changed = true;
if node.directness_maters() {
*expr = SeqExpr {
span: node.span(),
exprs: vec![0.into(), node.take()],
}
.into();
} else {
*expr = *node.take();
}
} else {
self.changed = true;
let mut seq = SeqExpr {
span: *span,
exprs: vec![left.take(), node.take()],
};
seq.visit_mut_with(self);
*expr = seq.into()
};
}
}
op!("instanceof") => {
fn is_non_obj(e: &Expr) -> bool {
match e {
// Non-object types are never instances.
Expr::Lit(Lit::Str { .. })
| Expr::Lit(Lit::Num(..))
| Expr::Lit(Lit::Null(..))
| Expr::Lit(Lit::Bool(..)) => true,
Expr::Ident(Ident { sym, .. }) if &**sym == "undefined" => true,
Expr::Ident(Ident { sym, .. }) if &**sym == "Infinity" => true,
Expr::Ident(Ident { sym, .. }) if &**sym == "NaN" => true,
Expr::Unary(UnaryExpr {
op: op!("!"),
ref arg,
..
})
| Expr::Unary(UnaryExpr {
op: op!(unary, "-"),
ref arg,
..
})
| Expr::Unary(UnaryExpr {
op: op!("void"),
ref arg,
..
}) => is_non_obj(arg),
_ => false,
}
}
fn is_obj(e: &Expr) -> bool {
matches!(
*e,
Expr::Array { .. }
| Expr::Object { .. }
| Expr::Fn { .. }
| Expr::New { .. }
)
}
// Non-object types are never instances.
if is_non_obj(left) {
self.changed = true;
*expr = *make_bool_expr(self.expr_ctx, *span, false, iter::once(right.take()));
return;
}
if is_obj(left) && right.is_global_ref_to(self.expr_ctx, "Object") {
self.changed = true;
*expr = *make_bool_expr(self.expr_ctx, *span, true, iter::once(left.take()));
}
}
// Arithmetic operations
op!(bin, "-") | op!("/") | op!("%") | op!("**") => {
try_replace!(number, self.perform_arithmetic_op(*op, left, right))
}
// Bit shift operations
op!("<<") | op!(">>") | op!(">>>") => {
fn try_fold_shift(
ctx: ExprCtx,
op: BinaryOp,
left: &Expr,
right: &Expr,
) -> Value<f64> {
if !left.is_number() || !right.is_number() {
return Unknown;
}
let (lv, rv) = match (left.as_pure_number(ctx), right.as_pure_number(ctx)) {
(Known(lv), Known(rv)) => (lv, rv),
_ => unreachable!(),
};
let (lv, rv) = (JsNumber::from(lv), JsNumber::from(rv));
Known(match op {
op!("<<") => *(lv << rv),
op!(">>") => *(lv >> rv),
op!(">>>") => *(lv.unsigned_shr(rv)),
_ => unreachable!("Unknown bit operator {:?}", op),
})
}
try_replace!(number, try_fold_shift(self.expr_ctx, *op, left, right))
}
// These needs one more check.
//
// (a * 1) * 2 --> a * (1 * 2) --> a * 2
op!("*") | op!("&") | op!("|") | op!("^") => {
try_replace!(number, self.perform_arithmetic_op(*op, left, right));
// Try left.rhs * right
if let Expr::Bin(BinExpr {
span: _,
left: left_lhs,
op: left_op,
right: left_rhs,
}) = &mut **left
{
if *left_op == *op {
if let Known(value) = self.perform_arithmetic_op(*op, left_rhs, right) {
let value_expr = if !value.is_nan() {
Lit::Num(Number {
value,
span: *span,
raw: None,
})
.into()
} else {
Ident::new("NaN".into(), *span, self.expr_ctx.unresolved_ctxt)
.into()
};
self.changed = true;
*left = left_lhs.take();
*right = Box::new(value_expr);
}
}
}
}
// Comparisons
op!("<") => {
try_replace!(self.perform_abstract_rel_cmp(left, right, false))
}
op!(">") => {
try_replace!(self.perform_abstract_rel_cmp(right, left, false))
}
op!("<=") => {
try_replace!(!self.perform_abstract_rel_cmp(right, left, true))
}
op!(">=") => {
try_replace!(!self.perform_abstract_rel_cmp(left, right, true))
}
op!("==") => try_replace!(self.perform_abstract_eq_cmp(*span, left, right)),
op!("!=") => try_replace!(!self.perform_abstract_eq_cmp(*span, left, right)),
op!("===") => try_replace!(self.perform_strict_eq_cmp(left, right)),
op!("!==") => try_replace!(!self.perform_strict_eq_cmp(left, right)),
_ => {}
};
}
/// Folds 'typeof(foo)' if foo is a literal, e.g.
///
/// typeof("bar") --> "string"
///
/// typeof(6) --> "number"
fn try_fold_typeof(&mut self, expr: &mut Expr) {
let UnaryExpr { op, arg, span } = match expr {
Expr::Unary(unary) => unary,
_ => return,
};
assert_eq!(*op, op!("typeof"));
let val = match &**arg {
Expr::Fn(..) => "function",
Expr::Lit(Lit::Str { .. }) => "string",
Expr::Lit(Lit::Num(..)) => "number",
Expr::Lit(Lit::Bool(..)) => "boolean",
Expr::Lit(Lit::Null(..)) | Expr::Object { .. } | Expr::Array { .. } => "object",
Expr::Unary(UnaryExpr {
op: op!("void"), ..
}) => "undefined",
Expr::Ident(Ident { sym, .. }) if &**sym == "undefined" => {
// We can assume `undefined` is `undefined`,
// because overriding `undefined` is always hard error in swc.
"undefined"
}
_ => {
return;
}
};
self.changed = true;
*expr = Lit::Str(Str {
span: *span,
raw: None,
value: val.into(),
})
.into();
}
fn optimize_unary_expr(&mut self, expr: &mut Expr) {
let UnaryExpr { op, arg, span } = match expr {
Expr::Unary(unary) => unary,
_ => return,
};
let may_have_side_effects = arg.may_have_side_effects(self.expr_ctx);
match op {
op!("typeof") if !may_have_side_effects => {
self.try_fold_typeof(expr);
}
op!("!") => {
match &**arg {
// Don't expand booleans.
Expr::Lit(Lit::Num(..)) => return,
// Don't remove ! from negated iifes.
Expr::Call(call) => {
if let Callee::Expr(callee) = &call.callee {
if let Expr::Fn(..) = &**callee {
return;
}
}
}
_ => {}
}
if let (_, Known(val)) = arg.cast_to_bool(self.expr_ctx) {
self.changed = true;
*expr = *make_bool_expr(self.expr_ctx, *span, !val, iter::once(arg.take()));
}
}
op!(unary, "+") => {
if let Known(v) = arg.as_pure_number(self.expr_ctx) {
self.changed = true;
if v.is_nan() {
*expr = *self.expr_ctx.preserve_effects(
*span,
Ident::new("NaN".into(), *span, self.expr_ctx.unresolved_ctxt).into(),
iter::once(arg.take()),
);
return;
}
*expr = *self.expr_ctx.preserve_effects(
*span,
Lit::Num(Number {
value: v,
span: *span,
raw: None,
})
.into(),
iter::once(arg.take()),
);
}
}
op!(unary, "-") => match &**arg {
Expr::Ident(Ident { sym, .. }) if &**sym == "Infinity" => {}
// "-NaN" is "NaN"
Expr::Ident(Ident { sym, .. }) if &**sym == "NaN" => {
self.changed = true;
*expr = *(arg.take());
}
Expr::Lit(Lit::Num(Number { value: f, .. })) => {
self.changed = true;
*expr = Lit::Num(Number {
value: -f,
span: *span,
raw: None,
})
.into();
}
_ => {
// TODO: Report that user is something bad (negating
// non-number value)
}
},
op!("void") if !may_have_side_effects => {
match &**arg {
Expr::Lit(Lit::Num(Number { value, .. })) if *value == 0.0 => return,
_ => {}
}
self.changed = true;
*arg = Lit::Num(Number {
value: 0.0,
span: arg.span(),
raw: None,
})
.into();
}
op!("~") => {
if let Known(value) = arg.as_pure_number(self.expr_ctx) {
if value.fract() == 0.0 {
self.changed = true;
*expr = Lit::Num(Number {
span: *span,
value: if value < 0.0 {
!(value as i32 as u32) as i32 as f64
} else {
!(value as u32) as i32 as f64
},
raw: None,
})
.into();
}
// TODO: Report error
}
}
_ => {}
}
}
/// Try to fold arithmetic binary operators
fn perform_arithmetic_op(&self, op: BinaryOp, left: &Expr, right: &Expr) -> Value<f64> {
/// Replace only if it becomes shorter
macro_rules! try_replace {
($value:expr) => {{
let (ls, rs) = (left.span(), right.span());
if ls.is_dummy() || rs.is_dummy() {
Known($value)
} else {
let new_len = format!("{}", $value).len();
if right.span().hi() > left.span().lo() {
let orig_len = right.span().hi() - right.span().lo() + left.span().hi()
- left.span().lo();
if new_len <= orig_len.0 as usize + 1 {
Known($value)
} else {
Unknown
}
} else {
Known($value)
}
}
}};
(i32, $value:expr) => {
try_replace!($value as f64)
};
}
let (lv, rv) = (
left.as_pure_number(self.expr_ctx),
right.as_pure_number(self.expr_ctx),
);
if (lv.is_unknown() && rv.is_unknown())
|| op == op!(bin, "+")
&& (!left.get_type(self.expr_ctx).casted_to_number_on_add()
|| !right.get_type(self.expr_ctx).casted_to_number_on_add())
{
return Unknown;
}
match op {
op!(bin, "+") => {
if let (Known(lv), Known(rv)) = (lv, rv) {
return try_replace!(lv + rv);
}
if lv == Known(0.0) {
return rv;
} else if rv == Known(0.0) {
return lv;
}
return Unknown;
}
op!(bin, "-") => {
if let (Known(lv), Known(rv)) = (lv, rv) {
return try_replace!(lv - rv);
}
// 0 - x => -x
if lv == Known(0.0) {
return rv;
}
// x - 0 => x
if rv == Known(0.0) {
return lv;
}
return Unknown;
}
op!("*") => {
if let (Known(lv), Known(rv)) = (lv, rv) {
return try_replace!(lv * rv);
}
// NOTE: 0*x != 0 for all x, if x==0, then it is NaN. So we can't take
// advantage of that without some kind of non-NaN proof. So the special cases
// here only deal with 1*x
if Known(1.0) == lv {
return rv;
}
if Known(1.0) == rv {
return lv;
}
return Unknown;
}
op!("/") => {
if let (Known(lv), Known(rv)) = (lv, rv) {
if rv == 0.0 {
return Unknown;
}
return try_replace!(lv / rv);
}
// NOTE: 0/x != 0 for all x, if x==0, then it is NaN
if rv == Known(1.0) {
// TODO: cloneTree
// x/1->x
return lv;
}
return Unknown;
}
op!("**") => {
if Known(0.0) == rv {
return Known(1.0);
}
if let (Known(lv), Known(rv)) = (lv, rv) {
let lv: JsNumber = lv.into();
let rv: JsNumber = rv.into();
let result: f64 = lv.pow(rv).into();
return try_replace!(result);
}
return Unknown;
}
_ => {}
}
let (lv, rv) = match (lv, rv) {
(Known(lv), Known(rv)) => (lv, rv),
_ => return Unknown,
};
match op {
op!("&") => try_replace!(i32, to_int32(lv) & to_int32(rv)),
op!("|") => try_replace!(i32, to_int32(lv) | to_int32(rv)),
op!("^") => try_replace!(i32, to_int32(lv) ^ to_int32(rv)),
op!("%") => {
if rv == 0.0 {
return Unknown;
}
try_replace!(lv % rv)
}
_ => unreachable!("unknown binary operator: {:?}", op),
}
}
/// This actually performs `<`.
///
/// https://tc39.github.io/ecma262/#sec-abstract-relational-comparison
fn perform_abstract_rel_cmp(
&mut self,
left: &Expr,
right: &Expr,
will_negate: bool,
) -> Value<bool> {
match (left, right) {
// Special case: `x < x` is always false.
(
&Expr::Ident(
Ident {
sym: ref li,
ctxt: l_ctxt,
..
},
..,
),
&Expr::Ident(Ident {
sym: ref ri,
ctxt: r_ctxt,
..
}),
) if !will_negate && li == ri && l_ctxt == r_ctxt => {
return Known(false);
}
// Special case: `typeof a < typeof a` is always false.
(
&Expr::Unary(UnaryExpr {
op: op!("typeof"),
arg: ref la,
..
}),
&Expr::Unary(UnaryExpr {
op: op!("typeof"),
arg: ref ra,
..
}),
) if la.as_ident().is_some()
&& la.as_ident().map(|i| i.to_id()) == ra.as_ident().map(|i| i.to_id()) =>
{
return Known(false)
}
_ => {}
}
// Try to evaluate based on the general type.
let (lt, rt) = (left.get_type(self.expr_ctx), right.get_type(self.expr_ctx));
if let (Known(StringType), Known(StringType)) = (lt, rt) {
if let (Known(lv), Known(rv)) = (
left.as_pure_string(self.expr_ctx),
right.as_pure_string(self.expr_ctx),
) {
// In JS, browsers parse \v differently. So do not compare strings if one
// contains \v.
if lv.contains('\u{000B}') || rv.contains('\u{000B}') {
return Unknown;
} else {
return Known(lv < rv);
}
}
}
// Then, try to evaluate based on the value of the node. Try comparing as
// numbers.
let (lv, rv) = (
try_val!(left.as_pure_number(self.expr_ctx)),
try_val!(right.as_pure_number(self.expr_ctx)),
);
if lv.is_nan() || rv.is_nan() {
return Known(will_negate);
}
Known(lv < rv)
}
/// https://tc39.github.io/ecma262/#sec-abstract-equality-comparison
fn perform_abstract_eq_cmp(&mut self, span: Span, left: &Expr, right: &Expr) -> Value<bool> {
let (lt, rt) = (
try_val!(left.get_type(self.expr_ctx)),
try_val!(right.get_type(self.expr_ctx)),
);
if lt == rt {
return self.perform_strict_eq_cmp(left, right);
}
match (lt, rt) {
(NullType, UndefinedType) | (UndefinedType, NullType) => Known(true),
(NumberType, StringType) | (_, BoolType) => {
let rv = try_val!(right.as_pure_number(self.expr_ctx));
self.perform_abstract_eq_cmp(
span,
left,
&Lit::Num(Number {
value: rv,
span,
raw: None,
})
.into(),
)
}
(StringType, NumberType) | (BoolType, _) => {
let lv = try_val!(left.as_pure_number(self.expr_ctx));
self.perform_abstract_eq_cmp(
span,
&Lit::Num(Number {
value: lv,
span,
raw: None,
})
.into(),
right,
)
}
(StringType, ObjectType)
| (NumberType, ObjectType)
| (ObjectType, StringType)
| (ObjectType, NumberType) => Unknown,
_ => Known(false),
}
}
/// https://tc39.github.io/ecma262/#sec-strict-equality-comparison
fn perform_strict_eq_cmp(&mut self, left: &Expr, right: &Expr) -> Value<bool> {
// Any strict equality comparison against NaN returns false.
if left.is_nan() || right.is_nan() {
return Known(false);
}
match (left, right) {
// Special case, typeof a == typeof a is always true.
(
&Expr::Unary(UnaryExpr {
op: op!("typeof"),
arg: ref la,
..
}),
&Expr::Unary(UnaryExpr {
op: op!("typeof"),
arg: ref ra,
..
}),
) if la.as_ident().is_some()
&& la.as_ident().map(|i| i.to_id()) == ra.as_ident().map(|i| i.to_id()) =>
{
return Known(true)
}
_ => {}
}
let (lt, rt) = (
try_val!(left.get_type(self.expr_ctx)),
try_val!(right.get_type(self.expr_ctx)),
);
// Strict equality can only be true for values of the same type.
if lt != rt {
return Known(false);
}
match lt {
UndefinedType | NullType => Known(true),
NumberType => Known(
try_val!(left.as_pure_number(self.expr_ctx))
== try_val!(right.as_pure_number(self.expr_ctx)),
),
StringType => {
let (lv, rv) = (
try_val!(left.as_pure_string(self.expr_ctx)),
try_val!(right.as_pure_string(self.expr_ctx)),
);
// In JS, browsers parse \v differently. So do not consider strings
// equal if one contains \v.
if lv.contains('\u{000B}') || rv.contains('\u{000B}') {
return Unknown;
}
Known(lv == rv)
}
BoolType => {
let (lv, rv) = (
left.as_pure_bool(self.expr_ctx),
right.as_pure_bool(self.expr_ctx),
);
// lv && rv || !lv && !rv
lv.and(rv).or((!lv).and(!rv))
}
ObjectType | SymbolType => Unknown,
}
}
}
impl VisitMut for SimplifyExpr {
noop_visit_mut_type!();
fn visit_mut_assign_expr(&mut self, n: &mut AssignExpr) {
let old = self.is_modifying;
self.is_modifying = true;
n.left.visit_mut_with(self);
self.is_modifying = old;
self.is_modifying = false;
n.right.visit_mut_with(self);
self.is_modifying = old;
}
/// This is overriden to preserve `this`.
fn visit_mut_call_expr(&mut self, n: &mut CallExpr) {
let old_in_callee = self.in_callee;
self.in_callee = true;
match &mut n.callee {
Callee::Super(..) | Callee::Import(..) => {}
Callee::Expr(e) => {
let may_inject_zero = !need_zero_for_this(e);
match &mut **e {
Expr::Seq(seq) => {
if seq.exprs.len() == 1 {
let mut expr = seq.exprs.take().into_iter().next().unwrap();
expr.visit_mut_with(self);
*e = expr;
} else if seq
.exprs
.last()
.map(|v| &**v)
.map_or(false, Expr::directness_maters)
{
match seq.exprs.first().map(|v| &**v) {
Some(Expr::Lit(..) | Expr::Ident(..)) => {}
_ => {
tracing::debug!("Injecting `0` to preserve `this = undefined`");
seq.exprs.insert(0, 0.0.into());
}
}
seq.visit_mut_with(self);
}
}
_ => {
e.visit_mut_with(self);
}
}
if may_inject_zero && need_zero_for_this(e) {
match &mut **e {
Expr::Seq(seq) => {
seq.exprs.insert(0, 0.into());
}
_ => {
let seq = SeqExpr {
span: DUMMY_SP,
exprs: vec![0.0.into(), e.take()],
};
**e = seq.into();
}
}
}
}
}
self.in_callee = false;
n.args.visit_mut_with(self);
self.in_callee = old_in_callee;
}
fn visit_mut_class_members(&mut self, members: &mut Vec<ClassMember>) {
self.maybe_par(cpu_count(), members, |v, member| {
member.visit_mut_with(v);
});
}
fn visit_mut_export_default_expr(&mut self, expr: &mut ExportDefaultExpr) {
fn is_paren_wrap_fn_or_class(expr: &mut Expr, visitor: &mut SimplifyExpr) -> bool {
match &mut *expr {
Expr::Fn(..) | Expr::Class(..) => {
expr.visit_mut_children_with(visitor);
true
}
Expr::Paren(p) => is_paren_wrap_fn_or_class(&mut p.expr, visitor),
_ => false,
}
}
if !is_paren_wrap_fn_or_class(&mut expr.expr, self) {
expr.visit_mut_children_with(self);
}
}
fn visit_mut_expr(&mut self, expr: &mut Expr) {
if let Expr::Unary(UnaryExpr {
op: op!("delete"), ..
}) = expr
{
return;
}
// fold children before doing something more.
expr.visit_mut_children_with(self);
match expr {
// Do nothing.
// Note: Paren should be handled in fixer
Expr::Lit(_) | Expr::This(..) | Expr::Paren(..) => return,
Expr::Seq(seq) if seq.exprs.is_empty() => return,
Expr::Unary(..)
| Expr::Bin(..)
| Expr::Member(..)
| Expr::Cond(..)
| Expr::Seq(..)
| Expr::Array(..)
| Expr::Object(..)
| Expr::New(..) => {}
_ => return,
}
match expr {
Expr::Unary(_) => {
self.optimize_unary_expr(expr);
debug_assert_valid(expr);
}
Expr::Bin(_) => {
self.optimize_bin_expr(expr);
debug_assert_valid(expr);
}
Expr::Member(_) => {
self.optimize_member_expr(expr);
debug_assert_valid(expr);
}
Expr::Cond(CondExpr {
span,
test,
cons,
alt,
}) => {
if let (p, Known(val)) = test.cast_to_bool(self.expr_ctx) {
self.changed = true;
let expr_value = if val { cons } else { alt };
*expr = if p.is_pure() {
if expr_value.directness_maters() {
SeqExpr {
span: *span,
exprs: vec![0.into(), expr_value.take()],
}
.into()
} else {
*expr_value.take()
}
} else {
SeqExpr {
span: *span,
exprs: vec![test.take(), expr_value.take()],
}
.into()
}
}
}
// Simplify sequence expression.
Expr::Seq(SeqExpr { exprs, .. }) => {
if exprs.len() == 1 {
//TODO: Respan
*expr = *exprs.take().into_iter().next().unwrap()
} else {
assert!(!exprs.is_empty(), "sequence expression should not be empty");
//TODO: remove unused
}
}
Expr::Array(ArrayLit { elems, .. }) => {
let mut e = Vec::with_capacity(elems.len());
for elem in elems.take() {
match elem {
Some(ExprOrSpread {
spread: Some(..),
expr,
}) if expr.is_array() => {
self.changed = true;
e.extend(expr.array().unwrap().elems.into_iter().map(|elem| {
Some(elem.unwrap_or_else(|| ExprOrSpread {
spread: None,
expr: Expr::undefined(DUMMY_SP),
}))
}));
}
_ => e.push(elem),
}
}
*elems = e;
}
Expr::Object(ObjectLit { props, .. }) => {
let should_work = props.iter().any(|p| matches!(p, PropOrSpread::Spread(..)));
if !should_work {
return;
}
let mut ps = Vec::with_capacity(props.len());
for p in props.take() {
match p {
PropOrSpread::Spread(SpreadElement {
dot3_token, expr, ..
}) if expr.is_object() => {
if let Expr::Object(obj) = &*expr {
if obj.props.iter().any(|p| match p {
PropOrSpread::Spread(..) => true,
PropOrSpread::Prop(p) => !matches!(
&**p,
Prop::Shorthand(_) | Prop::KeyValue(_) | Prop::Method(_)
),
}) {
ps.push(PropOrSpread::Spread(SpreadElement {
dot3_token,
expr,
}));
continue;
}
}
let props = expr.object().unwrap().props;
ps.extend(props);
self.changed = true;
}
_ => ps.push(p),
}
}
*props = ps;
}
// be conservative.
_ => {}
};
}
fn visit_mut_expr_or_spreads(&mut self, n: &mut Vec<ExprOrSpread>) {
self.maybe_par(cpu_count(), n, |v, n| {
n.visit_mut_with(v);
});
}
fn visit_mut_exprs(&mut self, n: &mut Vec<Box<Expr>>) {
self.maybe_par(cpu_count(), n, |v, n| {
n.visit_mut_with(v);
});
}
fn visit_mut_for_head(&mut self, n: &mut ForHead) {
let old = self.is_modifying;
self.is_modifying = true;
n.visit_mut_children_with(self);
self.is_modifying = old;
}
fn visit_mut_module_items(&mut self, n: &mut Vec<ModuleItem>) {
let mut child = SimplifyExpr {
expr_ctx: self.expr_ctx,
config: self.config,
changed: Default::default(),
is_arg_of_update: Default::default(),
is_modifying: Default::default(),
in_callee: Default::default(),
};
child.maybe_par(cpu_count(), n, |v, n| {
n.visit_mut_with(v);
});
self.changed |= child.changed;
}
/// Currently noop
#[inline]
fn visit_mut_opt_chain_expr(&mut self, _: &mut OptChainExpr) {}
fn visit_mut_opt_var_decl_or_expr(&mut self, n: &mut Option<VarDeclOrExpr>) {
if let Some(VarDeclOrExpr::Expr(e)) = n {
match &mut **e {
Expr::Seq(SeqExpr { exprs, .. }) if exprs.is_empty() => {
*n = None;
return;
}
_ => {}
}
}
n.visit_mut_children_with(self);
}
fn visit_mut_opt_vec_expr_or_spreads(&mut self, n: &mut Vec<Option<ExprOrSpread>>) {
self.maybe_par(cpu_count(), n, |v, n| {
n.visit_mut_with(v);
});
}
fn visit_mut_pat(&mut self, p: &mut Pat) {
let old_in_callee = self.in_callee;
self.in_callee = false;
p.visit_mut_children_with(self);
self.in_callee = old_in_callee;
if let Pat::Assign(a) = p {
if a.right.is_undefined(self.expr_ctx)
|| match *a.right {
Expr::Unary(UnaryExpr {
op: op!("void"),
ref arg,
..
}) => !arg.may_have_side_effects(self.expr_ctx),
_ => false,
}
{
self.changed = true;
*p = *a.left.take();
}
}
}
fn visit_mut_prop_or_spreads(&mut self, n: &mut Vec<PropOrSpread>) {
self.maybe_par(cpu_count(), n, |v, n| {
n.visit_mut_with(v);
});
}
/// Drops unused values
fn visit_mut_seq_expr(&mut self, e: &mut SeqExpr) {
if e.exprs.is_empty() {
return;
}
let old_in_callee = self.in_callee;
let len = e.exprs.len();
for (idx, e) in e.exprs.iter_mut().enumerate() {
if idx == len - 1 {
self.in_callee = old_in_callee;
} else {
self.in_callee = false;
}
e.visit_mut_with(self);
}
self.in_callee = old_in_callee;
let len = e.exprs.len();
let last_expr = e.exprs.pop().expect("SeqExpr.exprs must not be empty");
// Expressions except last one
let mut exprs = Vec::with_capacity(e.exprs.len() + 1);
for expr in e.exprs.take() {
match *expr {
Expr::Lit(Lit::Num(n)) if self.in_callee && n.value == 0.0 => {
if exprs.is_empty() {
exprs.push(0.0.into());
tracing::trace!("expr_simplifier: Preserving first zero");
}
}
Expr::Lit(..) | Expr::Ident(..)
if self.in_callee && !expr.may_have_side_effects(self.expr_ctx) =>
{
if exprs.is_empty() {
self.changed = true;
exprs.push(0.0.into());
tracing::debug!("expr_simplifier: Injected first zero");
}
}
// Drop side-effect free nodes.
Expr::Lit(_) => {}
// Flatten array
Expr::Array(ArrayLit { span, elems }) => {
let is_simple = elems
.iter()
.all(|elem| matches!(elem, None | Some(ExprOrSpread { spread: None, .. })));
if is_simple {
exprs.extend(elems.into_iter().flatten().map(|e| e.expr));
} else {
exprs.push(Box::new(ArrayLit { span, elems }.into()));
}
}
// Default case: preserve it
_ => exprs.push(expr),
}
}
exprs.push(last_expr);
self.changed |= len != exprs.len();
e.exprs = exprs;
}
fn visit_mut_stmt(&mut self, s: &mut Stmt) {
let old_is_modifying = self.is_modifying;
self.is_modifying = false;
let old_is_arg_of_update = self.is_arg_of_update;
self.is_arg_of_update = false;
s.visit_mut_children_with(self);
self.is_arg_of_update = old_is_arg_of_update;
self.is_modifying = old_is_modifying;
debug_assert_valid(s);
}
fn visit_mut_stmts(&mut self, n: &mut Vec<Stmt>) {
let mut child = SimplifyExpr {
expr_ctx: self.expr_ctx,
config: self.config,
changed: Default::default(),
is_arg_of_update: Default::default(),
is_modifying: Default::default(),
in_callee: Default::default(),
};
child.maybe_par(cpu_count(), n, |v, n| {
n.visit_mut_with(v);
});
self.changed |= child.changed;
}
fn visit_mut_tagged_tpl(&mut self, n: &mut TaggedTpl) {
let old = self.in_callee;
self.in_callee = true;
n.tag.visit_mut_with(self);
self.in_callee = false;
n.tpl.visit_mut_with(self);
self.in_callee = old;
}
fn visit_mut_update_expr(&mut self, n: &mut UpdateExpr) {
let old = self.is_modifying;
self.is_modifying = true;
n.arg.visit_mut_with(self);
self.is_modifying = old;
}
fn visit_mut_with_stmt(&mut self, n: &mut WithStmt) {
n.obj.visit_mut_with(self);
}
}
/// make a new boolean expression preserving side effects, if any.
fn make_bool_expr<I>(ctx: ExprCtx, span: Span, value: bool, orig: I) -> Box<Expr>
where
I: IntoIterator<Item = Box<Expr>>,
{
ctx.preserve_effects(span, Lit::Bool(Bool { value, span }).into(), orig)
}
fn nth_char(s: &str, mut idx: usize) -> Option<Cow<str>> {
if s.chars().any(|c| c.len_utf16() > 1) {
return None;
}
if !s.contains("\\ud") && !s.contains("\\uD") {
return Some(Cow::Owned(s.chars().nth(idx).unwrap().to_string()));
}
let mut iter = s.chars().peekable();
while let Some(c) = iter.next() {
if c == '\\' && iter.peek().copied() == Some('u') {
if idx == 0 {
let mut buf = String::new();
buf.push('\\');
buf.extend(iter.take(5));
return Some(Cow::Owned(buf));
} else {
for _ in 0..5 {
iter.next();
}
}
}
if idx == 0 {
return Some(Cow::Owned(c.to_string()));
}
idx -= 1;
}
unreachable!("string is too short")
}
fn need_zero_for_this(e: &Expr) -> bool {
e.directness_maters() || e.is_seq()
}
/// Gets the value of the given key from the given object properties, if the key
/// exists. If the key does exist, `Some` is returned and the property is
/// removed from the given properties.
fn get_key_value(key: &str, props: &mut Vec<PropOrSpread>) -> Option<Box<Expr>> {
// It's impossible to know the value for certain if a spread property exists.
let has_spread = props.iter().any(|prop| prop.is_spread());
if has_spread {
return None;
}
for (i, prop) in props.iter_mut().enumerate().rev() {
let prop = match prop {
PropOrSpread::Prop(x) => &mut **x,
PropOrSpread::Spread(_) => unreachable!(),
};
match prop {
Prop::Shorthand(ident) if ident.sym == key => {
let prop = match props.remove(i) {
PropOrSpread::Prop(x) => *x,
_ => unreachable!(),
};
let ident = match prop {
Prop::Shorthand(x) => x,
_ => unreachable!(),
};
return Some(ident.into());
}
Prop::KeyValue(prop) => {
if key != "__proto__" && prop_name_eq(&prop.key, "__proto__") {
// If __proto__ is defined, we need to check the contents of it,
// as well as any nested __proto__ objects
let Expr::Object(ObjectLit { props, .. }) = &mut *prop.value else {
// __proto__ is not an ObjectLiteral. It's unsafe to keep trying to find
// a value for this key, since __proto__ might also contain the key.
return None;
};
// Get key value from __props__ object. Only return if
// the result is Some. If None, we keep searching in the
// parent object.
let v = get_key_value(key, props);
if v.is_some() {
return v;
}
} else if prop_name_eq(&prop.key, key) {
let prop = match props.remove(i) {
PropOrSpread::Prop(x) => *x,
_ => unreachable!(),
};
let prop = match prop {
Prop::KeyValue(x) => x,
_ => unreachable!(),
};
return Some(prop.value);
}
}
_ => {}
}
}
None
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_optimization/src/simplify/expr/tests.rs | Rust | use swc_common::{Mark, SyntaxContext};
use swc_ecma_transforms_base::{fixer::paren_remover, resolver};
use swc_ecma_transforms_testing::test_transform;
use swc_ecma_utils::ExprCtx;
use swc_ecma_visit::visit_mut_pass;
use super::SimplifyExpr;
fn fold(src: &str, expected: &str) {
test_transform(
::swc_ecma_parser::Syntax::default(),
None,
|_| {
let unresolved_mark = Mark::new();
let top_level_mark = Mark::new();
(
resolver(unresolved_mark, top_level_mark, false),
paren_remover(None),
visit_mut_pass(SimplifyExpr {
expr_ctx: ExprCtx {
unresolved_ctxt: SyntaxContext::empty().apply_mark(unresolved_mark),
// This is hack
is_unresolved_ref_safe: true,
in_strict: false,
remaining_depth: 4,
},
config: super::Config {},
changed: false,
is_arg_of_update: false,
is_modifying: false,
in_callee: false,
}),
)
},
src,
expected,
)
}
/// Should not modify expression.
fn fold_same(s: &str) {
fold(s, s)
}
#[test]
fn regex() {
fold("/ab/?x=1:x=2", "x=1");
}
#[test]
fn object() {
fold("!({a:foo()});", "foo(), false;");
}
#[test]
fn test_undefined_comparison1() {
fold("undefined == undefined", "true");
fold("undefined == null", "true");
fold("undefined == void 0", "true");
fold("undefined == 0", "false");
fold("undefined == 1", "false");
fold("undefined == 'hi'", "false");
fold("undefined == true", "false");
fold("undefined == false", "false");
fold("undefined === undefined", "true");
fold("undefined === null", "false");
fold("undefined === void 0", "true");
fold_same("undefined == this");
fold_same("undefined == x");
fold("undefined != undefined", "false");
fold("undefined != null", "false");
fold("undefined != void 0", "false");
fold("undefined != 0", "true");
fold("undefined != 1", "true");
fold("undefined != 'hi'", "true");
fold("undefined != true", "true");
fold("undefined != false", "true");
fold("undefined !== undefined", "false");
fold("undefined !== void 0", "false");
fold("undefined !== null", "true");
fold_same("undefined != this");
fold_same("undefined != x");
fold("undefined < undefined", "false");
fold("undefined > undefined", "false");
fold("undefined >= undefined", "false");
fold("undefined <= undefined", "false");
fold("0 < undefined", "false");
fold("true > undefined", "false");
fold("'hi' >= undefined", "false");
fold("null <= undefined", "false");
fold("undefined < 0", "false");
fold("undefined > true", "false");
fold("undefined >= 'hi'", "false");
fold("undefined <= null", "false");
fold("null == undefined", "true");
fold("0 == undefined", "false");
fold("1 == undefined", "false");
fold("'hi' == undefined", "false");
fold("true == undefined", "false");
fold("false == undefined", "false");
fold("null === undefined", "false");
fold("void 0 === undefined", "true");
fold("undefined == NaN", "false");
fold("NaN == undefined", "false");
fold("undefined == Infinity", "false");
fold("Infinity == undefined", "false");
fold("undefined == -Infinity", "false");
fold("-Infinity == undefined", "false");
fold("({}) == undefined", "false");
fold("undefined == ({})", "false");
fold("([]) == undefined", "false");
fold("undefined == ([])", "false");
fold("(/a/g) == undefined", "false");
fold("undefined == (/a/g)", "false");
fold("(function(){}) == undefined", "false");
fold("undefined == (function(){})", "false");
fold("undefined != NaN", "true");
fold("NaN != undefined", "true");
fold("undefined != Infinity", "true");
fold("Infinity != undefined", "true");
fold("undefined != -Infinity", "true");
fold("-Infinity != undefined", "true");
fold("({}) != undefined", "true");
fold("undefined != ({})", "true");
fold("([]) != undefined", "true");
fold("undefined != ([])", "true");
fold("(/a/g) != undefined", "true");
fold("undefined != (/a/g)", "true");
fold("(function(){}) != undefined", "true");
fold("undefined != (function(){})", "true");
fold_same("this == undefined");
fold_same("x == undefined");
}
#[test]
fn test_undefined_comparison2() {
fold("\"123\" !== void 0", "true");
fold("\"123\" === void 0", "false");
fold("void 0 !== \"123\"", "true");
fold("void 0 === \"123\"", "false");
}
#[test]
fn test_undefined_comparison3() {
fold("\"123\" !== undefined", "true");
fold("\"123\" === undefined", "false");
fold("undefined !== \"123\"", "true");
fold("undefined === \"123\"", "false");
}
#[test]
fn test_undefined_comparison4() {
fold("1 !== void 0", "true");
fold("1 === void 0", "false");
fold("null !== void 0", "true");
fold("null === void 0", "false");
fold("undefined !== void 0", "false");
fold("undefined === void 0", "true");
}
#[test]
fn test_null_comparison1() {
fold("null == undefined", "true");
fold("null == null", "true");
fold("null == void 0", "true");
fold("null == 0", "false");
fold("null == 1", "false");
fold("null == 'hi'", "false");
fold("null == true", "false");
fold("null == false", "false");
fold("null === undefined", "false");
fold("null === null", "true");
fold("null === void 0", "false");
fold_same("null === x");
fold_same("null == this");
fold_same("null == x");
fold("null != undefined", "false");
fold("null != null", "false");
fold("null != void 0", "false");
fold("null != 0", "true");
fold("null != 1", "true");
fold("null != 'hi'", "true");
fold("null != true", "true");
fold("null != false", "true");
fold("null !== undefined", "true");
fold("null !== void 0", "true");
fold("null !== null", "false");
fold_same("null != this");
fold_same("null != x");
fold("null < null", "false");
fold("null > null", "false");
fold("null >= null", "true");
fold("null <= null", "true");
fold("0 < null", "false");
fold("0 > null", "false");
fold("0 >= null", "true");
fold("true > null", "true");
fold("'hi' < null", "false");
fold("'hi' >= null", "false");
fold("null <= null", "true");
fold("null < 0", "false");
fold("null > true", "false");
fold("null < 'hi'", "false");
fold("null >= 'hi'", "false");
fold("null <= null", "true");
fold("null == null", "true");
fold("0 == null", "false");
fold("1 == null", "false");
fold("'hi' == null", "false");
fold("true == null", "false");
fold("false == null", "false");
fold("null === null", "true");
fold("void 0 === null", "false");
fold("null == NaN", "false");
fold("NaN == null", "false");
fold("null == Infinity", "false");
fold("Infinity == null", "false");
fold("null == -Infinity", "false");
fold("-Infinity == null", "false");
fold("({}) == null", "false");
fold("null == ({})", "false");
fold("([]) == null", "false");
fold("null == ([])", "false");
fold("(/a/g) == null", "false");
fold("null == (/a/g)", "false");
fold("(function(){}) == null", "false");
fold("null == (function(){})", "false");
fold("null != NaN", "true");
fold("NaN != null", "true");
fold("null != Infinity", "true");
fold("Infinity != null", "true");
fold("null != -Infinity", "true");
fold("-Infinity != null", "true");
fold("({}) != null", "true");
fold("null != ({})", "true");
fold("([]) != null", "true");
fold("null != ([])", "true");
fold("(/a/g) != null", "true");
fold("null != (/a/g)", "true");
fold("(function(){}) != null", "true");
fold("null != (function(){})", "true");
fold("({a:f()}) == null", "f(), false;");
fold("null == ({a:f()})", "f(), false");
fold("([f()]) == null", "f(), false");
fold("null == ([f()])", "f(), false");
fold_same("this == null");
fold_same("x == null");
}
#[test]
fn test_boolean_boolean_comparison() {
fold_same("!x == !y");
fold_same("!x < !y");
fold_same("!x !== !y");
fold_same("!x == !x"); // foldable
fold_same("!x < !x"); // foldable
fold_same("!x !== !x"); // foldable
}
#[test]
fn test_boolean_number_comparison() {
fold_same("!x == +y");
fold_same("!x <= +y");
fold("!x !== +y", "true");
}
#[test]
fn test_number_boolean_comparison() {
fold_same("+x == !y");
fold_same("+x <= !y");
fold("+x === !y", "false");
}
#[test]
fn test_boolean_string_comparison() {
fold_same("!x == '' + y");
fold_same("!x <= '' + y");
fold("!x !== '' + y", "true");
}
#[test]
fn test_string_boolean_comparison() {
fold_same("'' + x == !y");
fold_same("'' + x <= !y");
fold("'' + x === !y", "false");
}
#[test]
fn test_number_number_comparison() {
fold("1 > 1", "false");
fold("2 == 3", "false");
fold("3.6 === 3.6", "true");
fold_same("+x > +y");
fold_same("+x == +y");
fold_same("+x === +y");
fold_same("+x == +x");
fold_same("+x === +x");
fold_same("+x > +x"); // foldable
}
#[test]
fn test_string_string_comparison() {
fold("'a' < 'b'", "true");
fold("'a' <= 'b'", "true");
fold("'a' > 'b'", "false");
fold("'a' >= 'b'", "false");
fold("+'a' < +'b'", "false");
fold_same("typeof a < 'a'");
fold_same("'a' >= typeof a");
fold("typeof a < typeof a", "false");
fold("typeof a >= typeof a", "true");
fold("typeof 3 > typeof 4", "false");
fold("typeof function() {} < typeof function() {}", "false");
fold("'a' == 'a'", "true");
fold("'b' != 'a'", "true");
fold_same("'undefined' == typeof a");
fold_same("typeof a != 'number'");
fold_same("'undefined' == typeof a");
fold_same("'undefined' == typeof a");
fold("typeof a == typeof a", "true");
fold("'a' === 'a'", "true");
fold("'b' !== 'a'", "true");
fold("typeof a === typeof a", "true");
fold("typeof a !== typeof a", "false");
fold_same("'' + x <= '' + y");
fold_same("'' + x != '' + y");
fold_same("'' + x === '' + y");
fold_same("'' + x <= '' + x"); // potentially foldable
fold_same("'' + x != '' + x"); // potentially foldable
fold_same("'' + x === '' + x"); // potentially foldable
}
#[test]
fn test_number_string_comparison() {
fold("1 < '2'", "true");
fold("2 > '1'", "true");
fold("123 > '34'", "true");
fold("NaN >= 'NaN'", "false");
fold("1 == '2'", "false");
fold("1 != '1'", "false");
fold("NaN == 'NaN'", "false");
fold("1 === '1'", "false");
fold("1 !== '1'", "true");
fold_same("+x > '' + y");
fold_same("+x == '' + y");
fold("+x !== '' + y", "true");
}
#[test]
fn test_string_number_comparison() {
fold("'1' < 2", "true");
fold("'2' > 1", "true");
fold("'123' > 34", "true");
fold("'NaN' < NaN", "false");
fold("'1' == 2", "false");
fold("'1' != 1", "false");
fold("'NaN' == NaN", "false");
fold("'1' === 1", "false");
fold("'1' !== 1", "true");
fold_same("'' + x < +y");
fold_same("'' + x == +y");
fold("'' + x === +y", "false");
}
#[test]
fn test_nan_comparison() {
fold("NaN < NaN", "false");
fold("NaN >= NaN", "false");
fold("NaN == NaN", "false");
fold("NaN === NaN", "false");
fold("NaN < null", "false");
fold("null >= NaN", "false");
fold("NaN == null", "false");
fold("null != NaN", "true");
fold("null === NaN", "false");
fold("NaN < undefined", "false");
fold("undefined >= NaN", "false");
fold("NaN == undefined", "false");
fold("undefined != NaN", "true");
fold("undefined === NaN", "false");
fold_same("NaN < x");
fold_same("x >= NaN");
fold_same("NaN == x");
fold_same("x != NaN");
fold("NaN === x", "false");
fold("x !== NaN", "true");
fold_same("NaN == foo()");
}
#[test]
fn test_object_comparison1() {
fold("!new Date()", "false");
fold("!!new Date()", "true");
fold("new Date() == null", "false");
fold("new Date() == undefined", "false");
fold("new Date() != null", "true");
fold("new Date() != undefined", "true");
fold("null == new Date()", "false");
fold("undefined == new Date()", "false");
fold("null != new Date()", "true");
fold("undefined != new Date()", "true");
}
#[test]
fn test_unary_ops_1() {
// These cases are handled by PeepholeRemoveDeadCode.
fold_same("!foo()");
fold_same("~foo()");
fold_same("-foo()");
// These cases are handled here.
fold("a=!true", "a=false");
fold("a=!10", "a=!10");
fold("a=!false", "a=true");
fold_same("a=!foo()");
//fold("a=-0", "a=-0.0");
//fold("a=-(0)", "a=-0.0");
fold_same("a=-Infinity");
fold("a=-NaN", "a=NaN");
fold_same("a=-foo()");
fold("a=~~0", "a=0");
fold("a=~~10", "a=10");
fold("a=~-7", "a=6");
fold("a=+true", "a=1");
fold("a=+10", "a=10");
fold("a=+false", "a=0");
fold_same("a=+foo()");
fold_same("a=+f");
// fold("a=+(f?true:false)", "a=+(f?1:0)");
}
#[test]
fn test_unary_ops_2() {
fold("a=+0", "a=0");
fold("a=+Infinity", "a=Infinity");
fold("a=+NaN", "a=NaN");
fold("a=+-7", "a=-7");
fold("a=+.5", "a=0.5");
}
#[test]
fn test_unary_ops_3() {
fold("a=~0xffffffff", "a=0");
}
#[test]
fn test_unary_ops_4() {
fold("a=~~0xffffffff", "a=-1");
}
#[test]
fn test_unary_ops_5() {
// Empty arrays
fold("+[]", "0");
fold("+[[]]", "0");
fold("+[[[]]]", "0");
// Arrays with one element
fold("+[1]", "1");
fold("+[[1]]", "1");
fold("+[undefined]", "0");
fold("+[null]", "0");
fold("+[,]", "0");
// Arrays with more than one element
fold("+[1, 2]", "NaN");
fold("+[[1], 2]", "NaN");
fold("+[,1]", "NaN");
fold("+[,,]", "NaN");
}
#[test]
fn test_unary_ops_string_compare() {
fold_same("a = -1");
fold("a = ~0", "a = -1");
fold("a = ~1", "a = -2");
fold("a = ~101", "a = -102");
}
#[test]
fn test_fold_logical_op_1() {
fold("x = true && x", "x = x");
fold("x = [foo()] && x", "x = (foo(),x)");
fold("x = false && x", "x = false");
fold("x = true || x", "x = true");
fold("x = false || x", "x = x");
fold("x = 0 && x", "x = 0");
fold("x = 3 || x", "x = 3");
fold("x = false || 0", "x = 0");
// unfoldable, because the right-side may be the result
fold("a = x && true", "a=x && true");
fold("a = x && false", "a=x && false");
fold("a = x || 3", "a=x || 3");
fold("a = x || false", "a=x || false");
fold("a = b ? c : x || false", "a=b ? c:x || false");
fold("a = b ? x || false : c", "a=b ? x || false:c");
fold("a = b ? c : x && true", "a=b ? c:x && true");
fold("a = b ? x && true : c", "a=b ? x && true:c");
// folded, but not here.
fold_same("a = x || false ? b : c");
fold_same("a = x && true ? b : c");
}
#[test]
#[ignore]
fn test_fold_logical_op_2() {
fold("x = foo() || true || bar()", "x = foo() || true");
fold("x = foo() || true && bar()", "x = foo() || bar()");
fold("x = foo() || false && bar()", "x = foo() || false");
fold("x = foo() && false && bar()", "x = foo() && false");
fold("x = foo() && false || bar()", "x = (foo() && false,bar())");
fold("x = foo() || false || bar()", "x = foo() || bar()");
fold("x = foo() && true && bar()", "x = foo() && bar()");
fold("x = foo() || true || bar()", "x = foo() || true");
fold("x = foo() && false && bar()", "x = foo() && false");
fold("x = foo() && 0 && bar()", "x = foo() && 0");
fold("x = foo() && 1 && bar()", "x = foo() && bar()");
fold("x = foo() || 0 || bar()", "x = foo() || bar()");
fold("x = foo() || 1 || bar()", "x = foo() || 1");
fold_same("x = foo() || bar() || baz()");
fold_same("x = foo() && bar() && baz()");
fold("0 || b()", "b()");
fold("1 && b()", "b()");
fold("a() && (1 && b())", "a() && b()");
fold("(a() && 1) && b()", "a() && b()");
fold("(x || '') || y;", "x || y");
fold("false || (x || '');", "x || ''");
fold("(x && 1) && y;", "x && y");
fold("true && (x && 1);", "x && 1");
// Really not foldable, because it would change the type of the
// expression if foo() returns something truthy but not true.
// Cf. FoldConstants.tryFoldAndOr().
// An example would be if foo() is 1 (truthy) and bar() is 0 (falsy):
// (1 && true) || 0 == true
// 1 || 0 == 1, but true =/= 1
fold_same("x = foo() && true || bar()");
fold_same("foo() && true || bar()");
}
#[test]
fn test_fold_logical_op2() {
fold("x = function(){} && x", "x = x");
fold("x = true && function(){}", "x = function(){}");
fold(
"x = [(function(){alert(x)})()] && x",
"x = (function() { alert(x); }(), x);",
);
}
#[test]
fn test_fold_bitwise_op() {
fold("x = 1 & 1", "x = 1");
fold("x = 1 & 2", "x = 0");
fold("x = 3 & 1", "x = 1");
fold("x = 3 & 3", "x = 3");
fold("x = 1 | 1", "x = 1");
fold("x = 1 | 2", "x = 3");
fold("x = 3 | 1", "x = 3");
fold("x = 3 | 3", "x = 3");
fold("x = 1 ^ 1", "x = 0");
fold("x = 1 ^ 2", "x = 3");
fold("x = 3 ^ 1", "x = 2");
fold("x = 3 ^ 3", "x = 0");
fold("x = -1 & 0", "x = 0");
fold("x = 0 & -1", "x = 0");
fold("x = 1 & 4", "x = 0");
fold("x = 2 & 3", "x = 2");
// make sure we fold only when we are supposed to -- not when doing so would
// lose information or when it is performed on nonsensical arguments.
fold("x = 1 & 1.1", "x = 1");
fold("x = 1.1 & 1", "x = 1");
fold("x = 1 & 3000000000", "x = 0");
fold("x = 3000000000 & 1", "x = 0");
// Try some cases with | as well
fold("x = 1 | 4", "x = 5");
fold("x = 1 | 3", "x = 3");
fold("x = 1 | 1.1", "x = 1");
fold_same("x = 1 | 3E9");
fold("x = 1 | 3000000001", "x = -1294967295");
fold("x = 4294967295 | 0", "x = -1");
}
#[test]
#[ignore]
fn test_fold_bitwise_op2() {
fold("x = y & 1 & 1", "x = y & 1");
fold("x = y & 1 & 2", "x = y & 0");
fold("x = y & 3 & 1", "x = y & 1");
fold("x = 3 & y & 1", "x = y & 1");
fold("x = y & 3 & 3", "x = y & 3");
fold("x = 3 & y & 3", "x = y & 3");
fold("x = y | 1 | 1", "x = y | 1");
fold("x = y | 1 | 2", "x = y | 3");
fold("x = y | 3 | 1", "x = y | 3");
fold("x = 3 | y | 1", "x = y | 3");
fold("x = y | 3 | 3", "x = y | 3");
fold("x = 3 | y | 3", "x = y | 3");
fold("x = y ^ 1 ^ 1", "x = y ^ 0");
fold("x = y ^ 1 ^ 2", "x = y ^ 3");
fold("x = y ^ 3 ^ 1", "x = y ^ 2");
fold("x = 3 ^ y ^ 1", "x = y ^ 2");
fold("x = y ^ 3 ^ 3", "x = y ^ 0");
fold("x = 3 ^ y ^ 3", "x = y ^ 0");
fold("x = Infinity | NaN", "x=0");
fold("x = 12 | NaN", "x=12");
}
#[test]
fn test_issue_9256() {
// Returns -2 prior to fix (Number.MAX_VALUE)
fold("1.7976931348623157e+308 << 1", "0");
// Isn't changed prior to fix
fold("1.7976931348623157e+308 << 1.7976931348623157e+308", "0");
fold("1.7976931348623157e+308 >> 1.7976931348623157e+308", "0");
// Panics prior to fix (Number.MIN_VALUE)
fold("5e-324 >> 5e-324", "0");
fold("5e-324 << 5e-324", "0");
fold("5e-324 << 0", "0");
fold("0 << 5e-324", "0");
// Wasn't broken prior, used to ensure overflows are handled correctly
fold("1 << 31", "-2147483648");
fold("-8 >> 2", "-2");
fold("-8 >>> 2", "1073741822");
}
#[test]
#[ignore]
fn test_folding_mix_types_early() {
fold_same("x = x + '2'");
fold("x = +x + +'2'", "x = +x + 2");
fold("x = x - '2'", "x = x - 2");
fold("x = x ^ '2'", "x = x ^ 2");
fold("x = '2' ^ x", "x = 2 ^ x");
fold("x = '2' & x", "x = 2 & x");
fold("x = '2' | x", "x = 2 | x");
fold("x = '2' | y", "x=2|y");
fold("x = y | '2'", "x=y|2");
fold("x = y | (a && '2')", "x=y|(a&&2)");
fold("x = y | (a,'2')", "x=y|(a,2)");
fold("x = y | (a?'1':'2')", "x=y|(a?1:2)");
fold("x = y | ('x'?'1':'2')", "x=y|('x'?1:2)");
}
#[test]
fn test_folding_add1() {
fold("x = null + true", "x=1");
fold_same("x = a + true");
}
#[test]
fn test_folding_add2() {
fold("x = false + []", "x=\"false\"");
fold("x = [] + true", "x=\"true\"");
fold("NaN + []", "\"NaN\"");
}
#[test]
fn test_fold_bitwise_op_string_compare() {
fold("x = -1 | 0", "x = -1");
}
#[test]
fn test_fold_bit_shifts() {
fold("x = 1 << 0", "x = 1");
fold("x = -1 << 0", "x = -1");
fold("x = 1 << 1", "x = 2");
fold("x = 3 << 1", "x = 6");
fold("x = 1 << 8", "x = 256");
fold("x = 1 >> 0", "x = 1");
fold("x = -1 >> 0", "x = -1");
fold("x = 1 >> 1", "x = 0");
fold("x = 2 >> 1", "x = 1");
fold("x = 5 >> 1", "x = 2");
fold("x = 127 >> 3", "x = 15");
fold("x = 3 >> 1", "x = 1");
fold("x = 3 >> 2", "x = 0");
fold("x = 10 >> 1", "x = 5");
fold("x = 10 >> 2", "x = 2");
fold("x = 10 >> 5", "x = 0");
fold("x = 10 >>> 1", "x = 5");
fold("x = 10 >>> 2", "x = 2");
fold("x = 10 >>> 5", "x = 0");
fold("x = -1 >>> 1", "x = 2147483647"); // 0x7fffffff
fold("x = -1 >>> 0", "x = 4294967295"); // 0xffffffff
fold("x = -2 >>> 0", "x = 4294967294"); // 0xfffffffe
fold("x = 0x90000000 >>> 28", "x = 9");
fold("x = 0xffffffff << 0", "x = -1");
fold("x = 0xffffffff << 4", "x = -16");
fold("1 << 32", "1");
fold("1 << -1", "-2147483648");
fold("1 >> 32", "1");
}
#[test]
fn test_fold_bit_shifts_string_compare() {
fold("x = -1 << 1", "x = -2");
fold("x = -1 << 8", "x = -256");
fold("x = -1 >> 1", "x = -1");
fold("x = -2 >> 1", "x = -1");
fold("x = -1 >> 0", "x = -1");
}
#[test]
#[ignore]
fn test_string_add() {
fold("x = 'a' + 'bc'", "x = 'abc'");
fold("x = 'a' + 5", "x = 'a5'");
fold("x = 5 + 'a'", "x = '5a'");
fold("x = 'a' + ''", "x = 'a'");
fold("x = 'a' + foo()", "x = 'a'+foo()");
fold("x = foo() + 'a' + 'b'", "x = foo()+'ab'");
fold("x = (foo() + 'a') + 'b'", "x = foo()+'ab'"); // believe it!
fold(
"x = foo() + 'a' + 'b' + 'cd' + bar()",
"x = foo()+'abcd'+bar()",
);
fold("x = foo() + 2 + 'b'", "x = foo()+2+\"b\""); // don't fold!
fold("x = foo() + 'a' + 2", "x = foo()+\"a2\"");
fold("x = '' + null", "x = 'null'");
fold("x = true + '' + false", "x = 'truefalse'");
fold("x = '' + []", "x = ''");
fold("x = foo() + 'a' + 1 + 1", "x = foo() + 'a11'");
fold("x = 1 + 1 + 'a'", "x = '2a'");
fold("x = 1 + 1 + 'a'", "x = '2a'");
fold("x = 'a' + (1 + 1)", "x = 'a2'");
fold("x = '_' + p1 + '_' + ('' + p2)", "x = '_' + p1 + '_' + p2");
fold("x = 'a' + ('_' + 1 + 1)", "x = 'a_11'");
fold("x = 'a' + ('_' + 1) + 1", "x = 'a_11'");
fold("x = 1 + (p1 + '_') + ('' + p2)", "x = 1 + (p1 + '_') + p2");
fold("x = 1 + p1 + '_' + ('' + p2)", "x = 1 + p1 + '_' + p2");
fold("x = 1 + 'a' + p1", "x = '1a' + p1");
fold("x = (p1 + (p2 + 'a')) + 'b'", "x = (p1 + (p2 + 'ab'))");
fold("'a' + ('b' + p1) + 1", "'ab' + p1 + 1");
fold("x = 'a' + ('b' + p1 + 'c')", "x = 'ab' + (p1 + 'c')");
fold_same("x = 'a' + (4 + p1 + 'a')");
fold_same("x = p1 / 3 + 4");
fold_same("foo() + 3 + 'a' + foo()");
fold_same("x = 'a' + ('b' + p1 + p2)");
fold_same("x = 1 + ('a' + p1)");
fold_same("x = p1 + '' + p2");
fold_same("x = 'a' + (1 + p1)");
fold_same("x = (p2 + 'a') + (1 + p1)");
fold_same("x = (p2 + 'a') + (1 + p1 + p2)");
fold_same("x = (p2 + 'a') + (1 + (p1 + p2))");
}
#[test]
fn test_issue821() {
fold_same("var a =(Math.random()>0.5? '1' : 2 ) + 3 + 4;");
fold_same("var a = ((Math.random() ? 0 : 1) || (Math.random()>0.5? '1' : 2 )) + 3 + 4;");
}
#[test]
fn test_fold_arithmetic() {
fold("x = 10 + 20", "x = 30");
fold("x = 2 / 4", "x = 0.5");
fold("x = 2.25 * 3", "x = 6.75");
fold_same("z = x * y");
fold_same("x = y * 5");
fold_same("x = 1 / 0");
fold("x = 3 % 2", "x = 1");
fold("x = 3 % -2", "x = 1");
fold("x = -1 % 3", "x = -1");
fold_same("x = 1 % 0");
fold("x = 2 ** 3", "x = 8");
// fold("x = 2 ** -3", "x = 0.125");
fold_same("x = 2 ** 55"); // backs off folding because 2 ** 55 is too large
fold_same("x = 3 ** -1"); // backs off because 3**-1 is shorter than
// 0.3333333333333333
}
#[test]
fn test_fold_arithmetic2() {
fold_same("x = y + 10 + 20");
fold_same("x = y / 2 / 4");
fold("x = y * 2.25 * 3", "x = y * 6.75");
fold_same("z = x * y");
fold_same("x = y * 5");
fold("x = y + (z * 24 * 60 * 60 * 1000)", "x = y + z * 86400000");
}
#[test]
fn test_fold_arithmetic3() {
fold("x = null * undefined", "x = NaN");
fold("x = null * 1", "x = 0");
fold("x = (null - 1) * 2", "x = -2");
fold("x = (null + 1) * 2", "x = 2");
fold("x = null ** 0", "x = 1");
}
#[test]
#[ignore]
fn test_fold_arithmetic3_2() {
fold("x = (-0) ** 3", "x = -0.0");
}
#[test]
fn test_fold_arithmetic_infinity() {
fold("x=-Infinity-2", "x=-Infinity");
fold("x=Infinity-2", "x=Infinity");
fold("x=Infinity*5", "x=Infinity");
fold("x = Infinity ** 2", "x = Infinity");
fold("x = Infinity ** -2", "x = 0");
}
#[test]
fn test_fold_arithmetic_string_comp() {
fold("x = 10 - 20", "x = -10");
}
#[test]
fn test_fold_comparison() {
fold("x = 0 == 0", "x = true");
fold("x = 1 == 2", "x = false");
fold("x = 'abc' == 'def'", "x = false");
fold("x = 'abc' == 'abc'", "x = true");
fold("x = \"\" == ''", "x = true");
fold("x = foo() == bar()", "x = foo()==bar()");
fold("x = 1 != 0", "x = true");
fold("x = 'abc' != 'def'", "x = true");
fold("x = 'a' != 'a'", "x = false");
fold("x = 1 < 20", "x = true");
fold("x = 3 < 3", "x = false");
fold("x = 10 > 1.0", "x = true");
fold("x = 10 > 10.25", "x = false");
fold("x = y == y", "x = y==y"); // Maybe foldable given type information
fold("x = y < y", "x = false");
fold("x = y > y", "x = false");
fold("x = 1 <= 1", "x = true");
fold("x = 1 <= 0", "x = false");
fold("x = 0 >= 0", "x = true");
fold("x = -1 >= 9", "x = false");
fold("x = true == true", "x = true");
fold("x = false == false", "x = true");
fold("x = false == null", "x = false");
fold("x = false == true", "x = false");
fold("x = true == null", "x = false");
fold("0 == 0", "true");
fold("1 == 2", "false");
fold("'abc' == 'def'", "false");
fold("'abc' == 'abc'", "true");
fold("\"\" == ''", "true");
fold_same("foo() == bar()");
fold("1 != 0", "true");
fold("'abc' != 'def'", "true");
fold("'a' != 'a'", "false");
fold("1 < 20", "true");
fold("3 < 3", "false");
fold("10 > 1.0", "true");
fold("10 > 10.25", "false");
fold_same("x == x");
fold("x < x", "false");
fold("x > x", "false");
fold("1 <= 1", "true");
fold("1 <= 0", "false");
fold("0 >= 0", "true");
fold("-1 >= 9", "false");
fold("true == true", "true");
fold("false == null", "false");
fold("false == true", "false");
fold("true == null", "false");
}
// ===, !== comparison tests
#[test]
fn test_fold_comparison2() {
fold("x = 0 === 0", "x = true");
fold("x = 1 === 2", "x = false");
fold("x = 'abc' === 'def'", "x = false");
fold("x = 'abc' === 'abc'", "x = true");
fold("x = \"\" === ''", "x = true");
fold("x = foo() === bar()", "x = foo()===bar()");
fold("x = 1 !== 0", "x = true");
fold("x = 'abc' !== 'def'", "x = true");
fold("x = 'a' !== 'a'", "x = false");
fold("x = y === y", "x = y===y");
fold("x = true === true", "x = true");
fold("x = false === false", "x = true");
fold("x = false === null", "x = false");
fold("x = false === true", "x = false");
fold("x = true === null", "x = false");
fold("0 === 0", "true");
fold("1 === 2", "false");
fold("'abc' === 'def'", "false");
fold("'abc' === 'abc'", "true");
fold("\"\" === ''", "true");
fold_same("foo() === bar()");
fold("1 === '1'", "false");
fold("1 === true", "false");
fold("1 !== '1'", "true");
fold("1 !== true", "true");
fold("1 !== 0", "true");
fold("'abc' !== 'def'", "true");
fold("'a' !== 'a'", "false");
fold_same("x === x");
fold("true === true", "true");
fold("false === null", "false");
fold("false === true", "false");
fold("true === null", "false");
}
#[test]
fn test_fold_comparison3() {
fold("x = !1 == !0", "x = false");
fold("x = !0 == !0", "x = true");
fold("x = !1 == !1", "x = true");
fold("x = !1 == null", "x = false");
fold("x = !1 == !0", "x = false");
fold("x = !0 == null", "x = false");
fold("!0 == !0", "true");
fold("!1 == null", "false");
fold("!1 == !0", "false");
fold("!0 == null", "false");
fold("x = !0 === !0", "x = true");
fold("x = !1 === !1", "x = true");
fold("x = !1 === null", "x = false");
fold("x = !1 === !0", "x = false");
fold("x = !0 === null", "x = false");
fold("!0 === !0", "true");
fold("!1 === null", "false");
fold("!1 === !0", "false");
fold("!0 === null", "false");
}
#[test]
fn test_fold_comparison4() {
fold_same("[] == false"); // true
fold_same("[] == true"); // false
fold_same("[0] == false"); // true
fold_same("[0] == true"); // false
fold_same("[1] == false"); // false
fold_same("[1] == true"); // true
fold_same("({}) == false"); // false
fold_same("({}) == true"); // true
}
#[test]
fn test_fold_get_elem1() {
fold("x = [,10][0]", "x = (0, void 0);");
fold("x = [10, 20][0]", "x = (0, 10);");
fold("x = [10, 20][1]", "x = (0, 20);");
// fold("x = [10, 20][-1]", "x = void 0;");
// fold("x = [10, 20][2]", "x = void 0;");
fold("x = [foo(), 0][1]", "x = (foo(), 0);");
fold("x = [0, foo()][1]", "x = (0, foo());");
// fold("x = [0, foo()][0]", "x = (foo(), 0)");
fold_same("for([1][0] in {});");
}
#[test]
fn test_fold_get_elem2_1() {
fold("x = 'string'[5]", "x = \"g\"");
fold("x = 'string'[0]", "x = \"s\"");
fold("x = 's'[0]", "x = \"s\"");
fold("x = '\\uD83D\\uDCA9'[0]", "x = \"\\uD83D\"");
fold("x = '\\uD83D\\uDCA9'[1]", "x = \"\\uDCA9\"");
}
#[test]
#[ignore]
fn test_fold_get_elem2_2() {
fold("x = 'string'[-1]", "x = void 0;");
fold("x = 'string'[6]", "x = void 0;");
}
#[test]
fn test_fold_array_lit_spread_get_elem() {
fold("x = [...[0 ]][0]", "x = (0, 0);");
fold("x = [0, 1, ...[2, 3, 4]][3]", "x = (0, 3);");
fold("x = [...[0, 1], 2, ...[3, 4]][3]", "x = (0, 3);");
fold("x = [...[...[0, 1], 2, 3], 4][0]", "x = (0, 0);");
fold("x = [...[...[0, 1], 2, 3], 4][3]", "x = (0, 3);");
// fold("x = [...[]][100]", "x = void 0;");
// fold("x = [...[0]][100]", "x = void 0;");
}
#[test]
fn test_dont_fold_non_literal_spread_get_elem() {
fold_same("x = [...iter][0];");
fold_same("x = [0, 1, ...iter][2];");
// `...iter` could have side effects, so don't replace `x` with `0`
fold_same("x = [0, 1, ...iter][0];");
}
#[test]
fn test_fold_array_spread() {
fold("x = [...[]]", "x = []");
fold("x = [0, ...[], 1]", "x = [0, 1]");
fold("x = [...[0, 1], 2, ...[3, 4]]", "x = [0, 1, 2, 3, 4]");
fold("x = [...[...[0], 1], 2]", "x = [0, 1, 2]");
fold_same("[...[x]] = arr");
}
#[test]
#[ignore]
fn test_fold_object_lit_spread_get_prop() {
fold("x = {...{a}}.a", "x = a;");
fold("x = {a, b, ...{c, d, e}}.d", "x = d;");
fold("x = {...{a, b}, c, ...{d, e}}.d", "x = d;");
fold("x = {...{...{a, b}, c, d}, e}.a", "x = a");
fold("x = {...{...{a, b}, c, d}, e}.d", "x = d");
}
#[test]
#[ignore]
fn test_dont_fold_non_literal_object_spread_get_prop_getters_impure() {
fold_same("x = {...obj}.a;");
fold_same("x = {a, ...obj, c}.a;");
fold_same("x = {a, ...obj, c}.c;");
}
#[test]
fn test_fold_object_spread() {
fold("x = {...{}}", "x = {}");
fold("x = {a, ...{}, b}", "x = {a, b}");
fold("x = {...{a, b}, c, ...{d, e}}", "x = {a, b, c, d, e}");
fold("x = {...{...{a}, b}, c}", "x = {a, b, c}");
fold_same("({...{x}} = obj)");
}
#[test]
#[ignore]
fn test_dont_fold_mixed_object_and_array_spread() {
fold_same("x = [...{}]");
fold_same("x = {...[]}");
fold("x = [a, ...[...{}]]", "x = [a, ...{}]");
fold("x = {a, ...{...[]}}", "x = {a, ...[]}");
}
#[test]
fn test_fold_complex() {
fold("x = (3 / 1.0) + (1 * 2)", "x = 5");
fold("x = (1 == 1.0) && foo() && true", "x = foo()&&true");
fold("x = 'abc' + 5 + 10", "x = \"abc510\"");
}
#[test]
#[ignore]
fn test_fold_left() {
fold_same("(+x - 1) + 2"); // not yet
fold("(+x + 1) + 2", "+x + 3");
}
#[test]
fn test_fold_array_length() {
// Can fold
fold("x = [].length", "x = 0");
fold("x = [1,2,3].length", "x = 3");
fold("x = [a,b].length", "x = 2");
// Not handled yet
fold("x = [,,1].length", "x = 3");
// Cannot fold
fold("x = [foo(), 0].length", "x = [foo(),0].length");
fold_same("x = y.length");
}
#[test]
fn test_fold_string_length() {
// Can fold basic strings.
fold("x = ''.length", "x = 0");
fold("x = '123'.length", "x = 3");
// Test Unicode escapes are accounted for.
fold("x = '123\\u01dc'.length", "x = 4");
}
#[test]
fn test_fold_typeof() {
fold("x = typeof 1", "x = \"number\"");
fold("x = typeof 'foo'", "x = \"string\"");
fold("x = typeof true", "x = \"boolean\"");
fold("x = typeof false", "x = \"boolean\"");
fold("x = typeof null", "x = \"object\"");
fold("x = typeof undefined", "x = \"undefined\"");
fold("x = typeof void 0", "x = \"undefined\"");
fold("x = typeof []", "x = \"object\"");
fold("x = typeof [1]", "x = \"object\"");
fold("x = typeof [1,[]]", "x = \"object\"");
fold("x = typeof {}", "x = \"object\"");
fold("x = typeof function() {}", "x = \"function\"");
fold_same("x = typeof[1,[foo()]]");
fold_same("x = typeof{bathwater:baby()}");
}
#[test]
fn test_fold_instance_of() {
// Non object types are never instances of anything.
fold("64 instanceof Object", "false");
fold("64 instanceof Number", "false");
fold("'' instanceof Object", "false");
fold("'' instanceof String", "false");
fold("true instanceof Object", "false");
fold("true instanceof Boolean", "false");
fold("!0 instanceof Object", "false");
fold("!0 instanceof Boolean", "false");
fold("false instanceof Object", "false");
fold("null instanceof Object", "false");
fold("undefined instanceof Object", "false");
fold("NaN instanceof Object", "false");
fold("Infinity instanceof Object", "false");
// Array and object literals are known to be objects.
fold("[] instanceof Object", "true");
fold("({}) instanceof Object", "true");
// 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");
fold("(function() {}) instanceof Object", "true");
// An unknown value should never be folded.
fold_same("x instanceof Foo");
fold_same("x instanceof Object");
}
#[test]
fn test_division() {
// Make sure the 1/3 does not expand to 0.333333
fold_same("print(1/3)");
// Decimal form is preferable to fraction form when strings are the
// same length.
fold("print(1/2)", "print(0.5)");
}
#[test]
fn test_assign_ops_early() {
fold_same("x=x+y");
fold_same("x=y+x");
fold_same("x=x*y");
fold_same("x=y*x");
fold_same("x.y=x.y+z");
fold_same("next().x = next().x + 1");
fold_same("x=x-y");
fold_same("x=y-x");
fold_same("x=x|y");
fold_same("x=y|x");
fold_same("x=x*y");
fold_same("x=y*x");
fold_same("x=x**y");
fold_same("x=y**2");
fold_same("x.y=x.y+z");
fold_same("next().x = next().x + 1");
}
#[test]
#[ignore]
fn test_assign_ops_early_2() {
// This is OK, really.
fold("({a:1}).a = ({a:1}).a + 1", "({a:1}).a = 2");
}
#[test]
fn test_fold_add1() {
fold("x=false+1", "x=1");
fold("x=true+1", "x=2");
fold("x=1+false", "x=1");
fold("x=1+true", "x=2");
}
#[test]
fn test_fold_literal_names() {
fold("NaN == NaN", "false");
fold("Infinity == Infinity", "true");
fold("Infinity == NaN", "false");
fold("undefined == NaN", "false");
fold("undefined == Infinity", "false");
fold("Infinity >= Infinity", "true");
fold("NaN >= NaN", "false");
}
#[test]
fn test_fold_literals_type_mismatches() {
fold("true == true", "true");
fold("true == false", "false");
fold("true == null", "false");
fold("false == null", "false");
// relational operators convert its operands
fold("null <= null", "true"); // 0 = 0
fold("null >= null", "true");
fold("null > null", "false");
fold("null < null", "false");
fold("false >= null", "true"); // 0 = 0
fold("false <= null", "true");
fold("false > null", "false");
fold("false < null", "false");
fold("true >= null", "true"); // 1 > 0
fold("true <= null", "false");
fold("true > null", "true");
fold("true < null", "false");
fold("true >= false", "true"); // 1 > 0
fold("true <= false", "false");
fold("true > false", "true");
fold("true < false", "false");
}
#[test]
#[ignore]
fn test_fold_left_child_concat() {
fold_same("x +5 + \"1\"");
fold("x+\"5\" + \"1\"", "x + \"51\"");
// fold("\"a\"+(c+\"b\")", "\"a\"+c+\"b\"");
fold("\"a\"+(\"b\"+c)", "\"ab\"+c");
}
#[test]
#[ignore]
fn test_fold_left_child_op() {
fold("x * Infinity * 2", "x * Infinity");
fold_same("x - Infinity - 2"); // want "x-Infinity"
fold_same("x - 1 + Infinity");
fold_same("x - 2 + 1");
fold_same("x - 2 + 3");
fold_same("1 + x - 2 + 1");
fold_same("1 + x - 2 + 3");
fold_same("1 + x - 2 + 3 - 1");
fold_same("f(x)-0");
fold("x-0-0", "x-0");
fold_same("x+2-2+2");
fold_same("x+2-2+2-2");
fold_same("x-2+2");
fold_same("x-2+2-2");
fold_same("x-2+2-2+2");
fold_same("1+x-0-NaN");
fold_same("1+f(x)-0-NaN");
fold_same("1+x-0+NaN");
fold_same("1+f(x)-0+NaN");
fold_same("1+x+NaN"); // unfoldable
fold_same("x+2-2"); // unfoldable
fold_same("x+2"); // nothing to do
fold_same("x-2"); // nothing to do
}
#[test]
fn test_fold_simple_arithmetic_op() {
fold_same("x*NaN");
fold_same("NaN/y");
fold_same("f(x)-0");
fold_same("f(x)*1");
fold_same("1*f(x)");
fold_same("0+a+b");
fold_same("0-a-b");
fold_same("a+b-0");
fold_same("(1+x)*NaN");
fold_same("(1+f(x))*NaN"); // don't fold side-effects
}
#[test]
#[ignore]
fn test_fold_literals_as_numbers() {
fold("x/'12'", "x/12");
fold("x/('12'+'6')", "x/126");
fold("true*x", "1*x");
fold("x/false", "x/0"); // should we add an error check? :)
}
#[test]
fn test_fold_arithmetic_with_strings() {
// Left side of expression is a string
fold("'10' - 5", "5");
fold("'4' / 2", "2");
fold("'11' % 2", "1");
fold("'10' ** 2", "100");
fold("'Infinity' * 2", "Infinity");
fold("'NaN' * 2", "NaN");
// Right side of expression is a string
fold("10 - '5'", "5");
fold("4 / '2'", "2");
fold("11 % '2'", "1");
fold("10 ** '2'", "100");
fold("2 * 'Infinity'", "Infinity");
fold("2 * 'NaN'", "NaN");
// Both sides are strings
fold("'10' - '5'", "5");
fold("'4' / '2'", "2");
fold("'11' % '2'", "1");
fold("'10' ** '2'", "100");
fold("'Infinity' * '2'", "Infinity");
fold("'NaN' * '2'", "NaN");
}
#[test]
fn test_not_fold_back_to_true_false() {
fold("!0", "!0");
fold("!1", "!1");
fold("!3", "!3");
}
#[test]
fn test_fold_bang_constants() {
fold("1 + !0", "2");
fold("1 + !1", "1");
fold("'a ' + !1", "\"a false\"");
fold("'a ' + !0", "\"a true\"");
}
#[test]
fn test_fold_mixed() {
fold("''+[1]", "\"1\"");
fold("false+[]", "\"false\"");
}
#[test]
fn test_fold_void() {
fold_same("void 0");
fold("void 1", "void 0");
fold("void x", "void 0");
fold_same("void x()");
}
#[test]
fn test_object_literal() {
fold("(!{})", "false");
fold("(!{a:1})", "false");
fold("(!{a:foo()})", "foo(), false;");
fold("(!{'a':foo()})", "foo(), false;");
}
#[test]
fn test_array_literal() {
fold("(![])", "false");
fold("(![1])", "false");
fold("(![a])", "false");
fold_same("foo(), false;");
}
#[test]
fn test_issue601() {
fold_same("'\\v' == 'v'");
fold_same("'v' == '\\v'");
fold_same("'\\u000B' == '\\v'");
}
#[test]
#[ignore]
fn test_fold_object_literal_ref1() {
// Leave extra side-effects in place
fold_same("var x = ({a:foo(),b:bar()}).a");
fold_same("var x = ({a:1,b:bar()}).a");
fold_same("function f() { return {b:foo(), a:2}.a; }");
// on the LHS the object act as a temporary leave it in place.
fold_same("({a:x}).a = 1");
fold("({a:x}).a += 1", "({a:x}).a = x + 1");
fold_same("({a:x}).a ++");
fold_same("({a:x}).a --");
// Getters should not be inlined.
fold_same("({get a() {return this}}).a");
// Except, if we can see that the getter function never references 'this'.
fold("({get a() {return 0}}).a", "(function() {return 0})()");
// It's okay to inline functions, as long as they're not immediately called.
// (For tests where they are immediately called, see
// testFoldObjectLiteralRefCall)
fold(
"({a:function(){return this}}).a",
"(function(){return this})",
);
// It's also okay to inline functions that are immediately called, so long as we
// know for sure the function doesn't reference 'this'.
fold("({a:function(){return 0}}).a()", "(function(){return 0})()");
// Don't inline setters.
fold_same("({set a(b) {return this}}).a");
fold_same("({set a(b) {this._a = b}}).a");
// Don't inline if there are side-effects.
fold_same("({[foo()]: 1, a: 0}).a");
fold_same("({['x']: foo(), a: 0}).a");
fold_same("({x: foo(), a: 0}).a");
// Leave unknown props alone, the might be on the prototype
fold_same("({}).a");
// setters by themselves don't provide a definition
fold_same("({}).a");
fold_same("({set a(b) {}}).a");
// sets don't hide other definitions.
fold("({a:1,set a(b) {}}).a", "1");
// get is transformed to a call (gets don't have self referential names)
fold("({get a() {}}).a", "(function (){})()");
// sets don't hide other definitions.
fold("({get a() {},set a(b) {}}).a", "(function (){})()");
// a function remains a function not a call.
fold(
"var x = ({a:function(){return 1}}).a",
"var x = function(){return 1}",
);
fold("var x = ({a:1}).a", "var x = 1");
fold("var x = ({a:1, a:2}).a", "var x = 2");
fold("var x = ({a:1, a:foo()}).a", "var x = foo()");
fold("var x = ({a:foo()}).a", "var x = foo()");
fold(
"function f() { return {a:1, b:2}.a; }",
"function f() { return 1; }",
);
// GETELEM is handled the same way.
fold("var x = ({'a':1})['a']", "var x = 1");
// try folding string computed properties
fold("var a = {['a']:x}['a']", "var a = x");
fold(
"var a = { get ['a']() { return 1; }}['a']",
"var a = function() { return 1; }();",
);
fold("var a = {'a': x, ['a']: y}['a']", "var a = y;");
fold_same("var a = {['foo']: x}.a;");
// Note: it may be useful to fold symbols in the future.
fold_same("var y = Symbol(); var a = {[y]: 3}[y];");
fold("var x = {a() { 1; }}.a;", "var x = function() { 1; };");
// Notice `a` isn't invoked, so behavior didn't change.
fold(
"var x = {a() { return this; }}.a;",
"var x = function() { return this; };",
);
// `super` is invisibly captures the object that declared the method so we can't
// fold.
fold_same("var x = {a() { return super.a; }}.a;");
fold(
"var x = {a: 1, a() { 2; }}.a;",
"var x = function() { 2; };",
);
fold("var x = {a() {}, a: 1}.a;", "var x = 1;");
fold_same("var x = {a() {}}.b");
}
#[test]
fn test_fold_object_literal_ref2() {
fold_same("({a:x}).a += 1");
}
// Regression test for https://github.com/google/closure-compiler/issues/2873
// It would be incorrect to fold this to "x();" because the 'this' value inside
// the function will be the global object, instead of the object {a:x} as it
// should be.
#[test]
fn test_fold_object_literal_method_call_non_literal_fn() {
fold_same("({a:x}).a()");
}
#[test]
#[ignore]
fn test_fold_object_literal_free_method_call() {
fold("({a() { return 1; }}).a()", "(function() { return 1; })()");
}
#[test]
#[ignore]
fn test_fold_object_literal_free_arrow_call_using_enclosing_this() {
fold("({a: () => this }).a()", "(() => this)()");
}
#[test]
fn test_fold_object_literal_unfree_method_call_due_to_this() {
fold_same("({a() { return this; }}).a()");
}
#[test]
fn test_fold_object_literal_unfree_method_call_due_to_super() {
fold_same("({a() { return super.toString(); }}).a()");
}
#[test]
fn test_fold_object_literal_param_to_invocation() {
fold("console.log({a: 1}.a)", "console.log(1)");
}
#[test]
fn test_ie_string() {
fold_same("!+'\\v1'");
}
#[test]
fn test_issue522() {
fold_same("[][1] = 1;");
}
#[test]
fn test_es6_features() {
fold(
"var x = {[undefined != true] : 1};",
"var x = {[true] : 1};",
);
fold("let x = false && y;", "let x = false;");
fold("const x = null == undefined", "const x = true");
fold(
"var [a, , b] = [false+1, true+1, ![]]",
"var [a, , b] = [1, 2, false]",
);
fold("var x = () => true || x;", "var x = () => true;");
fold(
"function foo(x = (1 !== void 0), y) {return x+y;}",
"function foo(x = true, y) {return x+y;}",
);
fold(
"class Foo { constructor() {this.x = null <= null;} }",
"class Foo { constructor() {this.x = true;}}",
);
fold(
"function foo() {return `${false && y}`}",
"function foo() {return `${false}`}",
);
}
#[test]
fn test_export_default_paren_expr() {
fold_same("import fn from './b'; export default (class fn1 {});");
fold_same("import fn from './b'; export default (function fn1 () {});");
fold("export default ((foo));", "export default foo;");
}
#[test]
fn test_issue_8747() {
// Index with a valid index.
fold("'a'[0]", "\"a\";");
fold("'a'['0']", "\"a\";");
// Index with an invalid index.
// An invalid index is an out-of-bound index. These are not replaced as
// prototype changes could cause undefined behaviour. Refer to
// pristine_globals in compress.
fold_same("'a'[0.5]");
fold_same("'a'[-1]");
fold_same("[1][0.5]");
fold_same("[1][-1]");
// Index with an expression.
fold("'a'[0 + []]", "\"a\";");
fold("[1][0 + []]", "0, 1;");
// Don't replace if side effects exist.
fold_same("[f(), f()][0]");
fold("[x(), 'x', 5][2]", "x(), 5;");
fold_same("({foo: f()}).foo");
// Index with length, resulting in replacement.
// Prototype changes don't affect .length in String and Array,
// but it is affected in Object.
fold("[].length", "0");
fold("[]['length']", "0");
fold("''.length", "0");
fold("''['length']", "0");
fold_same("({}).length");
fold_same("({})['length']");
fold("({length: 'foo'}).length", "'foo'");
fold("({length: 'foo'})['length']", "'foo'");
// Indexing objects has a few special cases that were broken that we test here.
fold("({0.5: 'a'})[0.5]", "'a';");
fold("({'0.5': 'a'})[0.5]", "'a';");
fold("({0.5: 'a'})['0.5']", "'a';");
// Indexing objects that have a spread operator in `__proto__` can still be
// optimized if the key comes before the `__proto__` object.
fold("({1: 'bar', __proto__: {...[1]}})[1]", "({...[1]}), 'bar';");
// Spread operator comes first, can't be evaluated.
fold_same("({...[1], 1: 'bar'})[1]");
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_optimization/src/simplify/inlining/mod.rs | Rust | use std::borrow::Cow;
use swc_common::{
pass::{CompilerPass, Repeated},
util::take::Take,
};
use swc_ecma_ast::*;
use swc_ecma_transforms_base::scope::IdentType;
use swc_ecma_utils::{contains_this_expr, find_pat_ids};
use swc_ecma_visit::{
noop_visit_mut_type, noop_visit_type, visit_mut_pass, visit_obj_and_computed, Visit, VisitMut,
VisitMutWith, VisitWith,
};
use tracing::{span, Level};
use self::scope::{Scope, ScopeKind, VarType};
mod scope;
#[derive(Debug, Default)]
pub struct Config {}
/// Note: this pass assumes that resolver is invoked before the pass.
///
/// As swc focuses on reducing gzipped file size, all strings are inlined.
///
///
/// # TODOs
///
/// - Handling of `void 0`
/// - Properly handle binary expressions.
/// - Track variables access by a function
///
/// Currently all functions are treated as a black box, and all the pass gives
/// up inlining variables across a function call or a constructor call.
pub fn inlining(_: Config) -> impl 'static + Repeated + CompilerPass + Pass + VisitMut {
visit_mut_pass(Inlining {
phase: Phase::Analysis,
is_first_run: true,
changed: false,
scope: Default::default(),
var_decl_kind: VarDeclKind::Var,
ident_type: IdentType::Ref,
in_test: false,
pat_mode: PatFoldingMode::VarDecl,
pass: Default::default(),
})
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Phase {
Analysis,
Inlining,
}
impl CompilerPass for Inlining<'_> {
fn name(&self) -> Cow<'static, str> {
Cow::Borrowed("inlining")
}
}
impl Repeated for Inlining<'_> {
fn changed(&self) -> bool {
self.changed
}
fn reset(&mut self) {
self.changed = false;
self.is_first_run = false;
self.pass += 1;
}
}
struct Inlining<'a> {
phase: Phase,
is_first_run: bool,
changed: bool,
scope: Scope<'a>,
var_decl_kind: VarDeclKind,
ident_type: IdentType,
in_test: bool,
pat_mode: PatFoldingMode,
pass: usize,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum PatFoldingMode {
Assign,
Param,
CatchParam,
VarDecl,
}
impl Inlining<'_> {
fn visit_with_child<T>(&mut self, kind: ScopeKind, node: &mut T)
where
T: 'static + for<'any> VisitMutWith<Inlining<'any>>,
{
self.with_child(kind, |child| {
node.visit_mut_children_with(child);
});
}
}
impl VisitMut for Inlining<'_> {
noop_visit_mut_type!();
fn visit_mut_arrow_expr(&mut self, node: &mut ArrowExpr) {
self.visit_with_child(ScopeKind::Fn { named: false }, node)
}
fn visit_mut_assign_expr(&mut self, e: &mut AssignExpr) {
tracing::trace!("{:?}; Fold<AssignExpr>", self.phase);
self.pat_mode = PatFoldingMode::Assign;
match e.op {
op!("=") => {
let mut v = WriteVisitor {
scope: &mut self.scope,
};
e.left.visit_with(&mut v);
e.right.visit_with(&mut v);
match &mut e.left {
AssignTarget::Simple(left) => {
//
if let SimpleAssignTarget::Member(ref left) = &*left {
tracing::trace!("Assign to member expression!");
let mut v = IdentListVisitor {
scope: &mut self.scope,
};
left.visit_with(&mut v);
e.right.visit_with(&mut v);
}
}
AssignTarget::Pat(p) => {
p.visit_mut_with(self);
}
}
}
_ => {
let mut v = IdentListVisitor {
scope: &mut self.scope,
};
e.left.visit_with(&mut v);
e.right.visit_with(&mut v)
}
}
e.right.visit_mut_with(self);
if self.scope.is_inline_prevented(&e.right) {
// Prevent inline for lhd
let ids: Vec<Id> = find_pat_ids(&e.left);
for id in ids {
self.scope.prevent_inline(&id);
}
return;
}
//
if let Some(i) = e.left.as_ident() {
let id = i.to_id();
self.scope.add_write(&id, false);
if let Some(var) = self.scope.find_binding(&id) {
if !var.is_inline_prevented() {
match *e.right {
Expr::Lit(..) | Expr::Ident(..) => {
*var.value.borrow_mut() = Some(*e.right.clone());
}
_ => {
*var.value.borrow_mut() = None;
}
}
}
}
}
}
fn visit_mut_block_stmt(&mut self, node: &mut BlockStmt) {
self.visit_with_child(ScopeKind::Block, node)
}
fn visit_mut_call_expr(&mut self, node: &mut CallExpr) {
node.callee.visit_mut_with(self);
if self.phase == Phase::Analysis {
if let Callee::Expr(ref callee) = node.callee {
self.scope.mark_this_sensitive(callee);
}
}
// args should not be inlined
node.args.visit_children_with(&mut WriteVisitor {
scope: &mut self.scope,
});
node.args.visit_mut_with(self);
self.scope.store_inline_barrier(self.phase);
}
fn visit_mut_catch_clause(&mut self, node: &mut CatchClause) {
self.with_child(ScopeKind::Block, move |child| {
child.pat_mode = PatFoldingMode::CatchParam;
node.param.visit_mut_with(child);
match child.phase {
Phase::Analysis => {
let ids: Vec<Id> = find_pat_ids(&node.param);
for id in ids {
child.scope.prevent_inline(&id);
}
}
Phase::Inlining => {}
}
node.body.visit_mut_with(child);
})
}
fn visit_mut_do_while_stmt(&mut self, node: &mut DoWhileStmt) {
{
node.test.visit_with(&mut IdentListVisitor {
scope: &mut self.scope,
});
}
node.test.visit_mut_with(self);
self.visit_with_child(ScopeKind::Loop, &mut node.body);
}
fn visit_mut_expr(&mut self, node: &mut Expr) {
node.visit_mut_children_with(self);
// Codes like
//
// var y;
// y = x;
// use(y)
//
// should be transformed to
//
// var y;
// x;
// use(x)
//
// We cannot know if this is possible while analysis phase
if self.phase == Phase::Inlining {
if let Expr::Assign(e @ AssignExpr { op: op!("="), .. }) = node {
if let Some(i) = e.left.as_ident() {
if let Some(var) = self.scope.find_binding_from_current(&i.to_id()) {
if var.is_undefined.get()
&& !var.is_inline_prevented()
&& !self.scope.is_inline_prevented(&e.right)
{
*var.value.borrow_mut() = Some(*e.right.clone());
var.is_undefined.set(false);
*node = *e.right.take();
return;
}
}
}
return;
}
}
if let Expr::Ident(ref i) = node {
let id = i.to_id();
if self.is_first_run {
if let Some(expr) = self.scope.find_constant(&id) {
self.changed = true;
let mut expr = expr.clone();
expr.visit_mut_with(self);
*node = expr;
return;
}
}
match self.phase {
Phase::Analysis => {
if self.in_test {
if let Some(var) = self.scope.find_binding(&id) {
match &*var.value.borrow() {
Some(Expr::Ident(..)) | Some(Expr::Lit(..)) => {}
_ => {
self.scope.prevent_inline(&id);
}
}
}
}
self.scope.add_read(&id);
}
Phase::Inlining => {
tracing::trace!("Trying to inline: {:?}", id);
let expr = if let Some(var) = self.scope.find_binding(&id) {
tracing::trace!("VarInfo: {:?}", var);
if !var.is_inline_prevented() {
let expr = var.value.borrow();
if let Some(expr) = &*expr {
tracing::debug!("Inlining: {:?}", id);
if *node != *expr {
self.changed = true;
}
Some(expr.clone())
} else {
tracing::debug!("Inlining: {:?} as undefined", id);
if var.is_undefined.get() {
*node = *Expr::undefined(i.span);
return;
} else {
tracing::trace!("Not a cheap expression");
None
}
}
} else {
tracing::trace!("Inlining is prevented");
None
}
} else {
None
};
if let Some(expr) = expr {
*node = expr;
}
}
}
}
if let Expr::Bin(b) = node {
match b.op {
BinaryOp::LogicalAnd | BinaryOp::LogicalOr => {
self.visit_with_child(ScopeKind::Cond, &mut b.right);
}
_ => {}
}
}
}
fn visit_mut_fn_decl(&mut self, node: &mut FnDecl) {
if self.phase == Phase::Analysis {
self.declare(
node.ident.to_id(),
None,
true,
VarType::Var(VarDeclKind::Var),
);
}
self.with_child(ScopeKind::Fn { named: true }, |child| {
child.pat_mode = PatFoldingMode::Param;
node.function.params.visit_mut_with(child);
match &mut node.function.body {
None => {}
Some(v) => {
v.visit_mut_children_with(child);
}
};
});
}
fn visit_mut_fn_expr(&mut self, node: &mut FnExpr) {
if let Some(ref ident) = node.ident {
self.scope.add_write(&ident.to_id(), true);
}
node.function.visit_mut_with(self)
}
fn visit_mut_for_in_stmt(&mut self, node: &mut ForInStmt) {
self.pat_mode = PatFoldingMode::Param;
node.left.visit_mut_with(self);
{
node.left.visit_with(&mut IdentListVisitor {
scope: &mut self.scope,
});
}
{
node.right.visit_with(&mut IdentListVisitor {
scope: &mut self.scope,
});
}
node.right.visit_mut_with(self);
self.visit_with_child(ScopeKind::Loop, &mut node.body);
}
fn visit_mut_for_of_stmt(&mut self, node: &mut ForOfStmt) {
self.pat_mode = PatFoldingMode::Param;
node.left.visit_mut_with(self);
{
node.left.visit_with(&mut IdentListVisitor {
scope: &mut self.scope,
});
}
{
node.right.visit_with(&mut IdentListVisitor {
scope: &mut self.scope,
});
}
node.right.visit_mut_with(self);
self.visit_with_child(ScopeKind::Loop, &mut node.body);
}
fn visit_mut_for_stmt(&mut self, node: &mut ForStmt) {
{
node.init.visit_with(&mut IdentListVisitor {
scope: &mut self.scope,
});
}
{
node.test.visit_with(&mut IdentListVisitor {
scope: &mut self.scope,
});
}
{
node.update.visit_with(&mut IdentListVisitor {
scope: &mut self.scope,
});
}
node.init.visit_mut_with(self);
node.test.visit_mut_with(self);
node.update.visit_mut_with(self);
self.visit_with_child(ScopeKind::Loop, &mut node.body);
if node.init.is_none() && node.test.is_none() && node.update.is_none() {
self.scope.store_inline_barrier(self.phase);
}
}
fn visit_mut_function(&mut self, node: &mut Function) {
self.with_child(ScopeKind::Fn { named: false }, move |child| {
child.pat_mode = PatFoldingMode::Param;
node.params.visit_mut_with(child);
match &mut node.body {
None => None,
Some(v) => {
v.visit_mut_children_with(child);
Some(())
}
};
})
}
fn visit_mut_if_stmt(&mut self, stmt: &mut IfStmt) {
let old_in_test = self.in_test;
self.in_test = true;
stmt.test.visit_mut_with(self);
self.in_test = old_in_test;
self.visit_with_child(ScopeKind::Cond, &mut stmt.cons);
self.visit_with_child(ScopeKind::Cond, &mut stmt.alt);
}
fn visit_mut_program(&mut self, program: &mut Program) {
let _tracing = span!(Level::ERROR, "inlining", pass = self.pass).entered();
let old_phase = self.phase;
self.phase = Phase::Analysis;
program.visit_mut_children_with(self);
tracing::trace!("Switching to Inlining phase");
// Inline
self.phase = Phase::Inlining;
program.visit_mut_children_with(self);
self.phase = old_phase;
}
fn visit_mut_new_expr(&mut self, node: &mut NewExpr) {
node.callee.visit_mut_with(self);
if self.phase == Phase::Analysis {
self.scope.mark_this_sensitive(&node.callee);
}
node.args.visit_mut_with(self);
self.scope.store_inline_barrier(self.phase);
}
fn visit_mut_pat(&mut self, node: &mut Pat) {
node.visit_mut_children_with(self);
if let Pat::Ident(ref i) = node {
match self.pat_mode {
PatFoldingMode::Param => {
self.declare(
i.to_id(),
Some(Cow::Owned(Ident::from(i).into())),
false,
VarType::Param,
);
}
PatFoldingMode::CatchParam => {
self.declare(
i.to_id(),
Some(Cow::Owned(Ident::from(i).into())),
false,
VarType::Var(VarDeclKind::Var),
);
}
PatFoldingMode::VarDecl => {}
PatFoldingMode::Assign => {
if self.scope.find_binding_from_current(&i.to_id()).is_some() {
} else {
self.scope.add_write(&i.to_id(), false);
}
}
}
}
}
fn visit_mut_stmts(&mut self, items: &mut Vec<Stmt>) {
let old_phase = self.phase;
match old_phase {
Phase::Analysis => {
items.visit_mut_children_with(self);
}
Phase::Inlining => {
self.phase = Phase::Analysis;
items.visit_mut_children_with(self);
// Inline
self.phase = Phase::Inlining;
items.visit_mut_children_with(self);
self.phase = old_phase
}
}
}
fn visit_mut_switch_case(&mut self, node: &mut SwitchCase) {
self.visit_with_child(ScopeKind::Block, node)
}
fn visit_mut_try_stmt(&mut self, node: &mut TryStmt) {
node.block.visit_with(&mut IdentListVisitor {
scope: &mut self.scope,
});
node.handler.visit_mut_with(self)
}
fn visit_mut_unary_expr(&mut self, node: &mut UnaryExpr) {
if let op!("delete") = node.op {
let mut v = IdentListVisitor {
scope: &mut self.scope,
};
node.arg.visit_with(&mut v);
return;
}
node.visit_mut_children_with(self)
}
fn visit_mut_update_expr(&mut self, node: &mut UpdateExpr) {
let mut v = IdentListVisitor {
scope: &mut self.scope,
};
node.arg.visit_with(&mut v);
}
fn visit_mut_var_decl(&mut self, decl: &mut VarDecl) {
self.var_decl_kind = decl.kind;
decl.visit_mut_children_with(self)
}
fn visit_mut_var_declarator(&mut self, node: &mut VarDeclarator) {
let kind = VarType::Var(self.var_decl_kind);
node.init.visit_mut_with(self);
self.pat_mode = PatFoldingMode::VarDecl;
match self.phase {
Phase::Analysis => {
if let Pat::Ident(ref name) = node.name {
//
match &node.init {
None => {
if self.var_decl_kind != VarDeclKind::Const {
self.declare(name.to_id(), None, true, kind);
}
}
// Constants
Some(e)
if (e.is_lit() || e.is_ident())
&& self.var_decl_kind == VarDeclKind::Const =>
{
if self.is_first_run {
self.scope
.constants
.insert(name.to_id(), Some((**e).clone()));
}
}
Some(..) if self.var_decl_kind == VarDeclKind::Const => {
if self.is_first_run {
self.scope.constants.insert(name.to_id(), None);
}
}
// Bindings
Some(e) | Some(e) if e.is_lit() || e.is_ident() => {
self.declare(name.to_id(), Some(Cow::Borrowed(e)), false, kind);
if self.scope.is_inline_prevented(e) {
self.scope.prevent_inline(&name.to_id());
}
}
Some(ref e) => {
if self.var_decl_kind != VarDeclKind::Const {
self.declare(name.to_id(), Some(Cow::Borrowed(e)), false, kind);
if contains_this_expr(&node.init) {
self.scope.prevent_inline(&name.to_id());
return;
}
}
}
}
}
}
Phase::Inlining => {
if let Pat::Ident(ref name) = node.name {
if self.var_decl_kind != VarDeclKind::Const {
let id = name.to_id();
tracing::trace!("Trying to optimize variable declaration: {:?}", id);
if self.scope.is_inline_prevented(&Ident::from(name).into())
|| !self.scope.has_same_this(&id, node.init.as_deref())
{
tracing::trace!("Inline is prevented for {:?}", id);
return;
}
let mut init = node.init.take();
init.visit_mut_with(self);
tracing::trace!("\tInit: {:?}", init);
if let Some(init) = &init {
if let Expr::Ident(ri) = &**init {
self.declare(
name.to_id(),
Some(Cow::Owned(ri.clone().into())),
false,
kind,
);
}
}
if let Some(ref e) = init {
if self.scope.is_inline_prevented(e) {
tracing::trace!(
"Inlining is not possible as inline of the initialization was \
prevented"
);
node.init = init;
self.scope.prevent_inline(&name.to_id());
return;
}
}
let e = match init {
None => None,
Some(e) if e.is_lit() || e.is_ident() => Some(e),
Some(e) => {
let e = *e;
if self.scope.is_inline_prevented(&Ident::from(name).into()) {
node.init = Some(Box::new(e));
return;
}
if let Some(cnt) = self.scope.read_cnt(&name.to_id()) {
if cnt == 1 {
Some(Box::new(e))
} else {
node.init = Some(Box::new(e));
return;
}
} else {
node.init = Some(Box::new(e));
return;
}
}
};
// tracing::trace!("({}): Inserting {:?}", self.scope.depth(),
// name.to_id());
self.declare(name.to_id(), e.map(|e| Cow::Owned(*e)), false, kind);
return;
}
}
}
}
node.name.visit_mut_with(self);
}
fn visit_mut_while_stmt(&mut self, node: &mut WhileStmt) {
{
node.test.visit_with(&mut IdentListVisitor {
scope: &mut self.scope,
});
}
node.test.visit_mut_with(self);
self.visit_with_child(ScopeKind::Loop, &mut node.body);
}
}
#[derive(Debug)]
struct IdentListVisitor<'a, 'b> {
scope: &'a mut Scope<'b>,
}
impl Visit for IdentListVisitor<'_, '_> {
noop_visit_type!();
visit_obj_and_computed!();
fn visit_ident(&mut self, node: &Ident) {
self.scope.add_write(&node.to_id(), true);
}
}
/// Mark idents as `written`.
struct WriteVisitor<'a, 'b> {
scope: &'a mut Scope<'b>,
}
impl Visit for WriteVisitor<'_, '_> {
noop_visit_type!();
visit_obj_and_computed!();
fn visit_ident(&mut self, node: &Ident) {
self.scope.add_write(&node.to_id(), false);
}
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_optimization/src/simplify/inlining/scope.rs | Rust | #![allow(dead_code)]
use std::{
borrow::Cow,
cell::{Cell, RefCell},
collections::VecDeque,
};
use indexmap::map::{Entry, IndexMap};
use rustc_hash::{FxBuildHasher, FxHashMap, FxHashSet};
use swc_ecma_ast::*;
use swc_ecma_transforms_base::ext::ExprRefExt;
use tracing::{span, Level};
use super::{Inlining, Phase};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ScopeKind {
/// If / Switch
Cond,
Loop,
Block,
Fn {
named: bool,
},
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum VarType {
Param,
Var(VarDeclKind),
}
impl Default for ScopeKind {
fn default() -> Self {
Self::Fn { named: false }
}
}
impl Inlining<'_> {
pub(super) fn with_child<F>(&mut self, kind: ScopeKind, op: F)
where
F: for<'any> FnOnce(&mut Inlining<'any>),
{
let (unresolved_usages, bindings) = {
let mut child = Inlining {
phase: self.phase,
is_first_run: self.is_first_run,
changed: false,
scope: Scope::new(Some(&self.scope), kind),
var_decl_kind: VarDeclKind::Var,
ident_type: self.ident_type,
pat_mode: self.pat_mode,
in_test: self.in_test,
pass: self.pass,
};
op(&mut child);
self.changed |= child.changed;
(child.scope.unresolved_usages, child.scope.bindings)
};
tracing::trace!("propagating variables");
self.scope.unresolved_usages.extend(unresolved_usages);
if !matches!(kind, ScopeKind::Fn { .. }) {
let v = bindings;
for (id, v) in v.into_iter().filter_map(|(id, v)| {
if v.kind == VarType::Var(VarDeclKind::Var) {
Some((id, v))
} else {
None
}
}) {
let v: VarInfo = v;
tracing::trace!("Hoisting a variable {:?}", id);
if self.scope.unresolved_usages.contains(&id) {
v.inline_prevented.set(true)
}
v.hoisted.set(true);
*v.value.borrow_mut() = None;
v.is_undefined.set(false);
self.scope.bindings.insert(id, v);
}
}
}
/// Note: this method stores the value only if init is [Cow::Owned] or it's
/// [Expr::Ident] or [Expr::Lit].
pub(super) fn declare(
&mut self,
id: Id,
init: Option<Cow<Expr>>,
is_change: bool,
kind: VarType,
) {
tracing::trace!(
"({}, {:?}) declare({})",
self.scope.depth(),
self.phase,
id.0
);
let init = init.map(|cow| match cow {
Cow::Owned(v) => Cow::Owned(v),
Cow::Borrowed(b) => match b {
Expr::Ident(..) | Expr::Lit(..) => Cow::Owned(b.clone()),
_ => Cow::Borrowed(b),
},
});
let is_undefined = self.var_decl_kind == VarDeclKind::Var
&& !is_change
&& init.is_none()
&& self.phase == Phase::Inlining;
let mut alias_of = None;
let value_idx = match init.as_deref() {
Some(Expr::Ident(vi)) => {
if let Some((value_idx, value_var)) = self.scope.idx_val(&vi.to_id()) {
alias_of = Some(value_var.kind);
Some((value_idx, vi.to_id()))
} else {
None
}
}
_ => None,
};
let is_inline_prevented = self.scope.should_prevent_inline_because_of_scope(&id)
|| match init {
Some(ref e) => self.scope.is_inline_prevented(e),
_ => false,
};
if is_inline_prevented {
tracing::trace!("\tdeclare: Inline prevented: {:?}", id)
}
if is_undefined {
tracing::trace!("\tdeclare: {:?} is undefined", id);
}
let idx = match self.scope.bindings.entry(id.clone()) {
Entry::Occupied(mut e) => {
e.get().is_undefined.set(is_undefined);
e.get().read_cnt.set(0);
e.get().read_from_nested_scope.set(false);
match init {
Some(Cow::Owned(v)) => e.get_mut().value = RefCell::new(Some(v)),
None => e.get_mut().value = RefCell::new(None),
_ => {}
}
e.get().inline_prevented.set(is_inline_prevented);
e.index()
}
Entry::Vacant(e) => {
let idx = e.index();
e.insert(VarInfo {
kind,
alias_of,
read_from_nested_scope: Cell::new(false),
read_cnt: Cell::new(0),
inline_prevented: Cell::new(is_inline_prevented),
is_undefined: Cell::new(is_undefined),
value: RefCell::new(match init {
Some(Cow::Owned(v)) => Some(v),
_ => None,
}),
this_sensitive: Cell::new(false),
hoisted: Cell::new(false),
});
idx
}
};
{
let mut cur = Some(&self.scope);
while let Some(scope) = cur {
if let ScopeKind::Fn { .. } = scope.kind {
break;
}
if scope.kind == ScopeKind::Loop {
tracing::trace!("preventing inline as it's declared in a loop");
self.scope.prevent_inline(&id);
break;
}
cur = scope.parent;
}
}
//
let barrier_works = match kind {
VarType::Param => false,
_ if alias_of == Some(VarType::Param) => false,
_ => true,
};
if barrier_works {
if let Some((value_idx, vi)) = value_idx {
tracing::trace!("\tdeclare: {} -> {}", idx, value_idx);
let barrier_exists = (|| {
for &blocker in self.scope.inline_barriers.borrow().iter() {
if (value_idx <= blocker && blocker <= idx)
|| (idx <= blocker && blocker <= value_idx)
{
return true;
}
}
false
})();
if value_idx > idx || barrier_exists {
tracing::trace!("Variable use before declaration: {:?}", id);
self.scope.prevent_inline(&id);
self.scope.prevent_inline(&vi)
}
} else {
tracing::trace!("\tdeclare: value idx is none");
}
}
}
}
#[derive(Debug, Default)]
pub(super) struct Scope<'a> {
pub parent: Option<&'a Scope<'a>>,
pub kind: ScopeKind,
inline_barriers: RefCell<VecDeque<usize>>,
bindings: IndexMap<Id, VarInfo, FxBuildHasher>,
unresolved_usages: FxHashSet<Id>,
/// Simple optimization. We don't need complex scope analysis.
pub constants: FxHashMap<Id, Option<Expr>>,
}
impl<'a> Scope<'a> {
pub fn new(parent: Option<&'a Scope<'a>>, kind: ScopeKind) -> Self {
Self {
parent,
kind,
..Default::default()
}
}
pub fn depth(&self) -> usize {
match self.parent {
None => 0,
Some(p) => p.depth() + 1,
}
}
fn should_prevent_inline_because_of_scope(&self, id: &Id) -> bool {
if self.unresolved_usages.contains(id) {
return true;
}
match self.parent {
None => false,
Some(p) => {
if p.should_prevent_inline_because_of_scope(id) {
return true;
}
if let Some(v) = p.find_binding(id) {
if v.hoisted.get() && v.is_inline_prevented() {
return true;
}
}
false
}
}
}
/// True if the returned scope is self
fn scope_for(&self, id: &Id) -> (&Scope, bool) {
if self.constants.contains_key(id) {
return (self, true);
}
if self.find_binding_from_current(id).is_some() {
return (self, true);
}
match self.parent {
None => (self, true),
Some(p) => {
let (s, _) = p.scope_for(id);
(s, false)
}
}
}
pub fn read_cnt(&self, id: &Id) -> Option<usize> {
if let Some(var) = self.find_binding(id) {
return Some(var.read_cnt.get());
}
None
}
fn read_prevents_inlining(&self, id: &Id) -> bool {
tracing::trace!("read_prevents_inlining({:?})", id);
if let Some(v) = self.find_binding(id) {
match v.kind {
// Reading parameter is ok.
VarType::Param => return false,
VarType::Var(VarDeclKind::Let) | VarType::Var(VarDeclKind::Const) => return false,
_ => {}
}
// If it's already hoisted, it means that it is already processed by child
// scope.
if v.hoisted.get() {
return false;
}
}
{
let mut cur = Some(self);
while let Some(scope) = cur {
let found = scope.find_binding_from_current(id).is_some();
if found {
tracing::trace!("found");
break;
}
tracing::trace!("({}): {}: kind = {:?}", scope.depth(), id.0, scope.kind);
match scope.kind {
ScopeKind::Fn { .. } => {
tracing::trace!(
"{}: variable access from a nested function detected",
id.0
);
return true;
}
ScopeKind::Loop | ScopeKind::Cond => {
return true;
}
_ => {}
}
cur = scope.parent;
}
}
false
}
pub fn add_read(&mut self, id: &Id) {
if self.read_prevents_inlining(id) {
tracing::trace!("prevent inlining because of read: {}", id.0);
self.prevent_inline(id)
}
if id.0 == "arguments" {
self.prevent_inline_of_params();
}
if let Some(var_info) = self.find_binding(id) {
var_info.read_cnt.set(var_info.read_cnt.get() + 1);
if var_info.hoisted.get() {
var_info.inline_prevented.set(true);
}
} else {
tracing::trace!("({}): Unresolved usage.: {:?}", self.depth(), id);
self.unresolved_usages.insert(id.clone());
}
let (scope, is_self) = self.scope_for(id);
if !is_self {
if let Some(var_info) = scope.find_binding_from_current(id) {
var_info.read_from_nested_scope.set(true);
}
}
}
fn write_prevents_inline(&self, id: &Id) -> bool {
tracing::trace!("write_prevents_inline({})", id.0);
{
let mut cur = Some(self);
while let Some(scope) = cur {
let found = scope.find_binding_from_current(id).is_some();
if found {
break;
}
tracing::trace!("({}): {}: kind = {:?}", scope.depth(), id.0, scope.kind);
match scope.kind {
ScopeKind::Fn { .. } => {
tracing::trace!(
"{}: variable access from a nested function detected",
id.0
);
return true;
}
ScopeKind::Loop | ScopeKind::Cond => {
return true;
}
_ => {}
}
cur = scope.parent;
}
}
false
}
pub fn add_write(&mut self, id: &Id, force_no_inline: bool) {
let _tracing = span!(
Level::DEBUG,
"add_write",
force_no_inline = force_no_inline,
id = &*format!("{:?}", id)
)
.entered();
if self.write_prevents_inline(id) {
tracing::trace!("prevent inlining because of write: {}", id.0);
self.prevent_inline(id)
}
if id.0 == "arguments" {
self.prevent_inline_of_params();
}
let (scope, is_self) = self.scope_for(id);
if let Some(var_info) = scope.find_binding_from_current(id) {
var_info.is_undefined.set(false);
if !is_self || force_no_inline {
self.prevent_inline(id)
}
} else if self.has_constant(id) {
// noop
} else {
tracing::trace!(
"({}): Unresolved. (scope = ({})): {:?}",
self.depth(),
scope.depth(),
id
);
self.bindings.insert(
id.clone(),
VarInfo {
kind: VarType::Var(VarDeclKind::Var),
alias_of: None,
read_from_nested_scope: Cell::new(false),
read_cnt: Cell::new(0),
inline_prevented: Cell::new(force_no_inline),
value: RefCell::new(None),
is_undefined: Cell::new(false),
this_sensitive: Cell::new(false),
hoisted: Cell::new(false),
},
);
}
}
pub fn find_binding(&self, id: &Id) -> Option<&VarInfo> {
if let Some(e) = self.find_binding_from_current(id) {
return Some(e);
}
self.parent.and_then(|parent| parent.find_binding(id))
}
/// Searches only for current scope.
fn idx_val(&self, id: &Id) -> Option<(usize, &VarInfo)> {
self.bindings.iter().enumerate().find_map(
|(idx, (k, v))| {
if k == id {
Some((idx, v))
} else {
None
}
},
)
}
pub fn find_binding_from_current(&self, id: &Id) -> Option<&VarInfo> {
let (_, v) = self.idx_val(id)?;
Some(v)
}
fn has_constant(&self, id: &Id) -> bool {
if self.constants.contains_key(id) {
return true;
}
self.parent
.map(|parent| parent.has_constant(id))
.unwrap_or(false)
}
pub fn find_constant(&self, id: &Id) -> Option<&Expr> {
if let Some(Some(e)) = self.constants.get(id) {
return Some(e);
}
self.parent.and_then(|parent| parent.find_constant(id))
}
pub fn mark_this_sensitive(&self, callee: &Expr) {
if let Expr::Ident(ref i) = callee {
if let Some(v) = self.find_binding(&i.to_id()) {
v.this_sensitive.set(true);
}
}
}
pub fn store_inline_barrier(&self, phase: Phase) {
tracing::trace!("store_inline_barrier({:?})", phase);
match phase {
Phase::Analysis => {
let idx = self.bindings.len();
self.inline_barriers.borrow_mut().push_back(idx);
}
Phase::Inlining => {
//if let Some(idx) =
// self.inline_barriers.borrow_mut().pop_front() {
// for i in 0..idx {
// if let Some((id, _)) = self.bindings.get_index(i) {
// self.prevent_inline(id);
// }
// }
//}
}
}
match self.parent {
None => {}
Some(p) => p.store_inline_barrier(phase),
}
}
fn prevent_inline_of_params(&self) {
for (_, v) in self.bindings.iter() {
let v: &VarInfo = v;
if v.is_param() {
v.inline_prevented.set(true);
}
}
if let ScopeKind::Fn { .. } = self.kind {
return;
}
if let Some(p) = self.parent {
p.prevent_inline_of_params()
}
}
pub fn prevent_inline(&self, id: &Id) {
tracing::trace!("({}) Prevent inlining: {:?}", self.depth(), id);
if let Some(v) = self.find_binding_from_current(id) {
v.inline_prevented.set(true);
}
for (_, v) in self.bindings.iter() {
if let Some(Expr::Ident(i)) = v.value.borrow().as_ref() {
if i.sym == id.0 && i.ctxt == id.1 {
v.inline_prevented.set(true);
}
}
}
match self.parent {
None => {}
Some(p) => p.prevent_inline(id),
}
}
pub fn is_inline_prevented(&self, e: &Expr) -> bool {
match e {
Expr::Ident(ref ri) => {
if let Some(v) = self.find_binding_from_current(&ri.to_id()) {
return v.inline_prevented.get();
}
}
Expr::Member(MemberExpr {
obj: right_expr, ..
}) if right_expr.is_ident() => {
let ri = right_expr.as_ident().unwrap();
if let Some(v) = self.find_binding_from_current(&ri.to_id()) {
return v.inline_prevented.get();
}
}
Expr::Update(..) => return true,
// TODO: Remove this
Expr::Paren(..) | Expr::Call(..) | Expr::New(..) => return true,
_ => {}
}
match self.parent {
None => false,
Some(p) => p.is_inline_prevented(e),
}
}
pub fn has_same_this(&self, id: &Id, init: Option<&Expr>) -> bool {
if let Some(v) = self.find_binding(id) {
if v.this_sensitive.get() {
if let Some(&Expr::Member(..)) = init {
return false;
}
}
}
true
}
}
#[derive(Debug)]
pub(super) struct VarInfo {
pub kind: VarType,
alias_of: Option<VarType>,
read_from_nested_scope: Cell<bool>,
read_cnt: Cell<usize>,
inline_prevented: Cell<bool>,
this_sensitive: Cell<bool>,
pub value: RefCell<Option<Expr>>,
pub is_undefined: Cell<bool>,
hoisted: Cell<bool>,
}
impl VarInfo {
pub fn is_param(&self) -> bool {
self.kind == VarType::Param
}
pub fn is_inline_prevented(&self) -> bool {
if self.inline_prevented.get() {
return true;
}
if self.this_sensitive.get() {
if let Some(Expr::Member(..)) = *self.value.borrow() {
return true;
}
}
false
}
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_optimization/src/simplify/mod.rs | Rust | //! Ported from closure compiler.
use swc_common::{
pass::{CompilerPass, Repeat, Repeated},
Mark,
};
use swc_ecma_ast::Pass;
pub use self::{
branch::dead_branch_remover,
expr::{expr_simplifier, Config as ExprSimplifierConfig},
};
mod branch;
pub mod const_propagation;
pub mod dce;
mod expr;
pub mod inlining;
#[derive(Debug, Default)]
pub struct Config {
pub dce: dce::Config,
pub inlining: inlining::Config,
pub expr: ExprSimplifierConfig,
}
/// Performs simplify-expr, inlining, remove-dead-branch and dce until nothing
/// changes.
pub fn simplifier(unresolved_mark: Mark, c: Config) -> impl CompilerPass + Pass + Repeated {
Repeat::new((
expr_simplifier(unresolved_mark, c.expr),
dead_branch_remover(unresolved_mark),
dce::dce(c.dce, unresolved_mark),
))
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_optimization/tests/__swc_snapshots__/src/inline_globals.rs/globals_simple.js | JavaScript | if (true) {}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_optimization/tests/__swc_snapshots__/src/inline_globals.rs/issue_215.js | JavaScript | if (process.env.x === 'development') {}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_optimization/tests/__swc_snapshots__/src/inline_globals.rs/issue_2499_1.js | JavaScript | process.env.x = 'foo';
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_optimization/tests/__swc_snapshots__/src/inline_globals.rs/issue_417_1.js | JavaScript | const test = process.env['x'];
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_optimization/tests/__swc_snapshots__/src/inline_globals.rs/issue_417_2.js | JavaScript | const test = 'FOO';
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_optimization/tests/__swc_snapshots__/src/inline_globals.rs/node_env.js | JavaScript | if ('development' === 'development') {}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_optimization/tests/__swc_snapshots__/src/inline_globals.rs/non_global.js | JavaScript | if (foo.debug) {}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_optimization/tests/__swc_snapshots__/src/json_parse.rs/array.js | JavaScript | const a = JSON.parse('{"b":[1,"b_val",null]}');
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_optimization/tests/__swc_snapshots__/src/json_parse.rs/boolean.js | JavaScript | const a = JSON.parse('{"b":false}');
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_optimization/tests/__swc_snapshots__/src/json_parse.rs/computed_property.js | JavaScript | const a = {
b: "b_val",
["c"]: "c_val"
};
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_optimization/tests/__swc_snapshots__/src/json_parse.rs/empty_object.js | JavaScript | const a = JSON.parse("{}");
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_optimization/tests/__swc_snapshots__/src/json_parse.rs/invalid_numeric_key.js | JavaScript | const a = JSON.parse('{"77777777777777780":"foo"}');
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_optimization/tests/__swc_snapshots__/src/json_parse.rs/min_cost_0.js | JavaScript | const a = JSON.parse('{"b":1,"c":2}');
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_optimization/tests/__swc_snapshots__/src/json_parse.rs/min_cost_15.js | JavaScript | const a = {
b: 1,
c: 2
};
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_optimization/tests/__swc_snapshots__/src/json_parse.rs/nested_array.js | JavaScript | const a = JSON.parse('{"b":[1,["b_val",{"a":1}],null]}');
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_optimization/tests/__swc_snapshots__/src/json_parse.rs/null.js | JavaScript | const a = JSON.parse('{"b":null}');
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_optimization/tests/__swc_snapshots__/src/json_parse.rs/number.js | JavaScript | const a = JSON.parse('{"b":1}');
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_optimization/tests/__swc_snapshots__/src/json_parse.rs/object.js | JavaScript | const a = JSON.parse('{"b":{"c":1}}');
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_optimization/tests/__swc_snapshots__/src/json_parse.rs/object_method.js | JavaScript | const a = {
method (arg) {
return arg;
},
b: 1
};
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_optimization/tests/__swc_snapshots__/src/json_parse.rs/object_numeric_keys.js | JavaScript | const a = JSON.parse('{"1":"123","23":45,"b":"b_val"}');
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_optimization/tests/__swc_snapshots__/src/json_parse.rs/simple_arr.js | JavaScript | let a = JSON.parse('["foo"]');
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_optimization/tests/__swc_snapshots__/src/json_parse.rs/simple_object.js | JavaScript | let a = JSON.parse('{"b":"foo"}');
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_optimization/tests/__swc_snapshots__/src/json_parse.rs/spread.js | JavaScript | const a = {
...a,
b: 1
};
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_optimization/tests/__swc_snapshots__/src/json_parse.rs/string.js | JavaScript | const a = JSON.parse('{"b":"b_val"}');
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_optimization/tests/__swc_snapshots__/src/json_parse.rs/string_single_quote_1.js | JavaScript | const a = JSON.parse('{"b":"\'abc\'"}');
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_optimization/tests/__swc_snapshots__/src/json_parse.rs/string_single_quote_2.js | JavaScript | const a = JSON.parse('{"b":"ab\'c"}');
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_optimization/tests/__swc_snapshots__/src/json_parse.rs/tpl.js | JavaScript | const a = JSON.parse('["\\"!\\"4"]');
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_optimization/tests/__swc_snapshots__/src/json_parse.rs/tpl2.js | JavaScript | const a = [
`1${b}2`
];
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_optimization/tests/__swc_snapshots__/src/json_parse.rs/tpl3.js | JavaScript | const a = [
`1${0}2`
];
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_optimization/tests/__swc_snapshots__/tests/const_modules.rs/complex_multiple.js | JavaScript | if (true) {
console.log('Foo!');
}
let woot;
if (false) {
woot = ()=>'woot';
} else if (true) {
woot = ()=>'toow';
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_optimization/tests/__swc_snapshots__/tests/const_modules.rs/default_import_issue_7601.js | JavaScript | console.log(true);
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_optimization/tests/__swc_snapshots__/tests/const_modules.rs/imports_hoisted.js | JavaScript | if (true) {
console.log('Foo!');
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_optimization/tests/__swc_snapshots__/tests/const_modules.rs/issue_7025.js | JavaScript | ({
'var': 'value'
})['var'];
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_optimization/tests/__swc_snapshots__/tests/const_modules.rs/namespace_import.js | JavaScript | console.log(true);
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_optimization/tests/__swc_snapshots__/tests/const_modules.rs/namespace_import_computed.js | JavaScript | console.log(true);
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_optimization/tests/__swc_snapshots__/tests/const_modules.rs/simple_flags.js | JavaScript | if (true) {
console.log('Foo!');
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_optimization/tests/__swc_snapshots__/tests/const_modules.rs/use_as_object_prop_shorthand.js | JavaScript | console.log({
bar: true
});
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_optimization/tests/__swc_snapshots__/tests/remove_imports_with_side_effects.rs/import_export_named.js | JavaScript | import foo from 'src';
export { foo };
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_optimization/tests/__swc_snapshots__/tests/remove_imports_with_side_effects.rs/import_unused_export_named.js | JavaScript | import foo from 'src';
export { foo };
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_optimization/tests/__swc_snapshots__/tests/remove_imports_with_side_effects.rs/single_pass.js | JavaScript | const a = 1;
if (a) {}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_optimization/tests/__swc_snapshots__/tests/simplify.rs/issue_1156_1.js | JavaScript | function d() {
let methods;
const promise = new Promise((resolve, reject)=>{
methods = {
resolve,
reject
};
});
return Object.assign(promise, methods);
}
class A {
a() {
this.s.resolve();
}
b() {
this.s = d();
}
constructor(){
this.s = d();
}
}
new A();
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_optimization/tests/__swc_snapshots__/tests/simplify.rs/issue_1619_1.js | JavaScript | "use strict";
console.log("\x001");
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_optimization/tests/__swc_snapshots__/tests/simplify.rs/issue_2466_1.js | JavaScript | const X = {
run () {
console.log(this === globalThis);
}
};
X.run();
(0, X.run)();
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_optimization/tests/__swc_snapshots__/tests/simplify.rs/issue_389_3.js | JavaScript | "use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _foo = /*#__PURE__*/ _interop_require_default(require("foo"));
function _interop_require_default(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
_foo.default.bar = true;
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_optimization/tests/__swc_snapshots__/tests/simplify.rs/issue_4173.js | JavaScript | function emit(type) {
const e = events[type];
if (Array.isArray(e)) for(let i = 0; i < e.length; i += 1)e[i].apply(this);
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_optimization/tests/__swc_snapshots__/tests/simplify.rs/issue_4272.js | JavaScript | function oe() {
var e, t;
return t !== i && (e, t), e = t;
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_optimization/tests/__swc_snapshots__/tests/simplify.rs/multi_run.js | JavaScript | console.log(3); // Prevent optimizing out.
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_optimization/tests/__swc_snapshots__/tests/simplify.rs/single_pass.js | JavaScript | const a = 1;
a;
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_optimization/tests/__swc_snapshots__/tests/simplify_dce.rs/assign_op.js | JavaScript | x *= 2;
use(x);
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_optimization/tests/__swc_snapshots__/tests/simplify_dce.rs/custom_loop_2.js | JavaScript | 2;
let c;
if (2) c = 3;
console.log(c);
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_optimization/tests/__swc_snapshots__/tests/simplify_dce.rs/deno_8736_1.js | JavaScript | class DenoStdInternalError1 extends Error {
constructor(message){
super(message);
this.name = 'DenoStdInternalError';
}
}
const DenoStdInternalError = DenoStdInternalError1;
function assert2(expr, msg = '') {
if (!expr) {
throw new DenoStdInternalError(msg);
}
}
const assert1 = assert2;
const assert = assert1;
const TEST = Deno.env.get('TEST');
assert(TEST, 'TEST must be defined!');
console.log(`Test is ${TEST}`);
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_optimization/tests/__swc_snapshots__/tests/simplify_dce.rs/deno_8736_2.js | JavaScript | class DenoStdInternalError extends Error {
constructor(message){
super(message);
this.name = 'DenoStdInternalError';
}
}
function assert(expr, msg = '') {
throw new DenoStdInternalError(msg);
}
const TEST = Deno.env.get('TEST');
assert(TEST, 'TEST must be defined!');
console.log(`Test is ${TEST}`);
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_optimization/tests/__swc_snapshots__/tests/simplify_dce.rs/deno_9076.js | JavaScript | class App {
constructor(){
console.log('Hello from app');
}
}
new App;
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_optimization/tests/__swc_snapshots__/tests/simplify_dce.rs/deno_9121_3.js | JavaScript | function wt(e, n, t, r) {
var l = e.updateQueue;
Fe = !1;
var i = l.firstBaseUpdate, o = l.lastBaseUpdate, u = l.shared.pending;
if (u !== null) {
l.shared.pending = null;
var s = u, d = s.next;
s.next = null, o === null ? i = d : o.next = d, o = s;
var y = e.alternate;
if (y !== null) {
y = y.updateQueue;
var _ = y.lastBaseUpdate;
_ !== o && (_ === null ? y.firstBaseUpdate = d : _.next = d, y.lastBaseUpdate = s);
}
}
if (i !== null) {
_ = l.baseState, o = 0, y = d = s = null;
do {
u = i.lane;
var h = i.eventTime;
if ((r & u) === u) {
y !== null && (y = y.next = {
eventTime: h,
lane: 0,
tag: i.tag,
payload: i.payload,
callback: i.callback,
next: null
});
e: {
var k = e, E = i;
switch(u = n, h = t, E.tag){
case 1:
if (k = E.payload, typeof k == 'function') {
_ = k.call(h, _, u);
break e;
}
_ = k;
break e;
case 3:
k.flags = k.flags & -4097 | 64;
case 0:
if (k = E.payload, u = typeof k == 'function' ? k.call(h, _, u) : k, u == null) break e;
_ = R({}, _, u);
break e;
case 2:
Fe = !0;
}
}
i.callback !== null && (e.flags |= 32, u = l.effects, u === null ? l.effects = [
i
] : u.push(i));
} else h = {
eventTime: h,
lane: u,
tag: i.tag,
payload: i.payload,
callback: i.callback,
next: null
}, y === null ? (d = y = h, s = _) : y = y.next = h, o |= u;
if (i = i.next, i === null) {
if (u = l.shared.pending, u === null) break;
i = u.next, u.next = null, l.lastBaseUpdate = u, l.shared.pending = null;
}
}while (1)
y === null && (s = _), l.baseState = s, l.firstBaseUpdate = d, l.lastBaseUpdate = y, gt |= o, e.lanes = o, e.memoizedState = _;
}
}
wt();
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_optimization/tests/__swc_snapshots__/tests/simplify_dce.rs/deno_9212_1.js | JavaScript | var _ = [];
_ = l.baseState;
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_optimization/tests/__swc_snapshots__/tests/simplify_dce.rs/deno_9212_2.js | JavaScript | if (u !== null) {
if (y !== null) {
var _ = y.lastBaseUpdate;
}
}
if (i !== null) {
_ = l.baseState;
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_optimization/tests/__swc_snapshots__/tests/simplify_dce.rs/export_named.js | JavaScript | export { x };
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_optimization/tests/__swc_snapshots__/tests/simplify_dce.rs/export_named_from.js | JavaScript | export { foo } from 'src';
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_optimization/tests/__swc_snapshots__/tests/simplify_dce.rs/import_default_export_named.js | JavaScript | import foo from 'src';
export { foo };
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_optimization/tests/__swc_snapshots__/tests/simplify_dce.rs/import_default_unused.js | JavaScript | import 'foo';
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_optimization/tests/__swc_snapshots__/tests/simplify_dce.rs/import_mixed_unused.js | JavaScript | import 'foo';
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_optimization/tests/__swc_snapshots__/tests/simplify_dce.rs/import_specific_unused.js | JavaScript | import 'foo';
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_optimization/tests/__swc_snapshots__/tests/simplify_dce.rs/import_unused_export_named.js | JavaScript | import foo from 'src';
export { foo };
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_optimization/tests/__swc_snapshots__/tests/simplify_dce.rs/issue_1111.js | JavaScript | const a = 1;
export const d = {
a
};
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_optimization/tests/__swc_snapshots__/tests/simplify_dce.rs/issue_1150_1.js | JavaScript | class A {
constructor(o = {}){
const { a = defaultA, c } = o;
this.#a = a;
this.#c = c;
}
a() {
this.#a();
}
c() {
console.log(this.#c);
}
}
new A();
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_optimization/tests/__swc_snapshots__/tests/simplify_dce.rs/issue_1156_1.js | JavaScript | export function d() {
let methods;
const promise = new Promise((resolve, reject)=>{
methods = {
resolve,
reject
};
});
return Object.assign(promise, methods);
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_optimization/tests/__swc_snapshots__/tests/simplify_dce.rs/issue_1156_2.js | JavaScript | function d() {
let methods;
const promise = new Promise((resolve, reject)=>{
methods = {
resolve,
reject
};
});
return Object.assign(promise, methods);
}
class A {
a() {
this.s.resolve();
}
b() {
this.s = d();
}
constructor(){
this.s = d();
}
}
new A();
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_optimization/tests/__swc_snapshots__/tests/simplify_dce.rs/issue_1156_3.js | JavaScript | function d() {
let methods;
const promise = new Promise((resolve, reject)=>{
methods = {
resolve,
reject
};
});
return Object.assign(promise, methods);
}
d();
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_optimization/tests/__swc_snapshots__/tests/simplify_dce.rs/issue_1156_4.js | JavaScript | function d() {
let methods;
const promise = new Promise((resolve, reject)=>{
methods = {
resolve,
reject
};
});
return Object.assign(promise, methods);
}
class A {
a() {
this.s.resolve();
}
constructor(){
this.s = d();
}
}
new A();
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_optimization/tests/__swc_snapshots__/tests/simplify_dce.rs/issue_760_1.js | JavaScript | var ref;
export const Auth = window === null || window === void 0 ? void 0 : (ref = window.aws) === null || ref === void 0 ? void 0 : ref.Auth;
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_optimization/tests/__swc_snapshots__/tests/simplify_dce.rs/issue_760_2_export_default.js | JavaScript | const initialState = 'foo';
export default function reducer(state = initialState, action = {}) {}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_optimization/tests/__swc_snapshots__/tests/simplify_dce.rs/issue_760_2_export_named.js | JavaScript | const initialState = 'foo';
export function reducer(state = initialState, action = {}) {}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_optimization/tests/__swc_snapshots__/tests/simplify_dce.rs/issue_763_1.js | JavaScript | import { RESOURCE_FACEBOOK, RESOURCE_INSTAGRAM, RESOURCE_WEBSITE } from '../../../../consts';
export const resources = [
{
value: RESOURCE_WEBSITE,
label: 'Webové stránky'
},
{
value: RESOURCE_FACEBOOK,
label: 'Facebook'
},
{
value: RESOURCE_INSTAGRAM,
label: 'Instagram'
}
];
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_optimization/tests/__swc_snapshots__/tests/simplify_dce.rs/issue_763_2.js | JavaScript | import { RESOURCE_FACEBOOK, RESOURCE_INSTAGRAM, RESOURCE_WEBSITE } from '../../../../consts';
const resources = [
{
value: RESOURCE_WEBSITE,
label: 'Webové stránky'
},
{
value: RESOURCE_FACEBOOK,
label: 'Facebook'
},
{
value: RESOURCE_INSTAGRAM,
label: 'Instagram'
}
];
resources.map(console.log.bind(console));
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_optimization/tests/__swc_snapshots__/tests/simplify_dce.rs/issue_763_3.js | JavaScript | import { RESOURCE_FACEBOOK, RESOURCE_INSTAGRAM, RESOURCE_WEBSITE } from '../../../../consts';
const resources = [
{
value: RESOURCE_WEBSITE,
label: 'Webové stránky'
},
{
value: RESOURCE_FACEBOOK,
label: 'Facebook'
},
{
value: RESOURCE_INSTAGRAM,
label: 'Instagram'
}
];
resources.map((v)=>v);
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_optimization/tests/__swc_snapshots__/tests/simplify_dce.rs/issue_763_4.js | JavaScript | import { RESOURCE_FACEBOOK, RESOURCE_INSTAGRAM, RESOURCE_WEBSITE } from './consts';
const resources = [
{
value: RESOURCE_WEBSITE,
label: 'Webové stránky'
},
{
value: RESOURCE_FACEBOOK,
label: 'Facebook'
},
{
value: RESOURCE_INSTAGRAM,
label: 'Instagram'
}
];
export function foo(websites) {
const a = resources.map((resource)=>({
value: resource.value
}));
const b = website.type_id === RESOURCE_INSTAGRAM ? 'text' : 'url';
return a + b;
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_optimization/tests/__swc_snapshots__/tests/simplify_dce.rs/issue_763_5_1.js | JavaScript | import { A, B } from './consts';
const resources = [
A,
B
];
use(B);
resources.map((v)=>v);
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_optimization/tests/__swc_snapshots__/tests/simplify_dce.rs/issue_763_5_2.js | JavaScript | import { A, B } from './consts';
const resources = {
A,
B
};
use(B);
resources.map((v)=>v);
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_optimization/tests/__swc_snapshots__/tests/simplify_dce.rs/issue_898_1.js | JavaScript | export default class X {
@whatever
anything = 0;
x() {
const localVar = aFunctionSomewhere();
return localVar;
}
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_optimization/tests/__swc_snapshots__/tests/simplify_dce.rs/issue_898_2.js | JavaScript | export default class X {
anything = 0;
x() {
const localVar = aFunctionSomewhere();
return localVar;
}
}
_ts_decorate([
whatever
], X.prototype, "anything", void 0);
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_optimization/tests/__swc_snapshots__/tests/simplify_dce.rs/noop_1.js | JavaScript | let b = 2;
let a = 1;
if (b) {
a = 2;
}
let c;
if (a) {
c = 3;
}
console.log(c);
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_optimization/tests/__swc_snapshots__/tests/simplify_dce.rs/noop_2.js | JavaScript | switch(1){
case 1:
a = '1';
}
console.log(a);
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_optimization/tests/__swc_snapshots__/tests/simplify_dce.rs/noop_3.js | JavaScript | try {
console.log(foo());
} catch (e) {
console.error(e);
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_optimization/tests/__swc_snapshots__/tests/simplify_dce.rs/single_pass.js | JavaScript | const a = 1;
if (a) {}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_optimization/tests/__swc_snapshots__/tests/simplify_dce.rs/spack_issue_004.js | JavaScript | const BAR = 'bar';
export default BAR;
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_optimization/tests/__swc_snapshots__/tests/simplify_dce.rs/spack_issue_005.js | JavaScript | function a() {}
function foo() {}
console.log(a(), foo());
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_optimization/tests/__swc_snapshots__/tests/simplify_dce.rs/spack_issue_006.js | JavaScript | import * as a from './a';
function foo() {}
console.log(foo(), a.a(), a.foo());
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_optimization/tests/__swc_snapshots__/tests/simplify_dce.rs/spack_issue_007.js | JavaScript | var load = function() {};
var { progress } = load();
console.log(progress);
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_transforms_optimization/tests/__swc_snapshots__/tests/simplify_dce.rs/spack_issue_008.js | JavaScript | class B {
}
class A extends B {
}
console.log('foo');
new A();
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.