Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions crates/oxc_ast/src/ast_impl/js.rs
Original file line number Diff line number Diff line change
Expand Up @@ -983,6 +983,21 @@ impl<'a> AssignmentTargetMaybeDefault<'a> {
_ => None,
}
}

/// Returns mut identifier bound by this assignment target.
pub fn identifier_mut(&mut self) -> Option<&mut IdentifierReference<'a>> {
match self {
AssignmentTargetMaybeDefault::AssignmentTargetIdentifier(id) => Some(id),
Self::AssignmentTargetWithDefault(target) => {
if let AssignmentTarget::AssignmentTargetIdentifier(id) = &mut target.binding {
Some(id)
} else {
None
}
}
_ => None,
}
}
}

impl Statement<'_> {
Expand Down
32 changes: 28 additions & 4 deletions crates/oxc_minifier/src/ctx.rs
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,9 @@ impl<'a> oxc_ecmascript::is_global_reference::IsGlobalReference<'a> for Ctx<'a,
self.scoping()
.get_reference(reference_id)
.symbol_id()
.and_then(|symbol_id| self.state.symbol_values.get_constant_value(symbol_id))
.and_then(|symbol_id| self.state.symbol_values.get_symbol_value(symbol_id))
.filter(|sv| sv.write_references_count == 0)
.and_then(|sv| sv.initialized_constant.as_ref())
.cloned()
}
}
Expand Down Expand Up @@ -164,7 +166,23 @@ impl<'a> Ctx<'a, '_> {
false
}

pub fn init_value(&mut self, symbol_id: SymbolId, constant: ConstantValue<'a>) {
pub fn init_value(&mut self, symbol_id: SymbolId, constant: Option<ConstantValue<'a>>) {
let mut exported = false;
if self.scoping.current_scope_id() == self.scoping().root_scope_id() {
for ancestor in self.ancestors() {
if ancestor.is_export_named_declaration()
|| ancestor.is_export_all_declaration()
|| ancestor.is_export_default_declaration()
{
exported = true;
}
}
}

let for_statement_init = self.ancestors().nth(1).is_some_and(|ancestor| {
ancestor.is_parent_of_for_statement_init() || ancestor.is_parent_of_for_statement_left()
});

let mut read_references_count = 0;
let mut write_references_count = 0;
for r in self.scoping().get_resolved_references(symbol_id) {
Expand All @@ -177,8 +195,14 @@ impl<'a> Ctx<'a, '_> {
}

let scope_id = self.scoping.current_scope_id();
let symbol_value =
SymbolValue { constant, read_references_count, write_references_count, scope_id };
let symbol_value = SymbolValue {
initialized_constant: constant,
exported,
for_statement_init,
read_references_count,
write_references_count,
scope_id,
};
self.state.symbol_values.init_value(symbol_id, symbol_value);
}

Expand Down
15 changes: 10 additions & 5 deletions crates/oxc_minifier/src/peephole/inline.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use oxc_ast::ast::*;
use oxc_ecmascript::constant_evaluation::ConstantEvaluation;
use oxc_ecmascript::constant_evaluation::{ConstantEvaluation, ConstantValue};
use oxc_span::GetSpan;

use crate::ctx::Ctx;
Expand All @@ -10,11 +10,12 @@ impl<'a> PeepholeOptimizations {
pub fn init_symbol_value(&self, decl: &VariableDeclarator<'a>, ctx: &mut Ctx<'a, '_>) {
let BindingPatternKind::BindingIdentifier(ident) = &decl.id.kind else { return };
let Some(symbol_id) = ident.symbol_id.get() else { return };
// Skip if not `const` variable.
if !ctx.scoping().symbol_flags(symbol_id).is_const_variable() {
// Skip for `var` declarations, due to TDZ problems.
if decl.kind.is_var() {
return;
}
let Some(value) = decl.init.evaluate_value(ctx) else { return };
let value =
decl.init.as_ref().map_or(Some(ConstantValue::Undefined), |e| e.evaluate_value(ctx));
ctx.init_value(symbol_id, value);
}

Expand All @@ -33,7 +34,11 @@ impl<'a> PeepholeOptimizations {
if symbol_value.write_references_count > 0 {
return;
}
*expr = ctx.value_to_expr(expr.span(), symbol_value.constant.clone());
if symbol_value.for_statement_init {
return;
}
let Some(cv) = &symbol_value.initialized_constant else { return };
*expr = ctx.value_to_expr(expr.span(), cv.clone());
ctx.state.changed = true;
}
}
Expand Down
3 changes: 2 additions & 1 deletion crates/oxc_minifier/src/peephole/minimize_conditions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -526,8 +526,9 @@ mod test {
// In the following test case, we can't remove the duplicate "alert(x);" lines since each "x"
// refers to a different variable.
// We only try removing duplicate statements if the AST is normalized and names are unique.
test_same(
test(
"if (Math.random() < 0.5) { let x = 3; alert(x); } else { let x = 5; alert(x); }",
"if (Math.random() < 0.5) { let x = 3; alert(3); } else { let x = 5; alert(5); }",
);
}

Expand Down
3 changes: 2 additions & 1 deletion crates/oxc_minifier/src/peephole/normalize.rs
Original file line number Diff line number Diff line change
Expand Up @@ -454,7 +454,8 @@ mod test {
#[test]
fn fold_number_nan() {
test("foo(Number.NaN)", "foo(NaN)");
test_same("let Number; foo(Number.NaN)");
test_same("var Number; foo(Number.NaN)");
test_same("let Number; foo((void 0).NaN)");
}

#[test]
Expand Down
112 changes: 69 additions & 43 deletions crates/oxc_minifier/src/peephole/remove_unused_variable_declaration.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use oxc_allocator::TakeIn;
use oxc_ast::ast::*;

use crate::{CompressOptionsUnused, ctx::Ctx};
Expand Down Expand Up @@ -88,37 +89,47 @@ impl<'a> PeepholeOptimizations {

pub fn remove_unused_assignment_expression(
&self,
_e: &mut Expression<'a>,
_ctx: &mut Ctx<'a, '_>,
e: &mut Expression<'a>,
ctx: &mut Ctx<'a, '_>,
) -> bool {
// let Expression::AssignmentExpression(assign_expr) = e else { return false };
// if matches!(
// ctx.state.options.unused,
// CompressOptionsUnused::Keep | CompressOptionsUnused::KeepAssign
// ) {
// return false;
// }
// let Some(SimpleAssignmentTarget::AssignmentTargetIdentifier(ident)) =
// assign_expr.left.as_simple_assignment_target()
// else {
// return false;
// };
// if Self::keep_top_level_var_in_script_mode(ctx) {
// return false;
// }
// let Some(reference_id) = ident.reference_id.get() else { return false };
// let Some(symbol_id) = ctx.scoping().get_reference(reference_id).symbol_id() else {
// return false;
// };
// // Keep error for assigning to `const foo = 1; foo = 2`.
// if ctx.scoping().symbol_flags(symbol_id).is_const_variable() {
// return false;
// }
// if !ctx.scoping().get_resolved_references(symbol_id).all(|r| !r.flags().is_read()) {
// return false;
// }
// *e = assign_expr.right.take_in(ctx.ast);
// state.changed = true;
let Expression::AssignmentExpression(assign_expr) = e else { return false };
if matches!(
ctx.state.options.unused,
CompressOptionsUnused::Keep | CompressOptionsUnused::KeepAssign
) {
return false;
}
let Some(SimpleAssignmentTarget::AssignmentTargetIdentifier(ident)) =
assign_expr.left.as_simple_assignment_target()
else {
return false;
};
if Self::keep_top_level_var_in_script_mode(ctx) {
return false;
}
let Some(reference_id) = ident.reference_id.get() else { return false };
let Some(symbol_id) = ctx.scoping().get_reference(reference_id).symbol_id() else {
return false;
};
// Keep error for assigning to `const foo = 1; foo = 2`.
if ctx.scoping().symbol_flags(symbol_id).is_const_variable() {
return false;
}
let Some(symbol_value) = ctx.state.symbol_values.get_symbol_value(symbol_id) else {
return false;
};
// Cannot remove assignment to live bindings: `export let foo; foo = 1;`.
if symbol_value.exported {
return false;
}
if symbol_value.read_references_count > 0 {
return false;
}
if symbol_value.for_statement_init {
return false;
}
*e = assign_expr.right.take_in(ctx.ast);
ctx.state.changed = true;
false
}

Expand Down Expand Up @@ -180,33 +191,48 @@ mod test {
}

#[test]
#[ignore]
fn remove_unused_assignment_expression() {
let options = CompressOptions::smallest();
test_options("var x = 1; x = 2;", "", &options);
test_options("var x = 1; x = 2;", "", &options);
test_options("var x = 1; x = foo();", "foo()", &options);
test_same_options("export let foo; foo = 0;", &options);
// Vars are not handled yet due to TDZ.
test_same_options("var x = 1; x = 2;", &options);
test_same_options("var x = 1; x = foo();", &options);
test_same_options("export var foo; foo = 0;", &options);
test_same_options("var x = 1; x = 2, foo(x)", &options);
test_same_options("function foo() { return t = x(); } foo();", &options);
test_same_options("function foo() { var t; return t = x(); } foo();", &options);
test_same_options("function foo(t) { return t = x(); } foo();", &options);

test_options("let x = 1; x = 2;", "", &options);
test_options("let x = 1; x = foo();", "foo()", &options);
test_same_options("export let foo; foo = 0;", &options);
test_same_options("let x = 1; x = 2, foo(x)", &options);
test_same_options("function foo() { return t = x(); } foo();", &options);
test_options(
"function foo() { var t; return t = x(); } foo();",
"function foo() { return x(); } foo();",
"function foo() { let t; return t = x(); } foo();",
"function foo() { return x() } foo()",
&options,
);
test_options(
"function foo(t) { return t = x(); } foo();",
"function foo(t) { return x(); } foo();",
test_same_options("function foo(t) { return t = x(); } foo();", &options);

test_same_options("for(let i;;) foo(i)", &options);
test_same_options("for(let i in []) foo(i)", &options);

test_options("var a; ({ a: a } = {})", "var a; ({ a } = {})", &options);
test_options("var a; b = ({ a: a })", "var a; b = ({ a })", &options);

test_options("let foo = {}; foo = 1", "", &options);

test_same_options(
"let bracketed = !1; for(;;) bracketed = !bracketed, log(bracketed)",
&options,
);

let options = CompressOptions::smallest();
let source_type = SourceType::cjs();
test_same_options_source_type("var x = 1; x = 2;", source_type, &options);
test_same_options_source_type("var x = 1; x = 2, foo(x)", source_type, &options);
test_options_source_type(
"function foo() { var x = 1; x = 2; bar() } foo()",
"function foo() { bar() } foo()",
test_same_options_source_type(
"function foo() { var x = 1; x = 2, bar() } foo()",
source_type,
&options,
);
Expand Down
Loading
Loading